@tylix/compiler 0.1.0 → 0.1.1

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.
@@ -28,6 +28,7 @@ export const TokenType = {
28
28
  DOT: 'DOT', // .
29
29
  LBRACKET: 'LBRACKET', // [
30
30
  RBRACKET: 'RBRACKET', // ]
31
+ SPREAD: 'SPREAD', // ...
31
32
  ARROW: 'ARROW', // =>
32
33
  QUESTION: 'QUESTION', // ?
33
34
  RETURN: 'RETURN',
@@ -46,6 +47,7 @@ export const TokenType = {
46
47
  LT: 'LT',
47
48
  GTE: 'GTE', // >=
48
49
  LTE: 'LTE', // <=
50
+ PIPE: 'PIPE', // |
49
51
 
50
52
  // Word operators (Tylix-native, not symbol-based)
51
53
  AND: 'AND', // and
@@ -10,6 +10,7 @@ import {
10
10
  TernaryExpr,
11
11
  ArrowFunctionExpr,
12
12
  TemplateLiteralExpr,
13
+ SpreadElement,
13
14
  Identifier,
14
15
  MemberExpr,
15
16
  Literal,
@@ -106,8 +107,10 @@ export class Parser {
106
107
  page.computed = this.parseSectionBlock(this.parseMethod.bind(this))
107
108
  } else if (this.match(TokenType.ACTION)) {
108
109
  page.actions = this.parseSectionBlock(this.parseMethod.bind(this))
109
- } else if (this.match(TokenType.ONMOUNT)) {
110
- page.onMount = this.parseOnMountBody()
110
+ } else if (this.check(TokenType.ONMOUNT)) {
111
+ const startLine = this.peek().line
112
+ this.advance()
113
+ page.onMount = { ...this.parseOnMountBody(), line: startLine }
111
114
  } else {
112
115
  throw new Error(
113
116
  `Unexpected token ${this.peek().type} at line ${this.peek().line}`,
@@ -175,53 +178,88 @@ export class Parser {
175
178
  }
176
179
 
177
180
  parsePropEntry() {
181
+ const startLine = this.peek().line
178
182
  const name = this.expect(TokenType.IDENTIFIER, 'Expected prop name').value
183
+ const optional = this.match(TokenType.QUESTION)
179
184
  this.expect(TokenType.COLON, "Expected ':' after prop name")
180
- const propType = this.expect(
181
- TokenType.IDENTIFIER,
182
- 'Expected prop type',
183
- ).value
184
- return PropNode(name, propType)
185
+ const propType = this.parseTypeExpression()
186
+ return { ...PropNode(name, propType, optional), line: startLine }
185
187
  }
186
-
187
188
  parseStateEntry() {
189
+ const startLine = this.peek().line
188
190
  const name = this.expect(TokenType.IDENTIFIER, 'Expected state name').value
191
+
192
+ let typeAnnotation = null
193
+ if (this.match(TokenType.LPAREN)) {
194
+ typeAnnotation = this.parseTypeExpression()
195
+ this.expect(
196
+ TokenType.RPAREN,
197
+ "Expected ')' to close state type annotation",
198
+ )
199
+ }
200
+
189
201
  this.expect(TokenType.COLON, "Expected ':' after state name")
190
202
  if (this.match(TokenType.MINUS)) {
191
203
  const num = this.expect(
192
204
  TokenType.NUMBER,
193
205
  "Expected a number after '-'",
194
206
  ).value
195
- return StateNode(name, Literal(-num))
207
+ return {
208
+ ...StateNode(name, Literal(-num), typeAnnotation),
209
+ line: startLine,
210
+ }
196
211
  }
197
212
  const value = this.parsePrimary()
198
- return StateNode(name, value)
213
+ return { ...StateNode(name, value, typeAnnotation), line: startLine }
199
214
  }
200
-
201
215
  parseMethod() {
216
+ const startLine = this.peek().line
202
217
  const isAsync = this.match(TokenType.ASYNC)
203
218
  const name = this.expect(TokenType.IDENTIFIER, 'Expected method name').value
204
219
  this.expect(TokenType.LPAREN, "Expected '(' after method name")
220
+
205
221
  const params = []
206
222
  while (!this.check(TokenType.RPAREN)) {
207
- params.push(
208
- this.expect(TokenType.IDENTIFIER, 'Expected parameter name').value,
209
- )
223
+ const paramName = this.expect(
224
+ TokenType.IDENTIFIER,
225
+ 'Expected parameter name',
226
+ ).value
227
+ let paramType = null
228
+ if (this.match(TokenType.COLON)) {
229
+ paramType = this.parseTypeExpression()
230
+ }
231
+ params.push({ name: paramName, typeAnnotation: paramType })
210
232
  this.match(TokenType.COMMA)
211
233
  }
212
234
  this.expect(TokenType.RPAREN, "Expected ')' after parameters")
213
- this.expect(TokenType.LBRACE, "Expected '{' to start method body")
214
235
 
236
+ let returnType = null
237
+ if (this.match(TokenType.COLON)) {
238
+ returnType = this.parseTypeExpression()
239
+ }
240
+
241
+ this.expect(TokenType.LBRACE, "Expected '{' to start method body")
215
242
  const body = []
216
243
  while (!this.check(TokenType.RBRACE)) {
217
244
  body.push(this.parseStatement())
218
245
  }
219
246
  this.expect(TokenType.RBRACE, "Expected '}' to close method body")
220
247
 
221
- return { ...MethodNode(name, params, body), isAsync }
248
+ return {
249
+ ...MethodNode(name, params, body, returnType),
250
+ isAsync,
251
+ line: startLine,
252
+ }
222
253
  }
223
254
 
224
255
  parseStatement() {
256
+ const startLine = this.peek().line
257
+ const node = this.parseStatementInner()
258
+ node.line = node.line ?? startLine
259
+ return node
260
+ }
261
+
262
+ parseStatementInner() {
225
263
  if (this.match(TokenType.RETURN)) {
226
264
  const hasValue =
227
265
  !this.check(TokenType.SEMICOLON) && !this.check(TokenType.RBRACE)
@@ -268,7 +306,6 @@ export class Parser {
268
306
  this.match(TokenType.SEMICOLON)
269
307
  return ExpressionStatement(expression)
270
308
  }
271
-
272
309
  parseIfStatement() {
273
310
  const hasParen = this.match(TokenType.LPAREN)
274
311
  const condition = this.parseExpression()
@@ -381,22 +418,38 @@ export class Parser {
381
418
  // reopening the entire statement grammar inside an expression
382
419
  // position.
383
420
  tryParseArrowFunction() {
421
+ // single-param form: x => expr or x: Type => expr
384
422
  if (this.check(TokenType.IDENTIFIER)) {
385
423
  const next = this.tokens[this.pos + 1]
386
424
  if (next && next.type === TokenType.ARROW) {
387
425
  const param = this.advance().value
388
426
  this.advance() // consume '=>'
389
427
  const body = this.parseAssignment()
390
- return ArrowFunctionExpr([param], body)
428
+ return ArrowFunctionExpr([param], body, [null])
429
+ }
430
+ if (next && next.type === TokenType.COLON) {
431
+ const savedPos = this.pos
432
+ const param = this.advance().value
433
+ this.advance() // consume ':'
434
+ const paramType = this.parseTypeExpression()
435
+ if (this.check(TokenType.ARROW)) {
436
+ this.advance()
437
+ const body = this.parseAssignment()
438
+ return ArrowFunctionExpr([param], body, [paramType])
439
+ }
440
+ // wasn't actually a typed arrow param -- back out
441
+ this.pos = savedPos
391
442
  }
392
443
  return null
393
444
  }
394
445
 
446
+ // (a, b) => expr or (a: Type, b: Type) => expr
395
447
  if (this.check(TokenType.LPAREN)) {
396
448
  const savedPos = this.pos
397
- this.pos++ // consume '('
449
+ this.pos++
398
450
 
399
451
  const params = []
452
+ const paramTypes = []
400
453
  let isValidParamList = true
401
454
 
402
455
  if (!this.check(TokenType.RPAREN)) {
@@ -406,28 +459,26 @@ export class Parser {
406
459
  break
407
460
  }
408
461
  params.push(this.advance().value)
462
+ paramTypes.push(
463
+ this.match(TokenType.COLON) ? this.parseTypeExpression() : null,
464
+ )
409
465
  if (this.match(TokenType.COMMA)) continue
410
466
  break
411
467
  }
412
468
  }
413
469
 
414
470
  if (isValidParamList && this.check(TokenType.RPAREN)) {
415
- this.pos++ // consume ')'
471
+ this.pos++
416
472
  if (this.check(TokenType.ARROW)) {
417
- this.pos++ // consume '=>'
473
+ this.pos++
418
474
  const body = this.parseAssignment()
419
- return ArrowFunctionExpr(params, body)
475
+ return ArrowFunctionExpr(params, body, paramTypes)
420
476
  }
421
477
  }
422
478
 
423
- // Not actually an arrow function (either the parameter list
424
- // wasn't a plain comma-separated identifier list, or there was
425
- // no '=>' after the closing paren) -- back out completely so
426
- // the normal parsePrimary grouped-expression path handles it.
427
479
  this.pos = savedPos
428
480
  return null
429
481
  }
430
-
431
482
  return null
432
483
  }
433
484
 
@@ -564,7 +615,11 @@ export class Parser {
564
615
  this.expect(TokenType.LPAREN, "Expected '(' to start call arguments")
565
616
  const args = []
566
617
  while (!this.check(TokenType.RPAREN)) {
567
- args.push(this.parseExpression())
618
+ if (this.match(TokenType.SPREAD)) {
619
+ args.push(SpreadElement(this.parseExpression()))
620
+ } else {
621
+ args.push(this.parseExpression())
622
+ }
568
623
  this.match(TokenType.COMMA)
569
624
  }
570
625
  this.expect(TokenType.RPAREN, "Expected ')' to close call arguments")
@@ -623,10 +678,90 @@ export class Parser {
623
678
  `Unexpected token ${this.peek().type} at line ${this.peek().line}`,
624
679
  )
625
680
  }
681
+
682
+ // Type expressions are captured as plain strings, not a full type
683
+ // AST -- Tylix's own codegen never interprets the, it only needs the exact TS source text to paste into the
684
+ // virtual .ts file handed to the TypeScript compiler API.
685
+ parseTypeExpression() {
686
+ let left = this.parseUnionTypeOperand()
687
+ while (this.check(TokenType.PIPE)) {
688
+ this.advance()
689
+ const right = this.parseUnionTypeOperand()
690
+ left = `${left} | ${right}`
691
+ }
692
+ return left
693
+ }
694
+
695
+ parseUnionTypeOperand() {
696
+ let type = this.parsePrimaryType()
697
+ while (this.check(TokenType.LBRACKET)) {
698
+ this.advance()
699
+ this.expect(TokenType.RBRACKET, "Expected ']' to close array type")
700
+ type = `${type}[]`
701
+ }
702
+ return type
703
+ }
704
+
705
+ parsePrimaryType() {
706
+ if (this.check(TokenType.LBRACE)) {
707
+ return this.parseObjectTypeLiteral()
708
+ }
709
+ if (this.match(TokenType.LPAREN)) {
710
+ const inner = this.parseTypeExpression()
711
+ this.expect(TokenType.RPAREN, "Expected ')' to close grouped type")
712
+ return `(${inner})`
713
+ }
714
+
715
+ let name = this.expect(TokenType.IDENTIFIER, 'Expected a type name').value
716
+ while (this.match(TokenType.DOT)) {
717
+ const prop = this.expect(
718
+ TokenType.IDENTIFIER,
719
+ "Expected a property name after '.'",
720
+ ).value
721
+ name += `.${prop}`
722
+ }
723
+
724
+ if (this.match(TokenType.LT)) {
725
+ const args = [this.parseTypeExpression()]
726
+ while (this.match(TokenType.COMMA)) {
727
+ args.push(this.parseTypeExpression())
728
+ }
729
+ this.expect(TokenType.GT, "Expected '>' to close generic type arguments")
730
+ name += `<${args.join(', ')}>`
731
+ }
732
+
733
+ return name
734
+ }
735
+
736
+ parseObjectTypeLiteral() {
737
+ this.expect(TokenType.LBRACE, "Expected '{' to start object type")
738
+ const members = []
739
+ while (!this.check(TokenType.RBRACE)) {
740
+ const key = this.expect(
741
+ TokenType.IDENTIFIER,
742
+ 'Expected a property name',
743
+ ).value
744
+ const optional = this.match(TokenType.QUESTION)
745
+ this.expect(
746
+ TokenType.COLON,
747
+ "Expected ':' after property name in object type",
748
+ )
749
+ const valueType = this.parseTypeExpression()
750
+ members.push(`${key}${optional ? '?' : ''}: ${valueType}`)
751
+ if (!this.match(TokenType.COMMA)) this.match(TokenType.SEMICOLON)
752
+ }
753
+ this.expect(TokenType.RBRACE, "Expected '}' to close object type")
754
+ return `{ ${members.join('; ')} }`
755
+ }
756
+
626
757
  parseArrayLiteral() {
627
758
  const elements = []
628
759
  while (!this.check(TokenType.RBRACKET)) {
629
- elements.push(this.parseExpression())
760
+ if (this.match(TokenType.SPREAD)) {
761
+ elements.push(SpreadElement(this.parseExpression()))
762
+ } else {
763
+ elements.push(this.parseExpression())
764
+ }
630
765
  this.match(TokenType.COMMA)
631
766
  }
632
767
  this.expect(TokenType.RBRACKET, "Expected ']' to close array literal")
@@ -69,12 +69,36 @@ class TemplateParser {
69
69
  constructor(source) {
70
70
  this.source = source
71
71
  this.pos = 0
72
+ // Precomputed once so lineAt() is a binary search instead of
73
+ // rescanning from the start on every node -- parsing jumps around
74
+ // via indexOf() in several places (interpolations, {{#if}}/
75
+ // {{#each}} headers), so a running line counter threaded
76
+ // incrementally (the way Lexer does it) would miss newlines that
77
+ // fall inside a skipped range.
78
+ this.lineStarts = [0]
79
+ for (let i = 0; i < source.length; i++) {
80
+ if (source[i] === '\n') this.lineStarts.push(i + 1)
81
+ }
72
82
  }
73
83
 
74
84
  remaining() {
75
85
  return this.source.slice(this.pos)
76
86
  }
77
87
 
88
+ // 1-based line number containing `pos`. Binary search over
89
+ // lineStarts -- called once per node, so this stays cheap even on
90
+ // large templates.
91
+ lineAt(pos) {
92
+ let lo = 0
93
+ let hi = this.lineStarts.length - 1
94
+ while (lo < hi) {
95
+ const mid = (lo + hi + 1) >> 1
96
+ if (this.lineStarts[mid] <= pos) lo = mid
97
+ else hi = mid - 1
98
+ }
99
+ return lo + 1
100
+ }
101
+
78
102
  // Parses sibling nodes. `stopTag` (an HTML tag name) or `stopMarker`
79
103
  // (a literal like "{{/if}}") tell this call when to return; nested
80
104
  // control blocks / elements consume their own closing marker before
@@ -144,6 +168,7 @@ class TemplateParser {
144
168
  }
145
169
 
146
170
  parseInterpolation() {
171
+ const line = this.lineAt(this.pos)
147
172
  const start = this.pos + 2
148
173
  const end = this.source.indexOf('}}', start)
149
174
  if (end === -1) {
@@ -151,10 +176,11 @@ class TemplateParser {
151
176
  }
152
177
  const exprSource = this.source.slice(start, end).trim()
153
178
  this.pos = end + 2
154
- return InterpolationNode(parseExpressionString(exprSource))
179
+ return { ...InterpolationNode(parseExpressionString(exprSource)), line }
155
180
  }
156
181
 
157
182
  parseIfBlock() {
183
+ const line = this.lineAt(this.pos)
158
184
  this.pos += 2 // "{{"
159
185
  this.pos += 3 // "#if"
160
186
  this.skipWhitespace()
@@ -166,10 +192,14 @@ class TemplateParser {
166
192
  this.pos = end + 2
167
193
 
168
194
  const children = this.parseNodes(null, '{{/if}}')
169
- return IfNode(parseExpressionString(conditionSource), children)
195
+ return {
196
+ ...IfNode(parseExpressionString(conditionSource), children),
197
+ line,
198
+ }
170
199
  }
171
200
 
172
201
  parseEachBlock() {
202
+ const line = this.lineAt(this.pos)
173
203
  this.pos += 2 // "{{"
174
204
  this.pos += 5 // "#each"
175
205
  this.skipWhitespace()
@@ -190,10 +220,14 @@ class TemplateParser {
190
220
  const iterableSource = match[2].trim()
191
221
 
192
222
  const children = this.parseNodes(null, '{{/each}}')
193
- return EachNode(itemName, parseExpressionString(iterableSource), children)
223
+ return {
224
+ ...EachNode(itemName, parseExpressionString(iterableSource), children),
225
+ line,
226
+ }
194
227
  }
195
228
 
196
229
  parseElement() {
230
+ const line = this.lineAt(this.pos)
197
231
  this.pos++
198
232
  const tag = this.readTagName()
199
233
  const attributes = this.parseAttributes()
@@ -201,7 +235,7 @@ class TemplateParser {
201
235
  this.skipWhitespace()
202
236
  if (this.remaining().startsWith('/>')) {
203
237
  this.pos += 2
204
- return ElementNode(tag, attributes, [])
238
+ return { ...ElementNode(tag, attributes, []), line }
205
239
  }
206
240
 
207
241
  if (this.source[this.pos] !== '>') {
@@ -223,11 +257,14 @@ class TemplateParser {
223
257
  }
224
258
  const rawContent = this.source.slice(this.pos, closeIndex)
225
259
  this.pos = closeIndex + closeTag.length
226
- return ElementNode(tag, attributes, [TextNode(rawContent)])
260
+ return {
261
+ ...ElementNode(tag, attributes, [TextNode(rawContent)]),
262
+ line,
263
+ }
227
264
  }
228
265
 
229
266
  const children = this.parseNodes(tag)
230
- return ElementNode(tag, attributes, children)
267
+ return { ...ElementNode(tag, attributes, children), line }
231
268
  }
232
269
 
233
270
  consumeClosingTag(expectedTag) {
@@ -269,6 +306,7 @@ class TemplateParser {
269
306
  }
270
307
 
271
308
  parseAttribute() {
309
+ const line = this.lineAt(this.pos)
272
310
  const nameMatch = ATTR_NAME_RE.exec(this.remaining())
273
311
  if (!nameMatch) {
274
312
  throw new Error(`Expected an attribute name at position ${this.pos}`)
@@ -283,7 +321,7 @@ class TemplateParser {
283
321
  // convention, so devs coming from plain HTML don't hit a
284
322
  // surprising "Expected '=' after attribute name" wall.
285
323
  if (this.source[this.pos] !== '=') {
286
- return AttributeNode(name, true, false)
324
+ return { ...AttributeNode(name, true, false), line }
287
325
  }
288
326
 
289
327
  this.pos++
@@ -306,9 +344,12 @@ class TemplateParser {
306
344
 
307
345
  const interpMatch = INTERP_ATTR_RE.exec(rawValue)
308
346
  if (interpMatch) {
309
- return AttributeNode(name, parseExpressionString(interpMatch[1]), true)
347
+ return {
348
+ ...AttributeNode(name, parseExpressionString(interpMatch[1]), true),
349
+ line,
350
+ }
310
351
  }
311
- return AttributeNode(name, rawValue, false)
352
+ return { ...AttributeNode(name, rawValue, false), line }
312
353
  }
313
354
 
314
355
  skipWhitespace() {
@@ -3,57 +3,89 @@
3
3
  * tracking), the same fundamental technique Vue 3 and Solid use to
4
4
  * avoid virtual-DOM diffing entirely. An effect() records which
5
5
  * reactive properties it read; reactive() re-runs exactly the effects
6
- * that depend on a property when that property is written — nothing
6
+ * that depend on a property when that property is written -- nothing
7
7
  * else re-renders.
8
+ *
9
+ * Every effect also tracks (a) which dep Sets it's currently a member
10
+ * of, and (b) which child effects were created while it was running
11
+ * (e.g. an #if/#each block's effect re-creating its children's own
12
+ * effects on every rebuild). Before an effect re-runs, it disposes
13
+ * itself from every dep Set and recursively disposes every child --
14
+ * without this, rebuilding a block's children on every re-render
15
+ * leaks the PREVIOUS render's child effects forever: they stay
16
+ * subscribed, keep firing on every future write to whatever they
17
+ * read, and do so against DOM nodes that have already been removed
18
+ * (whose .parentNode is now null), which throws and can abort
19
+ * whatever action triggered the write mid-way through.
8
20
  */
9
21
 
10
- let activeEffect = null;
11
- const targetMap = new WeakMap();
22
+ let activeEffect = null
23
+ const targetMap = new WeakMap()
12
24
 
13
25
  export function reactive(target) {
14
26
  return new Proxy(target, {
15
27
  get(obj, key, receiver) {
16
- track(obj, key);
17
- return Reflect.get(obj, key, receiver);
28
+ track(obj, key)
29
+ return Reflect.get(obj, key, receiver)
18
30
  },
19
31
  set(obj, key, value, receiver) {
20
- const changed = obj[key] !== value;
21
- const result = Reflect.set(obj, key, value, receiver);
22
- if (changed) trigger(obj, key);
23
- return result;
32
+ const changed = obj[key] !== value
33
+ const result = Reflect.set(obj, key, value, receiver)
34
+ if (changed) trigger(obj, key)
35
+ return result
24
36
  },
25
- });
37
+ })
26
38
  }
27
39
 
28
40
  function track(obj, key) {
29
- if (!activeEffect) return;
30
- let depsMap = targetMap.get(obj);
31
- if (!depsMap) targetMap.set(obj, (depsMap = new Map()));
32
- let dep = depsMap.get(key);
33
- if (!dep) depsMap.set(key, (dep = new Set()));
34
- dep.add(activeEffect);
41
+ if (!activeEffect) return
42
+ let depsMap = targetMap.get(obj)
43
+ if (!depsMap) targetMap.set(obj, (depsMap = new Map()))
44
+ let dep = depsMap.get(key)
45
+ if (!dep) depsMap.set(key, (dep = new Set()))
46
+ dep.add(activeEffect)
47
+ activeEffect.deps.push(dep)
35
48
  }
36
49
 
37
50
  function trigger(obj, key) {
38
- const depsMap = targetMap.get(obj);
39
- if (!depsMap) return;
40
- const dep = depsMap.get(key);
41
- if (!dep) return;
51
+ const depsMap = targetMap.get(obj)
52
+ if (!depsMap) return
53
+ const dep = depsMap.get(key)
54
+ if (!dep) return
42
55
  // Copy before iterating: an effect may re-track (add/remove itself)
43
56
  // while running, which would corrupt the Set mid-iteration.
44
- [...dep].forEach((fn) => fn());
57
+ ;[...dep].forEach((fn) => fn())
58
+ }
59
+
60
+ // Detaches an effect from every dep Set it was previously part of,
61
+ // and disposes every child effect it created during its last run --
62
+ // disposal recurses, so a deeply nested #if inside an #each inside
63
+ // another #if tears down its whole subtree correctly.
64
+ function cleanup(effectFn) {
65
+ for (const dep of effectFn.deps) dep.delete(effectFn)
66
+ effectFn.deps.length = 0
67
+ for (const child of effectFn.children) cleanup(child)
68
+ effectFn.children.length = 0
45
69
  }
46
70
 
47
71
  export function effect(fn) {
48
72
  const wrapped = () => {
49
- const previousEffect = activeEffect;
50
- activeEffect = wrapped;
73
+ cleanup(wrapped)
74
+ const previousEffect = activeEffect
75
+ // Register as a child of whichever effect is currently running
76
+ // (if any), so that when THAT effect re-runs, it disposes this
77
+ // one too -- this is what makes rebuilding an #if/#each block's
78
+ // children safe to do repeatedly without leaking.
79
+ if (previousEffect) previousEffect.children.push(wrapped)
80
+ activeEffect = wrapped
51
81
  try {
52
- fn();
82
+ fn()
53
83
  } finally {
54
- activeEffect = previousEffect;
84
+ activeEffect = previousEffect
55
85
  }
56
- };
57
- wrapped();
58
- return wrapped;
86
+ }
87
+ wrapped.deps = []
88
+ wrapped.children = []
89
+ wrapped()
90
+ return wrapped
59
91
  }