@tylix/compiler 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +30 -2
  3. package/src/ast/nodes.js +145 -23
  4. package/src/ast/substituteCapabilityRefs.js +52 -5
  5. package/src/codegen/emitStatementLines.js +60 -10
  6. package/src/codegen/generateExpression.js +294 -35
  7. package/src/codegen/generateStatement.js +125 -20
  8. package/src/codegen/generateTemplate.js +107 -96
  9. package/src/codegen/generateTemplateExpression.js +63 -10
  10. package/src/codegen/jsGlobals.js +62 -2
  11. package/src/compileComponent.js +37 -6
  12. package/src/lexer/Lexer.js +128 -28
  13. package/src/parser/Parser.js +1840 -500
  14. package/src/parser/parseExpressionString.js +5 -0
  15. package/src/parser/parseTemplate.js +153 -41
  16. package/src/renderPageDocument.js +71 -8
  17. package/src/runtime/capability.js +8 -1
  18. package/src/runtime/reactive.js +289 -61
  19. package/src/runtime/useApi.js +74 -13
  20. package/src/runtime/useChannel.js +27 -6
  21. package/src/typecheck/buildVirtualTs.js +11 -1
  22. package/src/typecheck/tylix-globals.d.ts +23 -4
  23. package/src/typecheck/typedTemplateExpr.js +90 -27
  24. package/src/codegen/generateExpression.array.test.js +0 -13
  25. package/src/codegen/generateExpression.callexpr.test.js +0 -19
  26. package/src/codegen/generateExpression.test.js +0 -59
  27. package/src/codegen/generateMethod.asyncawait.test.js +0 -37
  28. package/src/codegen/generateMethod.ifstatement.test.js +0 -20
  29. package/src/codegen/generateMethod.test.js +0 -81
  30. package/src/codegen/generatePage.onmount.test.js +0 -46
  31. package/src/codegen/generatePage.test.js +0 -138
  32. package/src/codegen/generateStatement.test.js +0 -31
  33. package/src/codegen/generateTemplate.ifeach.test.js +0 -138
  34. package/src/codegen/generateTemplate.test.js +0 -149
  35. package/src/codegen/generateTemplateExpression.test.js +0 -34
  36. package/src/compileComponent.test.js +0 -121
  37. package/src/lexer/Lexer.test.js +0 -151
  38. package/src/parser/Parser.array.test.js +0 -37
  39. package/src/parser/Parser.asyncawait.test.js +0 -33
  40. package/src/parser/Parser.ifstatement.test.js +0 -20
  41. package/src/parser/Parser.onmount.test.js +0 -18
  42. package/src/parser/Parser.test.js +0 -315
  43. package/src/parser/parseComponent.test.js +0 -53
  44. package/src/parser/parsePageFile.test.js +0 -101
  45. package/src/parser/parseTemplate.ifeach.test.js +0 -33
  46. package/src/parser/parseTemplate.pre.test.js +0 -39
  47. package/src/parser/parseTemplate.test.js +0 -112
  48. package/src/renderPageDocument.test.js +0 -125
  49. package/src/runtime/reactive.test.js +0 -106
  50. package/test/dashboard-syntax.test.js +0 -116
@@ -2,8 +2,13 @@ import { parseComponent } from './parser/parseComponent.js'
2
2
  import { parseTemplate } from './parser/parseTemplate.js'
3
3
  import { Lexer } from './lexer/Lexer.js'
4
4
  import { Parser } from './parser/Parser.js'
5
+ import { normalizeLanguageOptions } from './parser/languageOptions.js'
5
6
  import { generatePage } from './codegen/generatePage.js'
6
7
  import { generateTemplate } from './codegen/generateTemplate.js'
8
+ import {
9
+ generateStatement,
10
+ declaredNames,
11
+ } from './codegen/generateStatement.js'
7
12
  import { reactive, effect } from './runtime/reactive.js'
8
13
  import { useApi } from './runtime/useApi.js'
9
14
 
@@ -17,29 +22,55 @@ import { useApi } from './runtime/useApi.js'
17
22
  * The `components` map passed to mount() lets a template reference
18
23
  * other compiled components by capitalized tag name (<Badge />);
19
24
  * omit it for components that don't nest anything.
