@tylix/compiler 0.2.0 → 0.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tylix/compiler",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "main": "./src/index.js",
6
6
  "scripts": {
package/src/ast/nodes.js CHANGED
@@ -37,8 +37,21 @@ export function Identifier(name) {
37
37
  return { type: 'Identifier', name }
38
38
  }
39
39
 
40
- export function MemberExpr(object, property, computed = false) {
41
- return { type: 'MemberExpression', object, property, computed }
40
+ export function ObjectPattern(properties, rest = null) {
41
+ return { type: 'ObjectPattern', properties, rest }
42
+ }
43
+
44
+ export function ArrayPattern(elements, rest = null) {
45
+ return { type: 'ArrayPattern', elements, rest }
46
+ }
47
+
48
+ export function MemberExpr(
49
+ object,
50
+ property,
51
+ computed = false,
52
+ optional = false,
53
+ ) {
54
+ return { type: 'MemberExpression', object, property, computed, optional }
42
55
  }
43
56
 
44
57
  export function NewExpr(callee, args) {
@@ -110,6 +123,10 @@ export function UnaryExpr(operator, argument) {
110
123
  return { type: 'UnaryExpression', operator, argument }
111
124
  }
112
125
 
126
+ export function NullishCoalescingExpr(left, right) {
127
+ return { type: 'NullishCoalescingExpression', left, right }
128
+ }
129
+
113
130
  export function TernaryExpr(condition, consequent, alternate) {
114
131
  return { type: 'TernaryExpression', condition, consequent, alternate }
115
132
  }
@@ -145,3 +162,12 @@ export function TemplateLiteralExpr(parts) {
145
162
  export function SpreadElement(argument) {
146
163
  return { type: 'SpreadElement', argument }
147
164
  }
165
+ export function TryStatement(tryBlock, catchParam, catchBlock, finallyBlock) {
166
+ return {
167
+ type: 'TryStatement',
168
+ tryBlock,
169
+ catchParam,
170
+ catchBlock,
171
+ finallyBlock,
172
+ }
173
+ }
@@ -20,9 +20,13 @@ export function generateExpression(node, typed = false) {
20
20
  return node.name
21
21
 
22
22
  case 'MemberExpression':
23
- return node.computed
24
- ? `${generateExpression(node.object, typed)}[${generateExpression(node.property, typed)}]`
25
- : `${generateExpression(node.object, typed)}.${node.property}`
23
+ if (node.computed) {
24
+ return `${generateExpression(node.object, typed)}${node.optional ? '?.' : ''}[${generateExpression(node.property, typed)}]`
25
+ }
26
+ return `${generateExpression(node.object, typed)}${node.optional ? '?.' : '.'}${node.property}`
27
+
28
+ case 'NullishCoalescingExpression':
29
+ return `(${generateExpression(node.left, typed)} ?? ${generateExpression(node.right, typed)})`
26
30
 
27
31
  case 'NewExpression': {
28
32
  const args = node.args.map((a) => generateExpression(a, typed)).join(', ')
@@ -14,7 +14,7 @@ import { generateExpression } from './generateExpression.js'
14
14
  * The generated class expects `reactive` to be in scope where the
15
15
  * module is evaluated (imported from @tylix/compiler's runtime).
16
16
  */
17
- export function generatePage(pageNode, className = 'Page') {
17
+ export function generatePage(pageNode, className = 'Page', target = 'client') {
18
18
  const propAssignments = pageNode.props
19
19
  .map((p) => ` this.${p.name} = props.${p.name};`)
20
20
  .join('\n')
@@ -47,17 +47,23 @@ export function generatePage(pageNode, className = 'Page') {
47
47
  .map((a) => generateMethod(a))
48
48
  .join('\n\n')
49
49
 
50
- const onMountCall = pageNode.onMount ? ` this.__onMount();\n` : ''
50
+ // onMount is only ever emitted into the class at all when
51
+ // generating for the client bundle. Server-side (SSR) output never
52
+ // contains the onMount call OR its method body -- there's no
53
+ // runtime guard to rely on, because the code simply isn't there.
54
+ const onMountCall =
55
+ pageNode.onMount && target === 'client' ? ` this.__onMount();\n` : ''
51
56
 
52
- const onMountMethod = pageNode.onMount
53
- ? (() => {
54
- const body = pageNode.onMount.body
55
- .map((stmt) => ` ${statementSource(stmt)}`)
56
- .join('\n')
57
- const asyncPrefix = pageNode.onMount.isAsync ? 'async ' : ''
58
- return ` ${asyncPrefix}__onMount() {\n${body}\n }`
59
- })()
60
- : ''
57
+ const onMountMethod =
58
+ pageNode.onMount && target === 'client'
59
+ ? (() => {
60
+ const body = pageNode.onMount.body
61
+ .map((stmt) => ` ${statementSource(stmt)}`)
62
+ .join('\n')
63
+ const asyncPrefix = pageNode.onMount.isAsync ? 'async ' : ''
64
+ return ` ${asyncPrefix}__onMount() {\n${body}\n }`
65
+ })()
66
+ : ''
61
67
 
62
68
  return `class ${className} {
63
69
  constructor(props = {}) {
@@ -14,7 +14,7 @@ export function generateStatement(node) {
14
14
  return `${generateExpression(node.expression)};`
15
15
 
16
16
  case 'VariableDeclaration':
17
- return `${node.kind} ${node.name} = ${generateExpression(node.init)};`
17
+ return `${node.kind} ${generateDeclarationTarget(node.name)} = ${generateExpression(node.init)};`
18
18
 
19
19
  case 'IfStatement': {
20
20
  const cond = generateExpression(node.condition)
@@ -58,7 +58,87 @@ export function generateStatement(node) {
58
58
  case 'ContinueStatement':
59
59
  return 'continue;'
60
60
 
61
+ case 'TryStatement': {
62
+ const tryBody = node.tryBlock
63
+ .map((s) => ` ${generateStatement(s)}`)
64
+ .join('\n')
65
+ let out = `try {\n${tryBody}\n }`
66
+
67
+ if (node.catchBlock) {
68
+ const catchBody = node.catchBlock
69
+ .map((s) => ` ${generateStatement(s)}`)
70
+ .join('\n')
71
+ const catchHeader = node.catchParam
72
+ ? `catch (${node.catchParam})`
73
+ : 'catch'
74
+ out += ` ${catchHeader} {\n${catchBody}\n }`
75
+ }
76
+
77
+ if (node.finallyBlock) {
78
+ const finallyBody = node.finallyBlock
79
+ .map((s) => ` ${generateStatement(s)}`)
80
+ .join('\n')
81
+ out += ` finally {\n${finallyBody}\n }`
82
+ }
83
+
84
+ return out
85
+ }
86
+
61
87
  default:
62
88
  throw new Error(`generateStatement: unknown node type "${node.type}"`)
63
89
  }
64
90
  }
91
+
92
+ // Renders a VariableDeclaration's binding target -- a plain identifier
93
+ // (the pre-existing case, unchanged) or a destructuring pattern
94
+ // (ObjectPattern/ArrayPattern), each with optional per-field renames,
95
+ // defaults, and a rest element, matching real JS destructuring syntax
96
+ // so the generated line is exactly what a hand-written `const { a } = x`
97
+ // would look like.
98
+ // Renders a VariableDeclaration's binding target -- a plain identifier
99
+ // (the base case), or -- for destructuring -- a nested ObjectPattern/
100
+ // ArrayPattern, each with optional per-field renames, defaults, and a
101
+ // rest element, recursing through `binding` so patterns can nest
102
+ // arbitrarily deep (e.g. `const { data: { id, name } } = result`)
103
+ // instead of only supporting one flat level.
104
+ function generateDeclarationTarget(target) {
105
+ if (typeof target === 'string') {
106
+ return target
107
+ }
108
+
109
+ if (target.type === 'ObjectPattern') {
110
+ const parts = target.properties.map((p) => {
111
+ const bindingStr = generateDeclarationTarget(p.binding)
112
+ // Only emit "key: binding" when the binding differs from a bare
113
+ // shorthand match on the key itself -- i.e. it was renamed or
114
+ // it's a nested pattern (never just equal to the plain key string).
115
+ const needsColon = typeof p.binding !== 'string' || p.binding !== p.key
116
+ const lhs = needsColon ? `${p.key}: ${bindingStr}` : p.key
117
+ return p.defaultValue
118
+ ? `${lhs} = ${generateExpression(p.defaultValue)}`
119
+ : lhs
120
+ })
121
+ if (target.rest) {
122
+ parts.push(`...${target.rest}`)
123
+ }
124
+ return `{ ${parts.join(', ')} }`
125
+ }
126
+
127
+ if (target.type === 'ArrayPattern') {
128
+ const parts = target.elements.map((el) => {
129
+ if (el === null) return ''
130
+ const bindingStr = generateDeclarationTarget(el.binding)
131
+ return el.defaultValue
132
+ ? `${bindingStr} = ${generateExpression(el.defaultValue)}`
133
+ : bindingStr
134
+ })
135
+ if (target.rest) {
136
+ parts.push(`...${target.rest}`)
137
+ }
138
+ return `[${parts.join(', ')}]`
139
+ }
140
+
141
+ throw new Error(
142
+ `generateDeclarationTarget: unknown pattern type "${target.type}"`,
143
+ )
144
+ }
@@ -240,6 +240,23 @@ function compileElement(node, lines, scope, inSvg = false) {
240
240
  const LIVE_PROPERTY_ATTRS = new Set(['value', 'checked'])
241
241
  const LIVE_PROPERTY_TAGS = new Set(['input', 'textarea', 'select'])
242
242
 
243
+ // Attributes where HTML only cares whether they're *present*, not
244
+ // their string value -- setAttribute(name, "false") is still
245
+ // truthy to the browser, same as "true" or "". These need
246
+ // add/removeAttribute based on the JS value's truthiness, not a
247
+ // literal setAttribute call with the stringified value.
248
+ const BOOLEAN_ATTRS = new Set([
249
+ 'disabled',
250
+ 'checked',
251
+ 'readonly',
252
+ 'required',
253
+ 'selected',
254
+ 'multiple',
255
+ 'hidden',
256
+ 'autofocus',
257
+ 'open',
258
+ ])
259
+
243
260
  function compileAttribute(elVar, tag, attr, lines, scope) {
244
261
  if (EVENT_ATTR_PREFIX.test(attr.name)) {
245
262
  const eventName = attr.name.slice(2).toLowerCase()
@@ -271,15 +288,24 @@ function compileAttribute(elVar, tag, attr, lines, scope) {
271
288
  )
272
289
  return
273
290
  }
291
+
274
292
  if (attr.dynamic) {
275
293
  const expr = generateTemplateExpression(attr.value, scope)
276
294
  const useProperty =
277
295
  LIVE_PROPERTY_ATTRS.has(attr.name) && LIVE_PROPERTY_TAGS.has(tag)
296
+ const useBoolean = BOOLEAN_ATTRS.has(attr.name) && !useProperty
278
297
  if (useProperty) {
279
298
  // Set the live DOM property, not the attribute, so re-renders
280
299
  // after the user has typed (e.g. clearing the form on submit)
281
300
  // actually update what's on screen.
282
301
  lines.push(`effect(() => { ${elVar}.${attr.name} = ${expr}; });`)
302
+ } else if (useBoolean) {
303
+ // Boolean attribute: presence, not string value, is what
304
+ // matters to the browser. Add it (empty string) when truthy,
305
+ // remove it entirely when falsy.
306
+ lines.push(
307
+ `effect(() => { if (${expr}) { ${elVar}.setAttribute(${JSON.stringify(attr.name)}, ""); } else { ${elVar}.removeAttribute(${JSON.stringify(attr.name)}); } });`,
308
+ )
283
309
  } else {
284
310
  lines.push(
285
311
  `effect(() => { ${elVar}.setAttribute(${JSON.stringify(attr.name)}, ${expr}); });`,
@@ -1,51 +1,68 @@
1
1
  import { generateExpression } from './generateExpression.js'
2
2
 
3
- /**
4
- * Like generateExpression, but every Identifier is prefixed with
5
- * "instance." UNLESS it's a local name in `scope` (e.g. an
6
- * {{#each item in items}} loop variable), in which case it's left
7
- * bare -- it refers to the JS for-of loop variable, not a component
8
- * instance property.
9
- */
10
3
  export function generateTemplateExpression(node, scope = new Set()) {
11
4
  if (node.type === 'Identifier') {
12
- // $event is the DOM event object passed into inline handlers,
13
- // not an instance property -- treat it like a loop variable and
14
- // leave it bare rather than prefixing with "instance.".
15
5
  if (node.name === '$event' || scope.has(node.name)) {
16
6
  return node.name
17
7
  }
8
+ if (node.name === 'this') {
9
+ return 'instance'
10
+ }
11
+ // "null", "true", "false", "undefined" are JS keywords, not
12
+ // instance properties -- if the parser is tokenizing them as bare
13
+ // Identifier nodes (rather than Literal nodes), they must NOT be
14
+ // prefixed with "instance.", or comparisons like
15
+ // `serverId is not null` silently compile to
16
+ // `instance.serverId !== instance.null` (always undefined) instead
17
+ // of `instance.serverId !== null`.
18
+ if (
19
+ node.name === 'null' ||
20
+ node.name === 'true' ||
21
+ node.name === 'false' ||
22
+ node.name === 'undefined'
23
+ ) {
24
+ return node.name
25
+ }
18
26
  return `instance.${node.name}`
19
27
  }
28
+
20
29
  if (node.type === 'MemberExpression') {
21
- return node.computed
22
- ? `${generateTemplateExpression(node.object, scope)}[${generateTemplateExpression(node.property, scope)}]`
23
- : `${generateTemplateExpression(node.object, scope)}.${node.property}`
30
+ if (node.computed) {
31
+ return `${generateTemplateExpression(node.object, scope)}${node.optional ? '?.' : ''}[${generateTemplateExpression(node.property, scope)}]`
32
+ }
33
+ return `${generateTemplateExpression(node.object, scope)}${node.optional ? '?.' : '.'}${node.property}`
24
34
  }
35
+
25
36
  if (node.type === 'BinaryExpression') {
26
37
  return `(${generateTemplateExpression(node.left, scope)} ${node.operator} ${generateTemplateExpression(node.right, scope)})`
27
38
  }
39
+
40
+ if (node.type === 'NullishCoalescingExpression') {
41
+ return `(${generateTemplateExpression(node.left, scope)} ?? ${generateTemplateExpression(node.right, scope)})`
42
+ }
43
+
44
+ if (node.type === 'TernaryExpression') {
45
+ return `(${generateTemplateExpression(node.condition, scope)} ? ${generateTemplateExpression(node.consequent, scope)} : ${generateTemplateExpression(node.alternate, scope)})`
46
+ }
47
+
28
48
  if (node.type === 'UnaryExpression') {
29
49
  return `(${node.operator}${generateTemplateExpression(node.argument, scope)})`
30
50
  }
31
51
  if (node.type === 'AssignmentExpression') {
32
52
  return `${generateTemplateExpression(node.target, scope)} = ${generateTemplateExpression(node.value, scope)}`
33
53
  }
34
-
35
54
  if (node.type === 'CallExpression') {
36
55
  const args = node.args
37
56
  .map((a) => generateTemplateExpression(a, scope))
38
57
  .join(', ')
39
58
  return `${generateTemplateExpression(node.callee, scope)}(${args})`
40
59
  }
41
-
42
60
  if (node.type === 'NewExpression') {
43
61
  const args = node.args
44
62
  .map((a) => generateTemplateExpression(a, scope))
45
63
  .join(', ')
46
64
  return `new ${generateTemplateExpression(node.callee, scope)}(${args})`
47
65
  }
48
-
49
66
  if (node.type === 'Literal') {
50
67
  return generateExpression(node)
51
68
  }
@@ -132,6 +132,31 @@ export class Lexer {
132
132
  continue
133
133
  }
134
134
 
135
+ if (
136
+ char === '?' &&
137
+ this.source[this.pos + 1] === '?' &&
138
+ this.source[this.pos + 2] === '='
139
+ ) {
140
+ this.pushToken(TokenType.NULLISH_EQUALS, '??=')
141
+ this.pos += 3
142
+ continue
143
+ }
144
+
145
+ if (char === '?' && this.source[this.pos + 1] === '?') {
146
+ this.pushToken(TokenType.NULLISH, '??')
147
+ this.pos += 2
148
+ continue
149
+ }
150
+ if (
151
+ char === '?' &&
152
+ this.source[this.pos + 1] === '.' &&
153
+ !/[0-9]/.test(this.source[this.pos + 2] ?? '')
154
+ ) {
155
+ this.pushToken(TokenType.QUESTION_DOT, '?.')
156
+ this.pos += 2
157
+ continue
158
+ }
159
+
135
160
  if (char === '?') {
136
161
  this.pushToken(TokenType.QUESTION, '?')
137
162
  this.pos++
@@ -10,6 +10,9 @@ export const TokenType = {
10
10
  PROPS: 'PROPS',
11
11
  ONMOUNT: 'ONMOUNT',
12
12
  NEW: 'NEW',
13
+ TRY: 'TRY',
14
+ CATCH: 'CATCH',
15
+ FINALLY: 'FINALLY',
13
16
 
14
17
  // Literals
15
18
  IDENTIFIER: 'IDENTIFIER',
@@ -31,6 +34,9 @@ export const TokenType = {
31
34
  SPREAD: 'SPREAD', // ...
32
35
  ARROW: 'ARROW', // =>
33
36
  QUESTION: 'QUESTION', // ?
37
+ QUESTION_DOT: 'QUESTION_DOT', // ?.
38
+ NULLISH: 'NULLISH', // ??
39
+ NULLISH_EQUALS: 'NULLISH_EQUALS', // ??=
34
40
  RETURN: 'RETURN',
35
41
  ASYNC: 'ASYNC',
36
42
  AWAIT: 'AWAIT',
@@ -113,4 +119,7 @@ export const KEYWORDS = {
113
119
  repeat: TokenType.REPEAT,
114
120
  break: TokenType.BREAK,
115
121
  continue: TokenType.CONTINUE,
122
+ try: TokenType.TRY,
123
+ catch: TokenType.CATCH,
124
+ finally: TokenType.FINALLY,
116
125
  }
@@ -1,4 +1,4 @@
1
- import { TokenType } from '../lexer/tokenTypes.js'
1
+ import { TokenType, KEYWORDS } from '../lexer/tokenTypes.js'
2
2
  import {
3
3
  PageNode,
4
4
  PropNode,
@@ -8,6 +8,7 @@ import {
8
8
  BinaryExpr,
9
9
  UnaryExpr,
10
10
  TernaryExpr,
11
+ NullishCoalescingExpr,
11
12
  ArrowFunctionExpr,
12
13
  TemplateLiteralExpr,
13
14
  SpreadElement,
@@ -22,6 +23,9 @@ import {
22
23
  VariableDeclaration,
23
24
  ObjectExpr,
24
25
  ArrayExpr,
26
+ ObjectPattern,
27
+ ArrayPattern,
28
+ TryStatement,
25
29
  IfStatement,
26
30
  ForInStatement,
27
31
  ForRangeStatement,
@@ -49,6 +53,8 @@ const MULTIPLICATIVE_SYMBOLS = {
49
53
  [TokenType.PERCENT]: '%',
50
54
  }
51
55
 
56
+ const KEYWORD_TOKEN_TYPES = new Set(Object.values(KEYWORDS))
57
+
52
58
  // Compound assignment desugars at parse time into a plain
53
59
  // AssignmentExpression whose value is a BinaryExpression -- e.g.
54
60
  // `this.count += 1` becomes exactly the same AST as if the dev had
@@ -251,6 +257,103 @@ export class Parser {
251
257
  line: startLine,
252
258
  }
253
259
  }
260
+ // A binding target is anywhere a name is bound to a value: a plain
261
+ // identifier, or -- for destructuring -- a nested object/array
262
+ // pattern. Shared by top-level const/let targets, object pattern
263
+ // property values, and array pattern elements, so `const { a: { b } }
264
+ // = x` and `const [[a, b]] = x` both fall out for free instead of
265
+ // needing separate one-level-deep parsing logic in three places.
266
+ parseBindingTarget() {
267
+ if (this.check(TokenType.LBRACE)) return this.parseObjectPattern()
268
+ if (this.check(TokenType.LBRACKET)) return this.parseArrayPattern()
269
+ return this.expect(TokenType.IDENTIFIER, 'Expected a binding name').value
270
+ }
271
+
272
+ parseObjectPattern() {
273
+ this.expect(TokenType.LBRACE, "Expected '{' to start destructuring pattern")
274
+ const properties = []
275
+ let rest = null
276
+ while (!this.check(TokenType.RBRACE)) {
277
+ if (this.match(TokenType.SPREAD)) {
278
+ rest = this.expect(
279
+ TokenType.IDENTIFIER,
280
+ "Expected identifier after '...'",
281
+ ).value
282
+ this.match(TokenType.COMMA)
283
+ continue
284
+ }
285
+ const key = this.expect(
286
+ TokenType.IDENTIFIER,
287
+ 'Expected a property name',
288
+ ).value
289
+ let binding = key
290
+ if (this.match(TokenType.COLON)) {
291
+ binding = this.parseBindingTarget()
292
+ }
293
+ let defaultValue = null
294
+ if (this.match(TokenType.EQUALS)) {
295
+ defaultValue = this.parseAssignment()
296
+ }
297
+ properties.push({ key, binding, defaultValue })
298
+ this.match(TokenType.COMMA)
299
+ }
300
+ this.expect(TokenType.RBRACE, "Expected '}' to close destructuring pattern")
301
+ return ObjectPattern(properties, rest)
302
+ }
303
+
304
+ parseArrayPattern() {
305
+ this.expect(
306
+ TokenType.LBRACKET,
307
+ "Expected '[' to start array destructuring pattern",
308
+ )
309
+ const elements = []
310
+ let rest = null
311
+ while (!this.check(TokenType.RBRACKET)) {
312
+ if (this.match(TokenType.SPREAD)) {
313
+ rest = this.expect(
314
+ TokenType.IDENTIFIER,
315
+ "Expected identifier after '...'",
316
+ ).value
317
+ this.match(TokenType.COMMA)
318
+ continue
319
+ }
320
+ // A bare comma (or an immediate closing bracket after a comma)
321
+ // is a skipped slot -- `const [, second] = arr` -- distinct from
322
+ // a binding target. Checked before parseBindingTarget() so a
323
+ // hole doesn't fall through to "Expected a binding name".
324
+ if (this.check(TokenType.COMMA)) {
325
+ elements.push(null)
326
+ this.advance()
327
+ continue
328
+ }
329
+ const binding = this.parseBindingTarget()
330
+ let defaultValue = null
331
+ if (this.match(TokenType.EQUALS)) {
332
+ defaultValue = this.parseAssignment()
333
+ }
334
+ elements.push({ binding, defaultValue })
335
+ this.match(TokenType.COMMA)
336
+ }
337
+ this.expect(
338
+ TokenType.RBRACKET,
339
+ "Expected ']' to close array destructuring pattern",
340
+ )
341
+ return ArrayPattern(elements, rest)
342
+ }
343
+
344
+ parsePropertyName(context) {
345
+ const token = this.peek()
346
+ if (
347
+ token.type === TokenType.IDENTIFIER ||
348
+ KEYWORD_TOKEN_TYPES.has(token.type)
349
+ ) {
350
+ this.advance()
351
+ return token.value
352
+ }
353
+ throw new Error(
354
+ `Expected a property name ${context} at line ${token.line}, got ${token.type}`,
355
+ )
356
+ }
254
357
 
255
358
  parseStatement() {
256
359
  const startLine = this.peek().line
@@ -280,6 +383,10 @@ export class Parser {
280
383
  return this.parseRepeatStatement()
281
384
  }
282
385
 
386
+ if (this.match(TokenType.TRY)) {
387
+ return this.parseTryStatement()
388
+ }
389
+
283
390
  if (this.match(TokenType.BREAK)) {
284
391
  this.match(TokenType.SEMICOLON)
285
392
  return BreakStatement()
@@ -292,14 +399,11 @@ export class Parser {
292
399
 
293
400
  if (this.check(TokenType.CONST) || this.check(TokenType.LET)) {
294
401
  const kind = this.advance().type === TokenType.CONST ? 'const' : 'let'
295
- const name = this.expect(
296
- TokenType.IDENTIFIER,
297
- 'Expected variable name',
298
- ).value
402
+ const target = this.parseBindingTarget()
299
403
  this.expect(TokenType.EQUALS, "Expected '=' in variable declaration")
300
404
  const init = this.parseExpression()
301
405
  this.match(TokenType.SEMICOLON)
302
- return VariableDeclaration(kind, name, init)
406
+ return VariableDeclaration(kind, target, init)
303
407
  }
304
408
 
305
409
  const expression = this.parseExpression()
@@ -383,6 +487,45 @@ export class Parser {
383
487
  return RepeatStatement(count, body)
384
488
  }
385
489
 
490
+ parseTryStatement() {
491
+ this.expect(TokenType.LBRACE, "Expected '{' to start try block")
492
+ const tryBlock = []
493
+ while (!this.check(TokenType.RBRACE)) {
494
+ tryBlock.push(this.parseStatement())
495
+ }
496
+ this.expect(TokenType.RBRACE, "Expected '}' to close try block")
497
+
498
+ let catchParam = null
499
+ let catchBlock = null
500
+ if (this.match(TokenType.CATCH)) {
501
+ if (this.match(TokenType.LPAREN)) {
502
+ catchParam = this.expect(
503
+ TokenType.IDENTIFIER,
504
+ 'Expected catch parameter name',
505
+ ).value
506
+ this.expect(TokenType.RPAREN, "Expected ')' after catch parameter")
507
+ }
508
+ this.expect(TokenType.LBRACE, "Expected '{' to start catch block")
509
+ catchBlock = []
510
+ while (!this.check(TokenType.RBRACE)) {
511
+ catchBlock.push(this.parseStatement())
512
+ }
513
+ this.expect(TokenType.RBRACE, "Expected '}' to close catch block")
514
+ }
515
+
516
+ let finallyBlock = null
517
+ if (this.match(TokenType.FINALLY)) {
518
+ this.expect(TokenType.LBRACE, "Expected '{' to start finally block")
519
+ finallyBlock = []
520
+ while (!this.check(TokenType.RBRACE)) {
521
+ finallyBlock.push(this.parseStatement())
522
+ }
523
+ this.expect(TokenType.RBRACE, "Expected '}' to close finally block")
524
+ }
525
+
526
+ return TryStatement(tryBlock, catchParam, catchBlock, finallyBlock)
527
+ }
528
+
386
529
  parseExpression() {
387
530
  return this.parseAssignment()
388
531
  }
@@ -398,7 +541,13 @@ export class Parser {
398
541
  return AssignmentExpr(left, value)
399
542
  }
400
543
 
544
+ if (this.match(TokenType.NULLISH_EQUALS)) {
545
+ const value = this.parseAssignment()
546
+ return AssignmentExpr(left, NullishCoalescingExpr(left, value))
547
+ }
548
+
401
549
  const compoundOp = COMPOUND_ASSIGNMENT_OPS[this.peek().type]
550
+
402
551
  if (compoundOp) {
403
552
  this.advance()
404
553
  const value = this.parseAssignment()
@@ -483,7 +632,7 @@ export class Parser {
483
632
  }
484
633
 
485
634
  parseTernary() {
486
- const condition = this.parseLogicalOr()
635
+ const condition = this.parseNullishCoalescing()
487
636
  if (this.match(TokenType.QUESTION)) {
488
637
  const consequent = this.parseAssignment()
489
638
  this.expect(TokenType.COLON, "Expected ':' in ternary expression")
@@ -493,6 +642,15 @@ export class Parser {
493
642
  return condition
494
643
  }
495
644
 
645
+ parseNullishCoalescing() {
646
+ let left = this.parseLogicalOr()
647
+ while (this.match(TokenType.NULLISH)) {
648
+ const right = this.parseLogicalOr()
649
+ left = NullishCoalescingExpr(left, right)
650
+ }
651
+ return left
652
+ }
653
+
496
654
  parseLogicalOr() {
497
655
  let left = this.parseLogicalAnd()
498
656
  while (this.match(TokenType.OR)) {
@@ -586,10 +744,7 @@ export class Parser {
586
744
  let expr = this.parsePrimary()
587
745
  while (true) {
588
746
  if (this.match(TokenType.DOT)) {
589
- const property = this.expect(
590
- TokenType.IDENTIFIER,
591
- "Expected a property name after '.'",
592
- ).value
747
+ const property = this.parsePropertyName("after '.'")
593
748
  expr = MemberExpr(expr, property)
594
749
  continue
595
750
  }
@@ -606,6 +761,22 @@ export class Parser {
606
761
  expr = CallExpr(expr, this.parseCallArguments())
607
762
  continue
608
763
  }
764
+
765
+ if (this.match(TokenType.QUESTION_DOT)) {
766
+ if (this.match(TokenType.LBRACKET)) {
767
+ const property = this.parseExpression()
768
+ this.expect(
769
+ TokenType.RBRACKET,
770
+ "Expected ']' to close optional computed member access",
771
+ )
772
+ expr = MemberExpr(expr, property, true, true)
773
+ continue
774
+ }
775
+ const property = this.parsePropertyName("after '?.'")
776
+ expr = MemberExpr(expr, property, false, true)
777
+ continue
778
+ }
779
+
609
780
  break
610
781
  }
611
782
  return expr
@@ -658,8 +829,23 @@ export class Parser {
658
829
  }
659
830
 
660
831
  if (this.check(TokenType.IDENTIFIER)) {
661
- return Identifier(this.advance().value)
832
+ const name = this.advance().value
833
+ // "null"/"true"/"false"/"undefined" are lexed as plain identifier
834
+ // tokens (there's no separate keyword TokenType for them), but
835
+ // they're JS keyword literals, not variable/state references.
836
+ // Emitting them as Literal here -- instead of Identifier -- means
837
+ // every downstream consumer (generateExpression,
838
+ // generateTemplateExpression, and anything added later) treats
839
+ // them correctly by construction, rather than each one needing its
840
+ // own special-case list of magic strings to avoid prefixing them
841
+ // with "instance.".
842
+ if (name === 'null') return Literal(null)
843
+ if (name === 'undefined') return Literal(undefined)
844
+ if (name === 'true') return Literal(true)
845
+ if (name === 'false') return Literal(false)
846
+ return Identifier(name)
662
847
  }
848
+
663
849
  if (this.match(TokenType.LPAREN)) {
664
850
  const expr = this.parseExpression()
665
851
  this.expect(
@@ -771,9 +957,18 @@ export class Parser {
771
957
  parseObjectLiteral() {
772
958
  const properties = []
773
959
  while (!this.check(TokenType.RBRACE)) {
774
- const key = this.check(TokenType.STRING)
960
+ const isString = this.check(TokenType.STRING)
961
+ const key = isString
775
962
  ? this.advance().value
776
963
  : this.expect(TokenType.IDENTIFIER, 'Expected an object key').value
964
+
965
+ if (!isString && !this.check(TokenType.COLON)) {
966
+ // Shorthand: { name } means { name: name }
967
+ properties.push({ key, value: Identifier(key) })
968
+ this.match(TokenType.COMMA)
969
+ continue
970
+ }
971
+
777
972
  this.expect(TokenType.COLON, "Expected ':' after object key")
778
973
  const value = this.parseExpression()
779
974
  properties.push({ key, value })
@@ -6,6 +6,16 @@
6
6
  * that depend on a property when that property is written -- nothing
7
7
  * else re-renders.
8
8
  *
9
+ * reactive() wraps nested objects/arrays lazily, on read: when a get
10
+ * trap returns a value that is itself an object, that value is wrapped
11
+ * in reactive() too (and memoized, so repeated reads of the same
12
+ * nested object return the same Proxy identity rather than a fresh
13
+ * wrapper each time). Without this, only the top-level keys passed to
14
+ * reactive() are ever tracked -- writes to a property of an object
15
+ * *assigned into* a state field (e.g. a resource object's .data) are
16
+ * invisible to the dependency graph, because get() would otherwise
17
+ * hand back the raw, unwrapped object.
18
+ *
9
19
  * Every effect also tracks (a) which dep Sets it's currently a member
10
20
  * of, and (b) which child effects were created while it was running
11
21
  * (e.g. an #if/#each block's effect re-creating its children's own
@@ -22,11 +32,36 @@
22
32
  let activeEffect = null
23
33
  const targetMap = new WeakMap()
24
34
 
35
+ // Memoizes target -> proxy so re-reading the same nested object
36
+ // (e.g. a resource object stored in state, read on every render)
37
+ // returns the same Proxy instance instead of a new wrapper each time.
38
+ // Without this, dependencies tracked against one wrapper would never
39
+ // match the wrapper an effect reads on a later pass, and triggers
40
+ // would silently miss their subscribers.
41
+ const reactiveMap = new WeakMap()
42
+
43
+ function isObject(val) {
44
+ return val !== null && typeof val === 'object'
45
+ }
46
+
25
47
  export function reactive(target) {
26
- return new Proxy(target, {
48
+ if (!isObject(target)) return target
49
+
50
+ // Already-reactive objects (including ones we've handed out before)
51
+ // shouldn't get double-wrapped -- wrapping a Proxy in another Proxy
52
+ // would track/trigger through two independent dep graphs for the
53
+ // same logical object.
54
+ if (reactiveMap.has(target)) return reactiveMap.get(target)
55
+
56
+ const proxy = new Proxy(target, {
27
57
  get(obj, key, receiver) {
28
58
  track(obj, key)
29
- return Reflect.get(obj, key, receiver)
59
+ const result = Reflect.get(obj, key, receiver)
60
+ // Lazily wrap nested objects/arrays so writes to THEIR
61
+ // properties are tracked too -- e.g. state.postsResource.data =
62
+ // [...] needs postsResource itself to have been returned as a
63
+ // reactive proxy for this assignment to hit the set trap below.
64
+ return isObject(result) ? reactive(result) : result
30
65
  },
31
66
  set(obj, key, value, receiver) {
32
67
  const changed = obj[key] !== value
@@ -35,6 +70,9 @@ export function reactive(target) {
35
70
  return result
36
71
  },
37
72
  })
73
+
74
+ reactiveMap.set(target, proxy)
75
+ return proxy
38
76
  }
39
77
 
40
78
  function track(obj, key) {
@@ -51,9 +89,9 @@ function trigger(obj, key) {
51
89
  const depsMap = targetMap.get(obj)
52
90
  if (!depsMap) return
53
91
  const dep = depsMap.get(key)
54
- if (!dep) return
55
- // Copy before iterating: an effect may re-track (add/remove itself)
56
- // while running, which would corrupt the Set mid-iteration.
92
+ if (!dep)
93
+ return // Copy before iterating: an effect may re-track (add/remove itself)
94
+ // while running, which would corrupt the Set mid-iteration.
57
95
  ;[...dep].forEach((fn) => fn())
58
96
  }
59
97
 
@@ -2,11 +2,16 @@ import ts from 'typescript'
2
2
  import { fileURLToPath } from 'node:url'
3
3
 
4
4
  const VIRTUAL_FILE_NAME = '__tylix_virtual_page.ts'
5
+ const API_HELPERS_VIRTUAL_FILE_NAME = '__tylix_virtual_api_helpers.ts'
5
6
  const GLOBALS_FILE = fileURLToPath(
6
7
  new URL('./tylix-globals.d.ts', import.meta.url),
7
8
  )
8
9
 
9
- export function typecheckSource(virtualSource, compilerOptions = {}) {
10
+ export function typecheckSource(
11
+ virtualSource,
12
+ apiHelpersSource = '',
13
+ compilerOptions = {},
14
+ ) {
10
15
  const options = {
11
16
  strict: true,
12
17
  target: ts.ScriptTarget.ES2022,
@@ -22,18 +27,31 @@ export function typecheckSource(virtualSource, compilerOptions = {}) {
22
27
  if (fileName === VIRTUAL_FILE_NAME) {
23
28
  return ts.createSourceFile(fileName, virtualSource, languageVersion, true)
24
29
  }
30
+ if (fileName === API_HELPERS_VIRTUAL_FILE_NAME) {
31
+ return ts.createSourceFile(
32
+ fileName,
33
+ apiHelpersSource,
34
+ languageVersion,
35
+ true,
36
+ )
37
+ }
25
38
  return originalGetSourceFile(fileName, languageVersion, ...rest)
26
39
  }
27
40
  host.fileExists = (fileName) =>
28
- fileName === VIRTUAL_FILE_NAME || ts.sys.fileExists(fileName)
29
- host.readFile = (fileName) =>
30
- fileName === VIRTUAL_FILE_NAME ? virtualSource : ts.sys.readFile(fileName)
41
+ fileName === VIRTUAL_FILE_NAME ||
42
+ fileName === API_HELPERS_VIRTUAL_FILE_NAME ||
43
+ ts.sys.fileExists(fileName)
44
+ host.readFile = (fileName) => {
45
+ if (fileName === VIRTUAL_FILE_NAME) return virtualSource
46
+ if (fileName === API_HELPERS_VIRTUAL_FILE_NAME) return apiHelpersSource
47
+ return ts.sys.readFile(fileName)
48
+ }
49
+
50
+ const rootFiles = apiHelpersSource
51
+ ? [VIRTUAL_FILE_NAME, API_HELPERS_VIRTUAL_FILE_NAME, GLOBALS_FILE]
52
+ : [VIRTUAL_FILE_NAME, GLOBALS_FILE]
31
53
 
32
- const program = ts.createProgram(
33
- [VIRTUAL_FILE_NAME, GLOBALS_FILE],
34
- options,
35
- host,
36
- )
54
+ const program = ts.createProgram(rootFiles, options, host)
37
55
  const diagnostics = ts.getPreEmitDiagnostics(program)
38
56
 
39
57
  return diagnostics
@@ -21,6 +21,15 @@ export function typedTemplateExpr(node, scope) {
21
21
  if (node.type === 'UnaryExpression') {
22
22
  return `(${node.operator}${typedTemplateExpr(node.argument, scope)})`
23
23
  }
24
+
25
+ if (node.type === 'TernaryExpression') {
26
+ return `(${typedTemplateExpr(node.condition, scope)} ? ${typedTemplateExpr(node.consequent, scope)} : ${typedTemplateExpr(node.alternate, scope)})`
27
+ }
28
+
29
+ if (node.type === 'NullishCoalescingExpression') {
30
+ return `(${typedTemplateExpr(node.left, scope)} ?? ${typedTemplateExpr(node.right, scope)})`
31
+ }
32
+
24
33
  if (node.type === 'AssignmentExpression') {
25
34
  return `${typedTemplateExpr(node.target, scope)} = ${typedTemplateExpr(node.value, scope)}`
26
35
  }
@@ -19,7 +19,7 @@ import { typecheckSource } from './typecheck/typecheckVirtualFile.js'
19
19
  // at all and floods the diagnostics list with dozens of
20
20
  // cascading-recovery errors, none of which point at anything wrong
21
21
  // in the actual .tyx source.
22
- export function typecheckPage(source) {
22
+ export function typecheckPage(source, apiHelpersSource = '') {
23
23
  const { pageName, script, template, scriptStartLine } = parsePageFile(source)
24
24
 
25
25
  const pageNode =
@@ -35,7 +35,7 @@ export function typecheckPage(source) {
35
35
  pageName,
36
36
  templateNodes,
37
37
  )
38
- const diagnostics = typecheckSource(virtualSource)
38
+ const diagnostics = typecheckSource(virtualSource, apiHelpersSource)
39
39
 
40
40
  return diagnostics.map((d) => {
41
41
  const scriptLine = mapVirtualLineToSource(lineMap, d.virtualLine)