@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.
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 -295
  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
@@ -0,0 +1,903 @@
1
+ import { babel } from "./babel.js"
2
+
3
+ const {
4
+ tt, tokenIsIdentifier, tokenIsKeywordOrIdentifier, tokenCanStartExpression, tokenOperatorPrecedence, functionFlags, ExpressionErrors
5
+ } = babel.internals
6
+
7
+ const LEXICAL = 8201
8
+ const FUNCTION_SCOPE = 514
9
+
10
+ const PREFIX_OPERATORS = new Set(["sizeof", "kindof", "empty", "copyof", "lock"])
11
+ const NOT_AN_OPERAND = new Set(["in", "of", "instanceof", "as", "from"])
12
+ const DECLARATION_WORDS = new Set(["struct", "enum", "func", "component"])
13
+
14
+ const VOID_ELEMENTS = new Set([
15
+ "area", "base", "br", "col", "embed", "hr", "img", "input",
16
+ "link", "meta", "param", "source", "track", "wbr"
17
+ ])
18
+ const RAW_TEXT_ELEMENTS = new Set(["script", "style", "textarea", "title"])
19
+ const STATEMENT_WORDS = ["if", "for", "while", "do", "switch", "return", "const", "let", "var", "throw", "try"]
20
+ const UNTERMINATED = new Set(["UnterminatedRegExp", "UnterminatedString", "UnterminatedTemplate", "UnterminatedComment"])
21
+
22
+ const isLetter = c => (c >= "a" && c <= "z") || (c >= "A" && c <= "Z")
23
+ const isTagChar = c => isLetter(c) || (c >= "0" && c <= "9") || c === "-" || c === "_" || c === ":" || c === "."
24
+ const isBlank = c => c === " " || c === "\t" || c === "\r" || c === "\n"
25
+ const hasLineBreak = text => /[\n\r\u2028\u2029]/.test(text)
26
+
27
+ function lineColumn(input, pos) {
28
+ let line = 1
29
+ let lineStart = 0
30
+ for (let i = 0; i < pos; i++) {
31
+ if (input[i] === "\n") {
32
+ line++
33
+ lineStart = i + 1
34
+ }
35
+ }
36
+ return { line, column: pos - lineStart }
37
+ }
38
+
39
+ export function slimSyntaxError(input, pos, message) {
40
+ const { line, column } = lineColumn(input, pos)
41
+ const error = new SyntaxError(`${message} (${line}:${column})`)
42
+ error.loc = { line, column, index: pos }
43
+ error.pos = pos
44
+ error.code = "BABEL_PARSER_SYNTAX_ERROR"
45
+ error.reasonCode = "SlimSyntaxError"
46
+ error.slimMessage = message
47
+ return error
48
+ }
49
+
50
+ const slim = superClass => class SlimParser extends superClass {
51
+
52
+ isWord(word) {
53
+ return tokenIsKeywordOrIdentifier(this.state.type) && this.state.value === word && !this.state.containsEsc
54
+ }
55
+
56
+ tokenIsWord(token, word) {
57
+ return tokenIsKeywordOrIdentifier(token.type) && token.value === word
58
+ }
59
+
60
+ expectWord(word) {
61
+ if (!this.isWord(word)) this.slimFail(`Expected "${word}"`)
62
+ this.next()
63
+ }
64
+
65
+ slimFail(message, pos = this.state.start) {
66
+ throw slimSyntaxError(this.input, pos, message)
67
+ }
68
+
69
+ sameLine(token) {
70
+ return !hasLineBreak(this.input.slice(this.state.end, token.start))
71
+ }
72
+
73
+ charAfterSpaces(pos) {
74
+ while (pos < this.input.length && (this.input[pos] === " " || this.input[pos] === "\t")) pos++
75
+ return this.input[pos] ?? ""
76
+ }
77
+
78
+ slimParseType() {
79
+ return this.tsInType(() => this.tsParseType())
80
+ }
81
+
82
+ slimMoveTo(target) {
83
+ const input = this.input
84
+ for (let i = this.state.pos; i < target; i++) {
85
+ const c = input.charCodeAt(i)
86
+ if (c === 10 || c === 8232 || c === 8233 || (c === 13 && input.charCodeAt(i + 1) !== 10)) {
87
+ this.state.curLine++
88
+ this.state.lineStart = i + 1
89
+ }
90
+ }
91
+ this.state.pos = target
92
+ }
93
+
94
+ slimResumeAt(pos) {
95
+ this.slimMoveTo(pos)
96
+ this.state.end = pos
97
+ this.state.endLoc = this.state.curPosition()
98
+ this.next()
99
+ }
100
+
101
+ slimLooksLikeFunctionHeader(parenPos) {
102
+ const input = this.input
103
+ let depth = 0
104
+ let i = parenPos
105
+ for (; i < input.length; i++) {
106
+ const c = input[i]
107
+ if (c === '"' || c === "'" || c === "`") {
108
+ i++
109
+ while (i < input.length && input[i] !== c) i += input[i] === "\\" ? 2 : 1
110
+ } else if (c === "(") depth++
111
+ else if (c === ")" && --depth === 0) break
112
+ }
113
+ const next = this.charAfterSpaces(i + 1)
114
+ return next === "{" || next === ":" || (next === "-" && input[input.indexOf("-", i + 1) + 1] === ">")
115
+ }
116
+
117
+
118
+ parseStatementContent(flags, decorators) {
119
+ return this.parseSlimStatement() ?? super.parseStatementContent(flags, decorators)
120
+ }
121
+
122
+ shouldParseExportDeclaration() {
123
+ return this.slimDeclarationAhead() || super.shouldParseExportDeclaration()
124
+ }
125
+
126
+ parseExportDeclaration(node) {
127
+ return this.parseSlimStatement() ?? super.parseExportDeclaration(node)
128
+ }
129
+
130
+ parseExportDefaultExpression() {
131
+ if (this.match(tt._const) || this.match(tt._var) || this.isWord("let")) {
132
+ return this.parseVarStatement(this.startNode(), this.state.value)
133
+ }
134
+ return super.parseExportDefaultExpression()
135
+ }
136
+
137
+ slimDeclarationAhead() {
138
+ if (this.state.containsEsc || !tokenIsKeywordOrIdentifier(this.state.type)) return false
139
+ const word = this.state.value
140
+ const next = this.lookahead()
141
+
142
+ if (DECLARATION_WORDS.has(word) || word === "type" || word === "state") return tokenIsIdentifier(next.type)
143
+ if (word === "isolated" || word === "element") return this.tokenIsWord(next, "component") || next.type === tt.parenL
144
+ if (word === "async") return this.tokenIsWord(next, "func")
145
+ return false
146
+ }
147
+
148
+ parseSlimStatement() {
149
+ if (this.state.containsEsc || !tokenIsKeywordOrIdentifier(this.state.type)) return null
150
+
151
+ const word = this.state.value
152
+ const next = this.lookahead()
153
+
154
+ switch (word) {
155
+ case "struct":
156
+ if (tokenIsIdentifier(next.type)) return this.parseSlimStruct(this.startNode())
157
+ break
158
+ case "enum":
159
+ if (tokenIsIdentifier(next.type)) return this.parseSlimEnum(this.startNode())
160
+ break
161
+ case "type": {
162
+ const after = this.charAfterSpaces(next.end)
163
+ const isAlias = after === "=" && this.input[this.input.indexOf("=", next.end) + 1] !== "="
164
+ if (tokenIsIdentifier(next.type) && (isAlias || after === "(")) return this.parseSlimType(this.startNode())
165
+ break
166
+ }
167
+ case "func":
168
+ if (tokenIsIdentifier(next.type)) return this.parseSlimFunc(this.startNode(), false)
169
+ break
170
+ case "async":
171
+ if (this.tokenIsWord(next, "func")) return this.parseSlimFunc(this.startNode(), true)
172
+ if (tokenIsIdentifier(next.type) && this.charAfterSpaces(next.end) === "(" &&
173
+ this.slimLooksLikeFunctionHeader(this.input.indexOf("(", next.end))) {
174
+ return this.slimTryShorthandFunction(true)
175
+ }
176
+ break
177
+ case "component":
178
+ if (tokenIsIdentifier(next.type)) return this.parseSlimComponent(this.startNode())
179
+ break
180
+ case "isolated":
181
+ case "element":
182
+ if (this.tokenIsWord(next, "component") || (word === "element" && next.type === tt.parenL)) {
183
+ return this.slimTry(() => this.parseSlimComponent(this.startNode()))
184
+ }
185
+ break
186
+ case "use":
187
+ if (next.type === tt.string || next.type === tt.at) return this.parseSlimUse(this.startNode())
188
+ if (this.sameLine(next) && (next.type === tt.braceL || next.type === tt.star || tokenIsIdentifier(next.type))) {
189
+ return this.slimTry(() => this.parseSlimUse(this.startNode()))
190
+ }
191
+ break
192
+ case "lock":
193
+ if (next.type === tt._const) return this.parseSlimLockConst(this.startNode())
194
+ break
195
+ case "state":
196
+ if (tokenIsIdentifier(next.type) && this.sameLine(next)) {
197
+ const declaration = this.parseVarStatement(this.startNode(), "let")
198
+ declaration.slimState = true
199
+ return declaration
200
+ }
201
+ break
202
+ case "mode":
203
+ if (next.type === tt.string && this.sameLine(next)) return this.parseSlimMode(this.startNode())
204
+ break
205
+ }
206
+
207
+ if (tokenIsIdentifier(this.state.type) && next.type === tt.parenL && this.sameLine(next) &&
208
+ this.slimLooksLikeFunctionHeader(next.start)) {
209
+ return this.slimTryShorthandFunction(false)
210
+ }
211
+ return null
212
+ }
213
+
214
+ slimTry(fn) {
215
+ const result = this.tryParse(fn)
216
+ if (result.error || result.aborted) return null
217
+ return result.node
218
+ }
219
+
220
+ slimTryShorthandFunction(isAsync) {
221
+ return this.slimTry(() => {
222
+ const node = this.startNode()
223
+ if (isAsync) this.next()
224
+ const fn = this.parseFunction(node, 1 | (isAsync ? 8 : 0))
225
+ this.addExtra(fn, "slimShorthand", true)
226
+ return fn
227
+ })
228
+ }
229
+
230
+ parseSlimFunc(node, isAsync) {
231
+ if (isAsync) this.next()
232
+ this.next()
233
+ const fn = this.parseFunction(node, 1 | (isAsync ? 8 : 0))
234
+ this.addExtra(fn, "slimFunc", true)
235
+ return fn
236
+ }
237
+
238
+ parseSlimStruct(node) {
239
+ this.next()
240
+ node.id = this.parseIdentifier()
241
+ this.checkLVal(node.id, { type: "VariableDeclarator" }, LEXICAL)
242
+
243
+ node.typeParameters = []
244
+ if (this.eat(tt.lt)) {
245
+ do node.typeParameters.push(this.parseIdentifier())
246
+ while (this.eat(tt.comma))
247
+ this.expect(tt.gt)
248
+ }
249
+
250
+ node.superName = this.eat(tt._extends) ? this.parseIdentifier() : null
251
+ node.fields = []
252
+ node.methods = []
253
+
254
+ this.expect(tt.braceL)
255
+ while (!this.eat(tt.braceR)) {
256
+ if (this.eat(tt.comma) || this.eat(tt.semi)) continue
257
+ if (this.match(tt.eof)) this.slimFail(`Unclosed struct ${node.id.name}`)
258
+ this.parseSlimStructMember(node)
259
+ }
260
+ return this.finishNode(node, "SlimStructDeclaration")
261
+ }
262
+
263
+ parseSlimStructMember(struct) {
264
+ const next = this.lookahead()
265
+
266
+ if (tokenIsKeywordOrIdentifier(this.state.type) && next.type === tt.parenL) {
267
+ const method = this.startNode()
268
+ method.key = this.parseIdentifier(true)
269
+ method.computed = false
270
+ method.kind = "method"
271
+ method.method = true
272
+ struct.methods.push(this.parseMethod(method, false, false, false, false, "ObjectMethod"))
273
+ return
274
+ }
275
+
276
+ const field = this.startNode()
277
+ field.readonly = false
278
+ if (this.isWord("readonly") && (tokenIsKeywordOrIdentifier(next.type) || next.type === tt.star) &&
279
+ next.type !== tt.colon) {
280
+ this.next()
281
+ field.readonly = true
282
+ }
283
+ field.optional = this.eat(tt.star)
284
+ field.key = this.parseIdentifier(true)
285
+ if (this.eat(tt.question)) field.optional = true
286
+ this.expect(tt.colon)
287
+ field.typeAnnotation = this.slimParseType()
288
+ field.value = this.eat(tt.eq) ? this.parseMaybeAssignAllowIn() : null
289
+
290
+ if (!this.match(tt.braceR) && !this.match(tt.comma) && !this.match(tt.semi) && !this.hasPrecedingLineBreak()) {
291
+ this.unexpected()
292
+ }
293
+ struct.fields.push(this.finishNode(field, "SlimStructField"))
294
+ }
295
+
296
+ parseSlimEnum(node) {
297
+ this.next()
298
+ node.id = this.parseIdentifier()
299
+ this.checkLVal(node.id, { type: "VariableDeclarator" }, LEXICAL)
300
+ node.members = []
301
+
302
+ this.expect(tt.braceL)
303
+ while (!this.eat(tt.braceR)) {
304
+ if (this.eat(tt.comma) || this.eat(tt.semi)) continue
305
+ if (this.match(tt.eof)) this.slimFail(`Unclosed enum ${node.id.name}`)
306
+
307
+ const member = this.startNode()
308
+ member.key = this.parseIdentifier(true)
309
+ member.value = this.eat(tt.colon) ? this.parseMaybeAssignAllowIn() : null
310
+ node.members.push(this.finishNode(member, "SlimEnumMember"))
311
+ }
312
+ return this.finishNode(node, "SlimEnumDeclaration")
313
+ }
314
+
315
+ parseSlimType(node) {
316
+ this.next()
317
+ node.id = this.parseIdentifier()
318
+ this.checkLVal(node.id, { type: "VariableDeclarator" }, LEXICAL)
319
+
320
+ if (this.eat(tt.eq)) {
321
+ if (this.eat(tt._extends)) {
322
+ node.kind = "extends"
323
+ node.typeAnnotation = this.slimParseType()
324
+ } else if (this.eat(tt._typeof)) {
325
+ node.kind = "typeof"
326
+ node.expression = this.parseMaybeAssignAllowIn()
327
+ } else {
328
+ node.kind = "alias"
329
+ node.typeAnnotation = this.slimParseType()
330
+ }
331
+ this.semicolon()
332
+ return this.finishNode(node, "SlimTypeDeclaration")
333
+ }
334
+
335
+ node.kind = "validator"
336
+ const fn = this.startNode()
337
+ this.slimPendingExtends = fn
338
+ node.validator = this.parseMethod(fn, false, false, false, false, "ObjectMethod")
339
+ node.superType = fn.slimExtends ?? null
340
+ delete fn.slimExtends
341
+ return this.finishNode(node, "SlimTypeDeclaration")
342
+ }
343
+
344
+ parseSlimComponent(node) {
345
+ node.modifier = null
346
+ node.tag = null
347
+
348
+ if (this.isWord("isolated") || this.isWord("element")) {
349
+ node.modifier = this.state.value
350
+ this.next()
351
+ if (node.modifier === "element" && this.eat(tt.parenL)) {
352
+ if (!this.match(tt.string)) this.unexpected()
353
+ node.tag = this.state.value
354
+ this.next()
355
+ this.expect(tt.parenR)
356
+ }
357
+ }
358
+
359
+ this.expectWord("component")
360
+ node.id = this.parseIdentifier()
361
+ this.checkLVal(node.id, { type: "VariableDeclarator" }, LEXICAL)
362
+
363
+ const fn = this.startNode()
364
+ this.initFunction(fn, false)
365
+ this.scope.enter(FUNCTION_SCOPE)
366
+ this.prodParam.enter(functionFlags(false, false))
367
+ node.params = this.parseSlimComponentParams()
368
+ fn.params = []
369
+ this.parseFunctionBody(fn, false, true)
370
+ this.prodParam.exit()
371
+ this.scope.exit()
372
+
373
+ node.body = fn.body
374
+ return this.finishNode(node, "SlimComponentDeclaration")
375
+ }
376
+
377
+ parseSlimComponentParams() {
378
+ const params = { type: "SlimComponentParams", pattern: false, items: [] }
379
+ this.expect(tt.parenL)
380
+
381
+ if (this.eat(tt.braceL)) {
382
+ params.pattern = true
383
+ while (!this.eat(tt.braceR)) {
384
+ params.items.push(this.parseSlimParam())
385
+ if (!this.match(tt.braceR)) this.expect(tt.comma)
386
+ }
387
+ } else if (!this.match(tt.parenR)) {
388
+ params.items.push(this.parseSlimParam())
389
+ }
390
+
391
+ this.expect(tt.parenR)
392
+ return params
393
+ }
394
+
395
+ parseSlimParam() {
396
+ const param = this.startNode()
397
+ param.name = this.parseIdentifier()
398
+ param.optional = this.eat(tt.question)
399
+ param.typeAnnotation = this.eat(tt.colon) ? this.slimParseType() : null
400
+ param.value = this.eat(tt.eq) ? this.parseMaybeAssignAllowIn() : null
401
+ return this.finishNode(param, "SlimParam")
402
+ }
403
+
404
+ slimParseUseSource() {
405
+ if (this.match(tt.string)) {
406
+ const value = this.state.value
407
+ this.next()
408
+ return value
409
+ }
410
+ if (!this.match(tt.at)) return null
411
+
412
+ const start = this.state.start
413
+ let end = start + 1
414
+ while (end < this.input.length && /[\w$/.-]/.test(this.input[end])) end++
415
+ if (end === start + 1) this.unexpected()
416
+ this.slimResumeAt(end)
417
+ return this.input.slice(start, end)
418
+ }
419
+
420
+ parseSlimUse(node) {
421
+ this.next()
422
+ node.specifier = null
423
+ node.locals = []
424
+ const sourceStart = this.state.start
425
+ let source = this.slimParseUseSource()
426
+
427
+ if (source !== null && this.isWord("from")) {
428
+ this.slimFail(`A module name can't be imported as a string: write "use name from ..." instead of "use ${this.input.slice(sourceStart, this.state.lastTokEndLoc.index)} from ..."`, sourceStart)
429
+ }
430
+
431
+ if (source === null) {
432
+ const start = this.state.start
433
+
434
+ if (this.eat(tt.star)) {
435
+ this.expectWord("as")
436
+ node.locals.push(this.parseIdentifier())
437
+ } else if (this.eat(tt.braceL)) {
438
+ while (!this.eat(tt.braceR)) {
439
+ let local = this.parseIdentifier(true)
440
+ if (this.isWord("as")) {
441
+ this.next()
442
+ local = this.parseIdentifier()
443
+ }
444
+ node.locals.push(local)
445
+ if (!this.match(tt.braceR)) this.expect(tt.comma)
446
+ }
447
+ } else {
448
+ let local = this.parseIdentifier()
449
+ if (this.isWord("as")) {
450
+ this.next()
451
+ local = this.parseIdentifier()
452
+ }
453
+ node.locals.push(local)
454
+ }
455
+
456
+ node.specifier = this.input.slice(start, this.state.lastTokEndLoc.index).replace(/\s+/g, " ")
457
+ this.expectWord("from")
458
+ source = this.slimParseUseSource()
459
+ if (source === null) this.slimFail(`Expected a module after "from"`)
460
+ }
461
+
462
+ node.source = source
463
+ this.semicolon()
464
+ return this.finishNode(node, "SlimUseDeclaration")
465
+ }
466
+
467
+ parseSlimLockConst(node) {
468
+ this.next()
469
+ const declaration = this.parseVarStatement(node, "const")
470
+ for (const declarator of declaration.declarations) {
471
+ if (!declarator.init) continue
472
+ declarator.init = this.slimWrapUnary("lock", declarator.init)
473
+ }
474
+ this.addExtra(declaration, "slimLock", true)
475
+ return declaration
476
+ }
477
+
478
+ slimWrapUnary(operator, argument) {
479
+ const node = this.startNodeAtNode(argument)
480
+ node.operator = operator
481
+ node.argument = argument
482
+ return this.finishNodeAt(node, "SlimUnaryExpression", argument.loc.end)
483
+ }
484
+
485
+ parseSlimMode(node) {
486
+ this.next()
487
+ node.value = this.state.value
488
+ this.next()
489
+ this.semicolon()
490
+ return this.finishNode(node, "SlimModeStatement")
491
+ }
492
+
493
+ parseReturnStatement(node) {
494
+ const next = this.lookahead()
495
+ if (next.type === tt.lt && isLetter(this.input[next.end] ?? "")) {
496
+ this.next()
497
+ node.argument = this.parseExpression()
498
+ this.semicolon()
499
+ return this.finishNode(node, "ReturnStatement")
500
+ }
501
+ return super.parseReturnStatement(node)
502
+ }
503
+
504
+ parseIfStatement(node) {
505
+ this.next()
506
+ node.test = this.parseHeaderExpression()
507
+ node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration()
508
+
509
+ if (this.eat(tt._else)) {
510
+ node.alternate = this.parseStatementOrSloppyAnnexBFunctionDeclaration()
511
+ } else if (this.isWord("elif") && this.lookahead().type === tt.parenL) {
512
+ const alternate = this.parseIfStatement(this.startNode())
513
+ this.addExtra(alternate, "slimElif", true)
514
+ node.alternate = alternate
515
+ } else {
516
+ node.alternate = null
517
+ }
518
+ return this.finishNode(node, "IfStatement")
519
+ }
520
+
521
+
522
+ slimAtReturnArrow() {
523
+ return this.match(tt.plusMin) && this.state.value === "-" && this.input[this.state.end] === ">"
524
+ }
525
+
526
+ slimParseReturnArrow() {
527
+ this.next()
528
+ this.next()
529
+ const annotation = this.tsParseTypeAnnotation(false)
530
+ this.addExtra(annotation, "slimArrow", true)
531
+ return annotation
532
+ }
533
+
534
+ parseFunctionBodyAndFinish(node, type, isMethod = false) {
535
+ if (this.slimPendingExtends === node) {
536
+ this.slimPendingExtends = null
537
+ if (this.eat(tt._extends)) node.slimExtends = this.slimParseType()
538
+ }
539
+ if (this.slimAtReturnArrow()) node.returnType = this.slimParseReturnArrow()
540
+ return super.parseFunctionBodyAndFinish(node, type, isMethod)
541
+ }
542
+
543
+ shouldParseArrow(params) {
544
+ if (this.slimAtReturnArrow()) return params.every(expr => this.isAssignable(expr, true))
545
+ return super.shouldParseArrow(params)
546
+ }
547
+
548
+ parseArrow(node) {
549
+ if (this.slimAtReturnArrow()) {
550
+ const result = this.tryParse(abort => {
551
+ const returnType = this.slimParseReturnArrow()
552
+ if (this.canInsertSemicolon() || !this.match(tt.arrow)) abort()
553
+ return returnType
554
+ })
555
+ if (result.aborted) return undefined
556
+ if (!result.thrown) {
557
+ if (result.error) this.state = result.failState
558
+ node.returnType = result.node
559
+ }
560
+ }
561
+ return super.parseArrow(node)
562
+ }
563
+
564
+ shouldParseAsyncArrow() {
565
+ return this.slimAtReturnArrow() || super.shouldParseAsyncArrow()
566
+ }
567
+
568
+ parseAsyncArrowFromCallExpression(node, call) {
569
+ if (this.slimAtReturnArrow()) node.returnType = this.slimParseReturnArrow()
570
+ return super.parseAsyncArrowFromCallExpression(node, call)
571
+ }
572
+
573
+
574
+ tsParseNonArrayType() {
575
+ if (this.match(tt._function)) {
576
+ const node = this.startNode()
577
+ node.typeName = this.createIdentifier(this.startNode(), "function")
578
+ this.next()
579
+ return this.finishNode(node, "TSTypeReference")
580
+ }
581
+ return super.tsParseNonArrayType()
582
+ }
583
+
584
+ tsParseArrayTypeOrHigher() {
585
+ const type = super.tsParseArrayTypeOrHigher()
586
+ if (this.hasPrecedingLineBreak() || !this.match(tt.question)) return type
587
+
588
+ const node = this.startNodeAtNode(type)
589
+ this.next()
590
+ node.typeAnnotation = type
591
+ return this.finishNode(node, "SlimNullableType")
592
+ }
593
+
594
+ tsParseTypeReference() {
595
+ const reference = super.tsParseTypeReference()
596
+ if (!this.match(tt.colon) || this.input[this.state.start + 1] !== ":") return reference
597
+
598
+ this.next()
599
+ this.next()
600
+ const node = this.startNodeAtNode(reference)
601
+ node.enumName = reference
602
+ node.member = this.parseIdentifier(true)
603
+ return this.finishNode(node, "SlimEnumMemberType")
604
+ }
605
+
606
+
607
+ parseMaybeUnary(refExpressionErrors, sawUnary) {
608
+ if (this.slimAtMarkup()) return this.parseSlimMarkup()
609
+
610
+ if (this.slimAtPrefixOperator()) {
611
+ const node = this.startNode()
612
+ node.operator = this.state.value
613
+ this.next()
614
+ node.argument = this.parseMaybeUnary(null, true)
615
+ return this.finishNode(node, "SlimUnaryExpression")
616
+ }
617
+
618
+ if (this.isWord("match") && this.lookahead().type === tt.parenL) {
619
+ const match = this.slimTryMatch()
620
+ if (match) return this.parseSubscripts(match, match.loc.start)
621
+ }
622
+
623
+ return super.parseMaybeUnary(refExpressionErrors, sawUnary)
624
+ }
625
+
626
+ slimAtPrefixOperator() {
627
+ if (this.state.containsEsc || this.state.type !== tt.name || !PREFIX_OPERATORS.has(this.state.value)) return false
628
+ if (!isBlank(this.input[this.state.end] ?? "")) return false
629
+
630
+ const next = this.lookahead()
631
+ if (!this.sameLine(next) || !tokenCanStartExpression(next.type)) return false
632
+ if (tokenIsKeywordOrIdentifier(next.type) && NOT_AN_OPERAND.has(next.value)) return false
633
+ return true
634
+ }
635
+
636
+ parseExprOp(left, leftStartLoc, minPrec) {
637
+ if (!this.state.containsEsc && this.state.type === tt.name && (this.state.value === "and" || this.state.value === "or")) {
638
+ const word = this.state.value
639
+ const op = word === "and" ? tt.logicalAND : tt.logicalOR
640
+ const prec = tokenOperatorPrecedence(op)
641
+ if (prec <= minPrec) return left
642
+
643
+ const node = this.startNodeAt(leftStartLoc)
644
+ node.left = left
645
+ node.operator = word === "and" ? "&&" : "||"
646
+ this.addExtra(node, "slimWord", word)
647
+ this.next()
648
+ node.right = this.parseExprOpRightExpr(op, prec)
649
+ return this.parseExprOp(this.finishNode(node, "LogicalExpression"), leftStartLoc, minPrec)
650
+ }
651
+
652
+ if (this.match(tt.tilde) && this.input[this.state.end] === "/") {
653
+ const multiplicative = tokenOperatorPrecedence(tt.slash)
654
+ if (multiplicative + 0.5 <= minPrec) return left
655
+
656
+ const node = this.startNodeAt(leftStartLoc)
657
+ node.left = left
658
+ node.operator = "~/"
659
+ this.next()
660
+ this.next()
661
+ const rightStart = this.state.startLoc
662
+ node.right = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), rightStart, multiplicative)
663
+ return this.parseExprOp(this.finishNode(node, "SlimBinaryExpression"), leftStartLoc, minPrec)
664
+ }
665
+
666
+ if (this.slimAtOldPipeStep()) {
667
+ const method = this.lookahead().value
668
+ this.slimFail(`Pipe steps ("| ${method}(...)") were removed: chain the method instead, ".${method}(...)" on the next line. ` +
669
+ `For a bitwise OR, keep "|" at the end of the line above`)
670
+ }
671
+
672
+ return super.parseExprOp(left, leftStartLoc, minPrec)
673
+ }
674
+
675
+ slimAtOldPipeStep() {
676
+ if (!this.match(tt.bitwiseOR) || !this.hasPrecedingLineBreak()) return false
677
+ const next = this.lookahead()
678
+ return tokenIsKeywordOrIdentifier(next.type) && this.sameLine(next) && this.charAfterSpaces(next.end) === "("
679
+ }
680
+
681
+ slimTryMatch() {
682
+ let committed = false
683
+ const result = this.tryParse(abort => {
684
+ const node = this.startNode()
685
+ this.next()
686
+ this.expect(tt.parenL)
687
+ node.discriminant = this.parseExpression()
688
+ this.expect(tt.parenR)
689
+ if (!this.match(tt.braceL)) abort()
690
+
691
+ committed = true
692
+ this.next()
693
+ node.arms = []
694
+ while (!this.eat(tt.braceR)) {
695
+ node.arms.push(this.parseSlimMatchArm())
696
+ if (!this.match(tt.braceR)) this.expect(tt.comma)
697
+ }
698
+ return this.finishNode(node, "SlimMatchExpression")
699
+ })
700
+
701
+ if (result.aborted) return null
702
+ if (result.thrown || result.error) {
703
+ if (committed) throw result.error
704
+ return null
705
+ }
706
+ return result.node
707
+ }
708
+
709
+ parseSlimMatchArm() {
710
+ const arm = this.startNode()
711
+ arm.pattern = null
712
+ arm.binding = null
713
+ arm.guard = null
714
+
715
+ const wildcard = this.state.type === tt.name && this.state.value === "_"
716
+ if (wildcard) {
717
+ this.next()
718
+ } else if (!this.slimTryTypeArm(arm)) {
719
+ this.state.potentialArrowAt = -1
720
+ arm.pattern = this.parseExprOps(null)
721
+ }
722
+
723
+ if (this.isWord("when")) {
724
+ this.next()
725
+ if (arm.pattern && arm.pattern.type !== "Identifier") this.slimFail(`"when" needs a name or "_" before it`, arm.pattern.start)
726
+ arm.binding ??= arm.pattern
727
+ arm.pattern = null
728
+ this.state.potentialArrowAt = -1
729
+ arm.guard = this.parseExprOps(null)
730
+ }
731
+
732
+ arm.wildcard = wildcard
733
+ this.expect(tt.arrow)
734
+ arm.result = this.parseMaybeAssignAllowIn()
735
+ return this.finishNode(arm, "SlimMatchArm")
736
+ }
737
+
738
+ slimTryTypeArm(arm) {
739
+ if (!tokenIsKeywordOrIdentifier(this.state.type)) return false
740
+
741
+ const result = this.tryParse(abort => {
742
+ const type = this.slimParseType()
743
+ if (!tokenIsIdentifier(this.state.type) || this.isWord("when")) return abort()
744
+ const binding = this.parseIdentifier()
745
+ if (!this.match(tt.arrow) && !this.isWord("when")) return abort()
746
+ return { type, binding }
747
+ })
748
+ if (result.aborted || result.error || result.thrown) return false
749
+
750
+ arm.typeAnnotation = result.node.type
751
+ arm.binding = result.node.binding
752
+ return true
753
+ }
754
+
755
+
756
+ parseMaybeAssign(refExpressionErrors, afterLeftParse) {
757
+ if (!this.match(tt.lt) || !this.slimAtMarkup() || this.slimLooksGeneric()) {
758
+ return super.parseMaybeAssign(refExpressionErrors, afterLeftParse)
759
+ }
760
+ const startLoc = this.state.startLoc
761
+ const left = this.parseMaybeConditional(refExpressionErrors ?? new ExpressionErrors())
762
+ return afterLeftParse ? afterLeftParse.call(this, left, startLoc) : left
763
+ }
764
+
765
+ slimLooksGeneric() {
766
+ const rest = this.input.slice(this.state.end, this.state.end + 200)
767
+ return /^(?:const\s+)?[A-Za-z_$][\w$]*\s*(?:,|extends\b|>\s*\()/.test(rest)
768
+ }
769
+
770
+ slimAtMarkup() {
771
+ if (this.match(tt.lt)) return isLetter(this.input[this.state.end] ?? "")
772
+ return this.state.type === tt.name && this.state.value === "$" && this.input[this.state.end] === "{"
773
+ }
774
+
775
+ slimMarkupContinues(pos) {
776
+ const input = this.input
777
+ while (pos < input.length && isBlank(input[pos])) pos++
778
+ return (input[pos] === "<" && isLetter(input[pos + 1] ?? "")) || (input[pos] === "$" && input[pos + 1] === "{")
779
+ }
780
+
781
+ parseSlimMarkup() {
782
+ const node = this.startNode()
783
+ const input = this.input
784
+ const quasis = []
785
+ const expressions = []
786
+ const state = { depth: 0, inTag: false, closing: false, tag: "", quote: null, raw: null }
787
+
788
+ let pos = this.state.start
789
+ let chunk = pos
790
+ let done = false
791
+
792
+ const closeTag = () => {
793
+ state.inTag = false
794
+ if (state.closing) state.depth--
795
+ else if (!input.startsWith("/>", pos - 2) && !VOID_ELEMENTS.has(state.tag)) {
796
+ state.depth++
797
+ if (RAW_TEXT_ELEMENTS.has(state.tag)) state.raw = state.tag
798
+ }
799
+ return state.depth <= 0 && !this.slimMarkupContinues(pos)
800
+ }
801
+
802
+ while (!done) {
803
+ if (pos >= input.length) this.slimFail("Unclosed markup", node.start)
804
+ const c = input[pos]
805
+
806
+ if (c === "$" && input[pos + 1] === "{") {
807
+ quasis.push(input.slice(chunk, pos))
808
+ this.slimMoveTo(pos + 2)
809
+ this.next()
810
+ expressions.push(this.parseSlimInterpolation(pos))
811
+ pos = chunk = this.state.end
812
+ if (state.depth <= 0 && !state.inTag && !this.slimMarkupContinues(pos)) done = true
813
+ continue
814
+ }
815
+
816
+ if (state.raw) {
817
+ if (c === "<" && input[pos + 1] === "/" && input.substr(pos + 2, state.raw.length).toLowerCase() === state.raw) state.raw = null
818
+ else pos++
819
+ continue
820
+ }
821
+
822
+ if (state.inTag) {
823
+ pos++
824
+ if (state.quote) {
825
+ if (c === state.quote) state.quote = null
826
+ } else if (c === '"' || c === "'") {
827
+ state.quote = c
828
+ } else if (c === ">") {
829
+ done = closeTag()
830
+ }
831
+ continue
832
+ }
833
+
834
+ if (c === "<" && input.startsWith("<!--", pos)) {
835
+ const close = input.indexOf("-->", pos + 4)
836
+ if (close === -1) this.slimFail("Unclosed comment in markup", pos)
837
+ pos = close + 3
838
+ } else if (c === "<" && input[pos + 1] === "/") {
839
+ pos += 2
840
+ state.inTag = true
841
+ state.closing = true
842
+ } else if (c === "<" && isLetter(input[pos + 1] ?? "")) {
843
+ const nameStart = ++pos
844
+ while (pos < input.length && isTagChar(input[pos])) pos++
845
+ const tag = input.slice(nameStart, pos)
846
+ state.tag = /^[A-Z]/.test(tag) ? "" : tag.toLowerCase()
847
+ state.inTag = true
848
+ state.closing = false
849
+ } else {
850
+ pos++
851
+ }
852
+ }
853
+
854
+ quasis.push(input.slice(chunk, pos))
855
+ this.slimResumeAt(pos)
856
+
857
+ node.quasis = quasis
858
+ node.expressions = expressions
859
+ return this.finishNode(node, "SlimMarkup")
860
+ }
861
+
862
+ parseSlimInterpolation(open) {
863
+ if (this.match(tt.braceR)) this.slimFail("Empty ${} in markup: put an expression inside or remove it", open)
864
+
865
+ const statement = STATEMENT_WORDS.find(word => this.isWord(word))
866
+ if (statement) {
867
+ this.slimFail(`"${statement}" is a statement and can't go inside \${...}: use a ternary (a ? b : c), match or .map() instead`)
868
+ }
869
+
870
+ let expression
871
+ try {
872
+ expression = this.parseExpression()
873
+ } catch (error) {
874
+ if (UNTERMINATED.has(error.reasonCode) || (error.pos ?? 0) >= this.input.length) {
875
+ this.slimFail(`"\${" is not closed: add "}" after the expression`, open)
876
+ }
877
+ if (this.input[error.pos] === "}" && error.reasonCode === "UnexpectedToken") {
878
+ this.slimFail("The expression inside ${...} is incomplete", error.pos)
879
+ }
880
+ throw error
881
+ }
882
+
883
+ if (!this.match(tt.braceR)) {
884
+ if (this.match(tt.eof)) this.slimFail(`"\${" is not closed: add "}" after the expression`, open)
885
+ this.slimFail(`Expected "}" to close "\${", got "${this.input.slice(this.state.start, this.state.end)}"`)
886
+ }
887
+ return expression
888
+ }
889
+ }
890
+
891
+ babel.registerPlugin("slim", slim)
892
+
893
+ export function parseSlim(code, sourceFilename = "input.slim", { comments = false } = {}) {
894
+ return babel.parse(code, {
895
+ sourceType: "module",
896
+ sourceFilename,
897
+ attachComment: comments,
898
+ allowReturnOutsideFunction: false,
899
+ plugins: ["typescript", "slim"]
900
+ })
901
+ }
902
+
903
+ export { babel }