@tylix/compiler 0.3.6 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@tylix/compiler",
3
- "version": "0.3.6",
3
+ "version": "0.3.7",
4
4
  "type": "module",
5
- "keywords": [
5
+ "keywords": [
6
6
  "tylix",
7
7
  "compiler",
8
8
  "ui"
@@ -17,4 +17,4 @@
17
17
  "devDependencies": {
18
18
  "jsdom": "^24.0.0"
19
19
  }
20
- }
20
+ }
@@ -24,7 +24,9 @@ test("generates a zero-parameter method with a single return statement", () => {
24
24
  });
25
25
 
26
26
  test("generates a method with parameters", () => {
27
- const node = MethodNode("setCount", ["value"], [
27
+ // Params are { name, typeAnnotation } objects, the same shape the
28
+ // parser produces.
29
+ const node = MethodNode("setCount", [{ name: "value", typeAnnotation: null }], [
28
30
  ExpressionStatement(AssignmentExpr(MemberExpr(Identifier("this"), "count"), Identifier("value"))),
29
31
  ]);
30
32
 
@@ -76,4 +78,4 @@ test("the generated method source is valid, executable JavaScript", () => {
76
78
  instance.count = 5;
77
79
  instance.increment();
78
80
  assert.equal(instance.count, 6);
79
- });
81
+ });
@@ -5,13 +5,26 @@ import { reactive } from "../runtime/reactive.js";
5
5
  import { Parser } from "../parser/Parser.js";
6
6
  import { Lexer } from "../lexer/Lexer.js";
7
7
 
8
- test("onMount runs automatically on construction", () => {
9
- const source = `state\ncount: 0\nonMount\nthis.count = 99`;
8
+ function buildPageClass(source) {
10
9
  const page = new Parser(new Lexer(source).tokenize()).parse();
11
10
  const classSource = generatePage(page, "Page");
12
- const Page = new Function("reactive", `return ${classSource}`)(reactive);
11
+ return new Function("reactive", `return ${classSource}`)(reactive);
12
+ }
13
+
14
+ // onMount is not invoked from the constructor: the host awaits
15
+ // __ready() (so capabilities are loaded) and then calls __onMount().
16
+ test("onMount does not run on construction", () => {
17
+ const Page = buildPageClass(`state\ncount: 0\nonMount\nthis.count = 99`);
18
+
19
+ const instance = new Page();
20
+ assert.equal(instance.count, 0);
21
+ });
22
+
23
+ test("onMount runs when the host calls __onMount()", () => {
24
+ const Page = buildPageClass(`state\ncount: 0\nonMount\nthis.count = 99`);
13
25
 
14
26
  const instance = new Page();
27
+ instance.__onMount();
15
28
  assert.equal(instance.count, 99);
16
29
  });
17
30
 
@@ -30,4 +43,4 @@ test("async onMount can await before setting state", async () => {
30
43
  const instance = new PageClass();
31
44
  await instance.__onMount();
32
45
  assert.equal(instance.data, 123);
33
- });
46
+ });
@@ -262,9 +262,9 @@ export class Parser {
262
262
  throw new Error(`${message} at line ${token.line}, got ${token.type}`)
263
263
  }
264
264
 
265
- parsePropEntry() {
265
+ parsePropEntry() {
266
266
  const startLine = this.peek().line
267
- const name = this.expect(TokenType.IDENTIFIER, 'Expected prop name').value
267
+ const name = this.parseNameToken('Expected prop name')
268
268
  const optional = this.match(TokenType.QUESTION)
269
269
  this.expect(TokenType.COLON, "Expected ':' after prop name")
270
270
  const propType = this.parseTypeExpression()
@@ -361,7 +361,7 @@ export class Parser {
361
361
  return { ...StateNode(name, value, typeAnnotation), line: startLine }
362
362
  }
363
363
 
364
- parseMethod() {
364
+ parseMethod() {
365
365
  const startLine = this.peek().line
366
366
  const isAsync = this.match(TokenType.ASYNC)
367
367
  const name = this.parseNameToken('Expected method name')
@@ -369,10 +369,7 @@ export class Parser {
369
369
 
370
370
  const params = []
371
371
  while (!this.check(TokenType.RPAREN)) {
372
- const paramName = this.expect(
373
- TokenType.IDENTIFIER,
374
- 'Expected parameter name',
375
- ).value
372
+ const paramName = this.parseNameToken('Expected parameter name')
376
373
  let paramType = null
377
374
  if (this.match(TokenType.COLON)) {
378
375
  paramType = this.parseTypeExpression()
@@ -406,13 +403,13 @@ export class Parser {
406
403
  // property values, and array pattern elements, so `const { a: { b } }
407
404
  // = x` and `const [[a, b]] = x` both fall out for free instead of
408
405
  // needing separate one-level-deep parsing logic in three places.
409
- parseBindingTarget() {
406
+ parseBindingTarget() {
410
407
  if (this.check(TokenType.LBRACE)) return this.parseObjectPattern()
411
408
  if (this.check(TokenType.LBRACKET)) return this.parseArrayPattern()
412
- return this.expect(TokenType.IDENTIFIER, 'Expected a binding name').value
409
+ return this.parseNameToken('Expected a binding name')
413
410
  }
414
411
 
415
- parseObjectPattern() {
412
+ parseObjectPattern() {
416
413
  this.expect(TokenType.LBRACE, "Expected '{' to start destructuring pattern")
417
414
  const properties = []
418
415
  let rest = null
@@ -425,10 +422,7 @@ export class Parser {
425
422
  this.match(TokenType.COMMA)
426
423
  continue
427
424
  }
428
- const key = this.expect(
429
- TokenType.IDENTIFIER,
430
- 'Expected a property name',
431
- ).value
425
+ const key = this.parseNameToken('Expected a property name')
432
426
  let binding = key
433
427
  if (this.match(TokenType.COLON)) {
434
428
  binding = this.parseBindingTarget()
@@ -443,7 +437,6 @@ export class Parser {
443
437
  this.expect(TokenType.RBRACE, "Expected '}' to close destructuring pattern")
444
438
  return ObjectPattern(properties, rest)
445
439
  }
446
-
447
440
  parseArrayPattern() {
448
441
  this.expect(
449
442
  TokenType.LBRACKET,
@@ -1107,14 +1100,11 @@ export class Parser {
1107
1100
  return name
1108
1101
  }
1109
1102
 
1110
- parseObjectTypeLiteral() {
1103
+ parseObjectTypeLiteral() {
1111
1104
  this.expect(TokenType.LBRACE, "Expected '{' to start object type")
1112
1105
  const members = []
1113
1106
  while (!this.check(TokenType.RBRACE)) {
1114
- const key = this.expect(
1115
- TokenType.IDENTIFIER,
1116
- 'Expected a property name',
1117
- ).value
1107
+ const key = this.parseNameToken('Expected a property name')
1118
1108
  const optional = this.match(TokenType.QUESTION)
1119
1109
  this.expect(
1120
1110
  TokenType.COLON,
@@ -8,6 +8,39 @@ function parse(source) {
8
8
  return new Parser(tokens).parse()
9
9
  }
10
10
 
11
+ // AST nodes carry extra bookkeeping fields (line, typeAnnotation,
12
+ // computed, optional) that most of these tests don't care about.
13
+ // pickShape keeps only the keys named in `shape`, so a test asserts
14
+ // on what it means to check and doesn't break when a node gains a
15
+ // field.
16
+ function pickShape(actual, shape) {
17
+ if (Array.isArray(shape)) {
18
+ return Array.isArray(actual)
19
+ ? actual.map((item, i) => pickShape(item, shape[i]))
20
+ : actual
21
+ }
22
+ if (shape && typeof shape === 'object') {
23
+ const out = {}
24
+ for (const key of Object.keys(shape)) {
25
+ out[key] = pickShape(actual?.[key], shape[key])
26
+ }
27
+ return out
28
+ }
29
+ return actual
30
+ }
31
+
32
+ function assertMatches(actual, shape) {
33
+ assert.deepEqual(pickShape(actual, shape), shape)
34
+ }
35
+
36
+ // The same content written braced or bare lands on different lines,
37
+ // so line numbers are dropped before comparing the two ASTs.
38
+ function withoutLines(node) {
39
+ return JSON.parse(
40
+ JSON.stringify(node, (key, value) => (key === 'line' ? undefined : value)),
41
+ )
42
+ }
43
+
11
44
  test('respects operator precedence: multiplication before addition', () => {
12
45
  const source = `action\n compute() {\n return 1 + 2 * 3\n }`
13
46
  const ast = new Parser(new Lexer(source).tokenize()).parse()
@@ -57,14 +90,34 @@ test('parses a template literal with a single interpolation', () => {
57
90
 
58
91
  test('parses a props block', () => {
59
92
  const ast = parse(`props { title: String }`)
60
- assert.deepEqual(ast.props, [
93
+ assertMatches(ast.props, [
94
+ { type: 'Prop', name: 'title', propType: 'String' },
95
+ ])
96
+ })
97
+
98
+ test('parses a bare props block with a prop named title', () => {
99
+ const ast = parse(`props\ntitle: String`)
100
+ assertMatches(ast.props, [
61
101
  { type: 'Prop', name: 'title', propType: 'String' },
62
102
  ])
63
103
  })
64
104
 
105
+ test('accepts other keyword tokens as prop names', () => {
106
+ const ast = parse(`props { title: String, layout: String }`)
107
+ assert.equal(ast.props.length, 2)
108
+ assert.equal(ast.props[0].name, 'title')
109
+ assert.equal(ast.props[1].name, 'layout')
110
+ })
111
+
112
+ test('a page-level title section still parses after a bare props block', () => {
113
+ const ast = parse(`props\nname: String\ntitle "Home"`)
114
+ assert.equal(ast.props.length, 1)
115
+ assert.equal(ast.title, 'Home')
116
+ })
117
+
65
118
  test('parses a state block with number and string values', () => {
66
119
  const ast = parse(`state { count: 0, label: "hi" }`)
67
- assert.deepEqual(ast.state, [
120
+ assertMatches(ast.state, [
68
121
  { type: 'State', name: 'count', value: { type: 'Literal', value: 0 } },
69
122
  { type: 'State', name: 'label', value: { type: 'Literal', value: 'hi' } },
70
123
  ])
@@ -82,7 +135,7 @@ test('parses a computed block with return + member/binary expressions', () => {
82
135
  assert.equal(method.name, 'doubled')
83
136
  assert.deepEqual(method.params, [])
84
137
  assert.equal(method.body[0].type, 'ReturnStatement')
85
- assert.deepEqual(method.body[0].argument, {
138
+ assertMatches(method.body[0].argument, {
86
139
  type: 'BinaryExpression',
87
140
  operator: '*',
88
141
  left: {
@@ -124,7 +177,40 @@ test('parses a method with parameters', () => {
124
177
  }
125
178
  }
126
179
  `)
127
- assert.deepEqual(ast.actions[0].params, ['newValue'])
180
+ // Params carry an optional type annotation, so they are objects.
181
+ assert.deepEqual(ast.actions[0].params, [
182
+ { name: 'newValue', typeAnnotation: null },
183
+ ])
184
+ })
185
+
186
+ test('accepts a keyword token as a method parameter name', () => {
187
+ const ast = parse(`
188
+ action {
189
+ setTitle(title) {
190
+ this.title = title
191
+ }
192
+ }
193
+ `)
194
+ assert.deepEqual(ast.actions[0].params, [
195
+ { name: 'title', typeAnnotation: null },
196
+ ])
197
+ })
198
+
199
+ test('accepts a keyword token as a destructured property and binding name', () => {
200
+ assert.doesNotThrow(() =>
201
+ parse(`
202
+ action {
203
+ load() {
204
+ const { title } = this.data
205
+ const layout = title
206
+ }
207
+ }
208
+ `),
209
+ )
210
+ })
211
+
212
+ test('accepts a keyword token as a key in an object type annotation', () => {
213
+ assert.doesNotThrow(() => parse(`state { post({ title: string }): null }`))
128
214
  })
129
215
 
130
216
  test('parses a full realistic page script', () => {
@@ -195,7 +281,9 @@ test('braced and bare syntax produce identical ASTs for the same content', () =>
195
281
  const bracedPage = new Parser(new Lexer(braced).tokenize()).parse()
196
282
  const barePage = new Parser(new Lexer(bare).tokenize()).parse()
197
283
 
198
- assert.deepEqual(bracedPage.state, barePage.state)
284
+ // Same content, different line numbers (1 vs 2), so compare
285
+ // everything except `line`.
286
+ assert.deepEqual(withoutLines(bracedPage.state), withoutLines(barePage.state))
199
287
  })
200
288
 
201
289
  test('parses a method call with no arguments inside an action body', () => {
@@ -224,4 +312,4 @@ test('parses chained member access followed by a call', () => {
224
312
  assert.equal(call.type, 'CallExpression')
225
313
  assert.equal(call.callee.type, 'MemberExpression')
226
314
  assert.equal(call.callee.property, 'remove')
227
- })
315
+ })
@@ -2,13 +2,27 @@ import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { parseTemplate } from "./parseTemplate.js";
4
4
 
5
+ // Element and Attribute nodes carry a `line` for error reporting.
6
+ // Tests that compare whole nodes drop it first, so they assert on
7
+ // structure and don't break whenever position tracking changes.
8
+ function withoutLines(node) {
9
+ return JSON.parse(
10
+ JSON.stringify(node, (key, value) => (key === "line" ? undefined : value)),
11
+ );
12
+ }
13
+
5
14
  test("parses a single element with text content", () => {
6
15
  const nodes = parseTemplate(`<h1>Hello</h1>`);
7
- assert.deepEqual(nodes, [
16
+ assert.deepEqual(withoutLines(nodes), [
8
17
  { type: "Element", tag: "h1", attributes: [], children: [{ type: "Text", value: "Hello" }] },
9
18
  ]);
10
19
  });
11
20
 
21
+ test("records the source line on elements", () => {
22
+ const nodes = parseTemplate(`<h1>Hello</h1>`);
23
+ assert.equal(nodes[0].line, 1);
24
+ });
25
+
12
26
  test("parses an interpolation node", () => {
13
27
  const nodes = parseTemplate(`{{ count }}`);
14
28
  assert.equal(nodes.length, 1);
@@ -34,7 +48,7 @@ test("parses nested elements", () => {
34
48
 
35
49
  test("parses a static attribute", () => {
36
50
  const nodes = parseTemplate(`<div class="wrapper"></div>`);
37
- assert.deepEqual(nodes[0].attributes, [
51
+ assert.deepEqual(withoutLines(nodes[0].attributes), [
38
52
  { type: "Attribute", name: "class", value: "wrapper", dynamic: false },
39
53
  ]);
40
54
  });
@@ -49,7 +63,9 @@ test("parses a dynamic event-binding attribute using the expression parser", ()
49
63
 
50
64
  test("parses a self-closing element", () => {
51
65
  const nodes = parseTemplate(`<input />`);
52
- assert.deepEqual(nodes, [{ type: "Element", tag: "input", attributes: [], children: [] }]);
66
+ assert.deepEqual(withoutLines(nodes), [
67
+ { type: "Element", tag: "input", attributes: [], children: [] },
68
+ ]);
53
69
  });
54
70
 
55
71
  test("parses the realistic counter template from the design doc", () => {
@@ -93,4 +109,4 @@ test("collapses indentation-only whitespace between tags to nothing", () => {
93
109
  const nodes = parseTemplate(`<div>\n <h1>Hi</h1>\n</div>`);
94
110
  assert.equal(nodes[0].children.length, 1, "pure-whitespace indentation should not become a Text node");
95
111
  assert.equal(nodes[0].children[0].tag, "h1");
96
- });
112
+ });
@@ -35,7 +35,7 @@ template
35
35
  </div>
36
36
  `
37
37
 
38
- const html = renderPageDocument(source)
38
+ const html = await renderPageDocument(source)
39
39
  assert.match(html, /<title>CounterPage<\/title>/)
40
40
 
41
41
  const dom = await loadDocument(html)
@@ -62,7 +62,7 @@ template
62
62
  </div>
63
63
  `
64
64
 
65
- const html = renderPageDocument(source, {}, { props: { id: '42' } })
65
+ const html = await renderPageDocument(source, {}, { props: { id: '42' } })
66
66
  const dom = await loadDocument(html)
67
67
  const span = dom.window.document.querySelector('#app span')
68
68
 
@@ -79,19 +79,19 @@ template
79
79
  style
80
80
  p { color: red; }
81
81
  `
82
- const html = renderPageDocument(source)
82
+ const html = await renderPageDocument(source)
83
83
  assert.match(html, /<style>\s*p \{ color: red; \}\s*<\/style>/)
84
84
  })
85
85
 
86
86
  test('omits the style tag entirely when no style section is present', async () => {
87
87
  const source = `page Home\n\ntemplate\n <p>Hello</p>`
88
- const html = renderPageDocument(source)
88
+ const html = await renderPageDocument(source)
89
89
  assert.doesNotMatch(html, /<style>/)
90
90
  })
91
91
 
92
92
  test('supports a page with no script section at all', async () => {
93
93
  const source = `page Static\n\ntemplate\n <p>Just static markup</p>`
94
- const html = renderPageDocument(source)
94
+ const html = await renderPageDocument(source)
95
95
  const dom = await loadDocument(html)
96
96
  assert.equal(
97
97
  dom.window.document.querySelector('#app p').textContent,
@@ -116,10 +116,10 @@ template
116
116
  </div>
117
117
  `
118
118
 
119
- const html = renderPageDocument(pageSource, { Badge: badgeSource })
119
+ const html = await renderPageDocument(pageSource, { Badge: badgeSource })
120
120
  const dom = await loadDocument(html)
121
121
  const { document } = dom.window
122
122
 
123
123
  assert.equal(document.querySelector('#app h1').textContent, 'Ada Lovelace')
124
124
  assert.equal(document.querySelector('#app .badge').textContent, 'Verified')
125
- })
125
+ })