25
+ *
26
+ * `languageOption` takes the same compiler switches as
27
+ * renderPageDocument, e.g. { not: 'loose' }.
28
+ *
29
+ * Module-level declarations in the script (function, const, let,
30
+ * class, enum) are scoped to this component and attached to each
31
+ * instance so the template can call them.
20
32
  */
21
- export function compileComponent(source, className = 'Component') {
33
+ export function compileComponent(
34
+ source,
35
+ className = 'Component',
36
+ languageOption = {},
37
+ ) {
38
+ const language = normalizeLanguageOptions(languageOption ?? {})
22
39
  const { script, template } = parseComponent(source)
23
40
 
24
41
  const pageNode =
25
42
  script.trim().length > 0
26
- ? new Parser(new Lexer(script).tokenize()).parse()
27
- : { props: [], state: [], computed: [], actions: [] }
43
+ ? new Parser(new Lexer(script).tokenize(), language).parse()
44
+ : { props: [], state: [], computed: [], actions: [], helpers: [] }
28
45
 
29
46
  const classSource = generatePage(pageNode, className)
30
- const ComponentClass = new Function(
47
+
48
+ const helpers = pageNode.helpers ?? []
49
+ const helperSource = helpers
50
+ .map((h) => generateStatement(h, false))
51
+ .filter((s) => s.trim().length > 0)
52
+ .join('\n')
53
+ const exposed = helpers
54
+ .flatMap(declaredNames)
55
+ .map((n) => `${JSON.stringify(n)}: ${n}`)
56
+ .join(', ')
57
+
58
+ const { Class: ComponentClass, helperValues } = new Function(
31
59
  'reactive',
32
60
  'useApi',
33
- `return ${classSource}`,
61
+ `${helperSource}\nconst __Class = ${classSource};\nreturn { Class: __Class, helperValues: { ${exposed} } };`,
34
62
  )(reactive, useApi)
35
63
 
36
- const templateNodes = parseTemplate(template)
64
+ const templateNodes = parseTemplate(template, language)
37
65
  const { code, rootVar } = generateTemplate(templateNodes)
38
66
 
39
67
  return {
40
68
  ComponentClass,
41
69
  mount(document, components = {}) {
42
70
  const instance = new ComponentClass()
71
+ for (const key of Object.keys(helperValues)) {
72
+ instance[key] = helperValues[key]
73
+ }
43
74
  const renderFn = new Function(
44
75
  'document',
45
76
  'effect',
@@ -2,6 +2,17 @@ import { TokenType, KEYWORDS } from './tokenTypes.js'
2
2
 
3
3
  const T = TokenType
4
4
 
5
+ // Identifier characters follow the JS spec (Unicode ID_Start /
6
+ // ID_Continue plus $ and _), so names like `café` or `変数` work.
7
+ const ID_START = /^[\p{ID_Start}_$]$/u
8
+ const ID_PART = /^[\p{ID_Continue}$\u200c\u200d]$/u
9
+
10
+ // The whole code point at index i (handles surrogate pairs), or ''.
11
+ function codePointStringAt(src, i) {
12
+ const cp = src.codePointAt(i)
13
+ return cp === undefined ? '' : String.fromCodePoint(cp)
14
+ }
15
+
5
16
  // Multi-character operators, matched longest-first. JS-style spellings
6
17
  // of Tylix word operators are aliased here:
7
18
  // == / === -> is != / !== -> is not
@@ -127,6 +138,12 @@ const REGEX_PRECEDERS = new Set([
127
138
  T.HAS,
128
139
  T.IN,
129
140
  T.OF,
141
+ T.IF,
142
+ T.ELSE,
143
+ T.DO,
144
+ T.WHILE,
145
+ T.SWITCH,
146
+ T.INSTANCEOF,
130
147
  T.RETURN,
131
148
  T.AWAIT,
132
149
  T.TYPEOF,
@@ -189,7 +206,13 @@ export class Lexer {
189
206
  continue
190
207
  }
191
208
 
192
- if (/[a-zA-Z_$]/.test(char)) {
209
+ // Identifiers: any Unicode ID_Start character, or `#name` (a
210
+ // class private name, lexed as one identifier token).
211
+ const ch = codePointStringAt(src, this.pos)
212
+ if (
213
+ ID_START.test(ch) ||
214
+ (ch === '#' && ID_START.test(codePointStringAt(src, this.pos + 1)))
215
+ ) {
193
216
  this.readIdentifierOrKeyword()
194
217
  continue
195
218
  }
@@ -275,7 +298,16 @@ export class Lexer {
275
298
  // regex literal (or number) based on the previous token.
276
299
  regexAllowed() {
277
300
  const prev = this.tokens[this.tokens.length - 1]
278
- return !prev || REGEX_PRECEDERS.has(prev.type)
301
+ if (!prev) return true
302
+ // A keyword right after "." is a property name (`obj.in / 2`),
303
+ // so the "/" is division, not the start of a regex.
304
+ const before = this.tokens[this.tokens.length - 2]
305
+ if (before && (before.type === T.DOT || before.type === T.QUESTION_DOT)) {
306
+ return false
307
+ }
308
+ // `yield /re/` -- yield is a plain identifier token.
309
+ if (prev.type === T.IDENTIFIER && prev.value === 'yield') return true
310
+ return REGEX_PRECEDERS.has(prev.type)
279
311
  }
280
312
 
281
313
  readRegex() {
@@ -400,31 +432,35 @@ export class Lexer {
400
432
  }
401
433
 
402
434
  // Scans a backtick template literal into a flat list of parts --
403
- // { type: "text", value } for literal text, { type: "expr", source }
404
- // for each ${...} span -- rather than re-entering full tokenization
405
- // mid-string. Each expr span's raw source gets parsed later via
406
- // parseExpressionString, reusing the same mechanism already used for
407
- // {{ }} interpolations and #if/#each headers.
435
+ // { type: "text", value, raw } for literal text, { type: "expr",
436
+ // source } for each ${...} span -- rather than re-entering full
437
+ // tokenization mid-string. `value` is the cooked text (escapes
438
+ // resolved); `raw` is the text exactly as written, which tagged
439
+ // templates need for String.raw. Each expr span's raw source gets
440
+ // parsed later via parseExpressionString.
408
441
  readTemplateLiteral() {
442
+ const src = this.source
409
443
  const startLine = this.line
410
444
  this.pos++ // skip opening backtick
411
445
  const parts = []
412
446
  let textBuf = ''
447
+ let rawBuf = ''
413
448
 
414
449
  const flushText = () => {
415
- if (textBuf.length > 0) {
416
- parts.push({ type: 'text', value: textBuf })
450
+ if (textBuf.length > 0 || rawBuf.length > 0) {
451
+ parts.push({ type: 'text', value: textBuf, raw: rawBuf })
417
452
  textBuf = ''
453
+ rawBuf = ''
418
454
  }
419
455
  }
420
456
 
421
457
  while (true) {
422
- if (this.pos >= this.source.length) {
458
+ if (this.pos >= src.length) {
423
459
  throw new Error(
424
460
  `Unterminated template literal starting at line ${startLine}`,
425
461
  )
426
462
  }
427
- const char = this.source[this.pos]
463
+ const char = src[this.pos]
428
464
 
429
465
  if (char === '`') {
430
466
  this.pos++ // skip closing backtick
@@ -432,33 +468,33 @@ export class Lexer {
432
468
  }
433
469
 
434
470
  if (char === '\\') {
471
+ const escStart = this.pos
435
472
  textBuf += this.readEscape()
473
+ rawBuf += src.slice(escStart, this.pos)
436
474
  continue
437
475
  }
438
476
 
439
- if (char === '$' && this.source[this.pos + 1] === '{') {
477
+ if (char === '$' && src[this.pos + 1] === '{') {
440
478
  flushText()
441
479
  this.pos += 2 // skip "${"
442
480
  const exprStart = this.pos
443
- let depth = 1
444
- while (this.pos < this.source.length && depth > 0) {
445
- if (this.source[this.pos] === '{') depth++
446
- else if (this.source[this.pos] === '}') depth--
447
- if (depth > 0) this.pos++
448
- }
449
- if (depth !== 0) {
481
+ const exprEnd = this.findTemplateExprEnd(exprStart)
482
+ if (exprEnd === -1) {
450
483
  throw new Error(
451
484
  `Unterminated \${...} in template literal starting at line ${startLine}`,
452
485
  )
453
486
  }
454
- const exprSource = this.source.slice(exprStart, this.pos)
455
- this.pos++ // skip closing "}"
487
+ const exprSource = src.slice(exprStart, exprEnd)
488
+ // Newlines inside the span still count toward line numbers.
489
+ this.line += (exprSource.match(/\n/g) ?? []).length
490
+ this.pos = exprEnd + 1 // skip closing "}"
456
491
  parts.push({ type: 'expr', source: exprSource })
457
492
  continue
458
493
  }
459
494
 
460
495
  if (char === '\n') this.line++
461
496
  textBuf += char
497
+ rawBuf += char
462
498
  this.pos++
463
499
  }
464
500
 
@@ -466,6 +502,63 @@ export class Lexer {
466
502
  this.pushToken(T.TEMPLATE_LITERAL, parts, startLine)
467
503
  }
468
504
 
505
+ // Index of the "}" that closes a ${ ... } span starting at `from`.
506
+ // Braces inside strings and nested template literals are skipped,
507
+ // so ${ "}" } and ${ `a${b}` } work.
508
+ findTemplateExprEnd(from) {
509
+ const src = this.source
510
+ let depth = 1
511
+ let i = from
512
+ while (i < src.length) {
513
+ const c = src[i]
514
+ if (c === '"' || c === "'") {
515
+ i++
516
+ while (i < src.length && src[i] !== c) {
517
+ if (src[i] === '\\') i++
518
+ i++
519
+ }
520
+ i++
521
+ continue
522
+ }
523
+ if (c === '`') {
524
+ i = this.skipNestedTemplate(i)
525
+ if (i === -1) return -1
526
+ continue
527
+ }
528
+ if (c === '{') {
529
+ depth++
530
+ } else if (c === '}') {
531
+ depth--
532
+ if (depth === 0) return i
533
+ }
534
+ i++
535
+ }
536
+ return -1
537
+ }
538
+
539
+ // `i` points at an opening backtick. Returns the index just past
540
+ // the matching closing backtick, or -1 if it never closes.
541
+ skipNestedTemplate(i) {
542
+ const src = this.source
543
+ i++
544
+ while (i < src.length) {
545
+ const c = src[i]
546
+ if (c === '\\') {
547
+ i += 2
548
+ continue
549
+ }
550
+ if (c === '`') return i + 1
551
+ if (c === '$' && src[i + 1] === '{') {
552
+ const end = this.findTemplateExprEnd(i + 2)
553
+ if (end === -1) return -1
554
+ i = end + 1
555
+ continue
556
+ }
557
+ i++
558
+ }
559
+ return -1
560
+ }
561
+
469
562
  // Numbers: 42, 3.14, .5, 1_000, 1e6, 2.5e-3, 0xFF, 0b101, 0o17,
470
563
  // BigInt (10n, 0xFFn) and durations (500ms, 2s, 5m, 1h, 7d). A "."
471
564
  // is only part of the number when a digit follows, so
@@ -528,15 +621,22 @@ export class Lexer {
528
621
  }
529
622
 
530
623
  readIdentifierOrKeyword() {
624
+ const src = this.source
531
625
  const start = this.pos
532
- while (
533
- this.pos < this.source.length &&
534
- /[a-zA-Z0-9_$]/.test(this.source[this.pos])
535
- ) {
536
- this.pos++
626
+ if (src[this.pos] === '#') this.pos++ // private name: #field
627
+ while (this.pos < src.length) {
628
+ const ch = codePointStringAt(src, this.pos)
629
+ if (!ID_PART.test(ch)) break
630
+ this.pos += ch.length
537
631
  }
538
- const text = this.source.slice(start, this.pos)
539
- const type = KEYWORDS[text] ?? T.IDENTIFIER
632
+ const text = src.slice(start, this.pos)
633
+ // Own-property lookup only: a plain `KEYWORDS[text]` also finds
634
+ // inherited names, so `toString`, `constructor` and
635
+ // `hasOwnProperty` used to come out as function "token types".
636
+ const type =
637
+ !text.startsWith('#') && Object.hasOwn(KEYWORDS, text)
638
+ ? KEYWORDS[text]
639
+ : T.IDENTIFIER
540
640
  this.pushToken(type, text)
541
641
  }
542
642