@tylix/compiler 0.5.2 → 0.6.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.
@@ -1,16 +1,41 @@
1
1
  import { generateStatement } from './generateStatement.js'
2
2
 
3
3
  // Note: generateStatement.js imports generateExpression and this file
4
- // imports generateStatement (block-bodied arrows need it). That
5
- // circular import is safe in ES modules because both are hoisted
6
- // function declarations only called at runtime, never at load time.
4
+ // imports generateStatement (block-bodied arrows and function
5
+ // expressions need it). That circular import is safe in ES modules
6
+ // because both are hoisted function declarations only called at
7
+ // runtime, never at load time.
7
8
 
8
- // Word operators (typeof) need a space before their operand;
9
- // symbolic ones (!, -) must not get one.
9
+ // Word operators (typeof, delete, void) need a space before their
10
+ // operand; symbolic ones (!, ~, -) must not get one.
10
11
  function unaryPrefix(operator) {
11
12
  return /^[a-z]/i.test(operator) ? `${operator} ` : operator
12
13
  }
13
14
 
15
+ /**
16
+ * Renders a parameter list: [{ name, typeAnnotation, defaultValue, rest }].
17
+ * `typed` adds `: Type` annotations (falling back to `any`, or `any[]`
18
+ * for rest params) for the virtual .ts file; real JS output omits them.
19
+ */
20
+ export function generateParams(params, typed = false) {
21
+ return params
22
+ .map((p) => {
23
+ const rest = p.rest ? '...' : ''
24
+ const type = typed
25
+ ? `: ${p.typeAnnotation ?? (p.rest ? 'any[]' : 'any')}`
26
+ : ''
27
+ const def = p.defaultValue
28
+ ? ` = ${generateExpression(p.defaultValue, typed)}`
29
+ : ''
30
+ return `${rest}${p.name}${type}${def}`
31
+ })
32
+ .join(', ')
33
+ }
34
+
35
+ function statementsInline(body, typed) {
36
+ return body.map((s) => generateStatement(s, typed)).join(' ')
37
+ }
38
+
14
39
  /**
15
40
  * Compiles a single expression AST node into a JS (or, when
16
41
  * typed=true, TypeScript) source string. Used both for method-body
@@ -18,9 +43,12 @@ function unaryPrefix(operator) {
18
43
  * and the virtual .ts file handed to the TypeScript compiler API
19
44
  * (typed=true) -- one source of truth for expression -> source
20
45
  * translation, so the two outputs can never structurally drift from
21
- * each other. `typed` only changes ONE thing: whether an arrow
22
- * function's params get a `: Type` annotation. Everything else emits
23
- * identically either way.
46
+ * each other. `typed` only changes whether parameters get `: Type`
47
+ * annotations. Everything else emits identically either way.
48
+ *
49
+ * `await` and assignment are always parenthesized: `(await f()).x`
50
+ * and `ok && (count = count + 1)` are only valid JS with the parens,
51
+ * and the extra pair is harmless at statement level.
24
52
  */
25
53
  export function generateExpression(node, typed = false) {
26
54
  switch (node.type) {
@@ -57,18 +85,23 @@ export function generateExpression(node, typed = false) {
57
85
 
58
86
  case 'ArrowFunctionExpression': {
59
87
  // paramTypes is a parallel array of type strings or null,
60
- // populated by tryParseArrowFunction when a dev writes
88
+ // populated by tryParseSyncArrow when a dev writes
61
89
  // `f: Post => ...`; absent/null entries mean "no annotation
62
90
  // was written" -- in typed mode those fall back to `any`
63
91
  // rather than being left bare, since a bare untyped param in a
64
92
  // .ts arrow function has no implicit-any exemption the way
65
- // real JS does.
93
+ // real JS does. paramDefaults is a parallel array of default
94
+ // value expressions (or null).
66
95
  const paramTypes = node.paramTypes ?? node.params.map(() => null)
96
+ const paramDefaults = node.paramDefaults ?? node.params.map(() => null)
67
97
  const params = node.params
68
98
  .map((name, i) => {
69
- if (!typed) return name
70
- const paramType = paramTypes[i]
71
- return `${name}: ${paramType ?? 'any'}`
99
+ let out = name
100
+ if (typed) out = `${name}: ${paramTypes[i] ?? 'any'}`
101
+ if (paramDefaults[i]) {
102
+ out += ` = ${generateExpression(paramDefaults[i], typed)}`
103
+ }
104
+ return out
72
105
  })
73
106
  .join(', ')
74
107
  const asyncPrefix = node.isAsync ? 'async ' : ''
@@ -77,10 +110,7 @@ export function generateExpression(node, typed = false) {
77
110
  // one line separated by spaces; multi-line statements (if,
78
111
  // for, try) keep their own newlines, which is still valid JS.
79
112
  if (node.body.type === 'BlockStatement') {
80
- const stmts = node.body.body
81
- .map((s) => generateStatement(s, typed))
82
- .join(' ')
83
- return `${asyncPrefix}(${params}) => { ${stmts} }`
113
+ return `${asyncPrefix}(${params}) => { ${statementsInline(node.body.body, typed)} }`
84
114
  }
85
115
 
86
116
  // Expression body is always parenthesized so an object literal
@@ -88,6 +118,12 @@ export function generateExpression(node, typed = false) {
88
118
  return `${asyncPrefix}(${params}) => (${generateExpression(node.body, typed)})`
89
119
  }
90
120
 
121
+ case 'FunctionExpression': {
122
+ const asyncPrefix = node.isAsync ? 'async ' : ''
123
+ const name = node.name ? ` ${node.name}` : ''
124
+ return `(${asyncPrefix}function${name}(${generateParams(node.params, typed)}) { ${statementsInline(node.body, typed)} })`
125
+ }
126
+
91
127
  case 'TemplateLiteralExpression': {
92
128
  const inner = node.parts
93
129
  .map((p) =>
@@ -100,7 +136,7 @@ export function generateExpression(node, typed = false) {
100
136
  }
101
137
 
102
138
  case 'AssignmentExpression':
103
- return `${generateExpression(node.target, typed)} = ${generateExpression(node.value, typed)}`
139
+ return `(${generateExpression(node.target, typed)} = ${generateExpression(node.value, typed)})`
104
140
 
105
141
  case 'CallExpression': {
106
142
  const args = node.args
@@ -110,7 +146,7 @@ export function generateExpression(node, typed = false) {
110
146
  }
111
147
 
112
148
  case 'AwaitExpression':
113
- return `await ${generateExpression(node.argument, typed)}`
149
+ return `(await ${generateExpression(node.argument, typed)})`
114
150
 
115
151
  case 'SpreadElement':
116
152
  return `...${generateExpression(node.argument, typed)}`
@@ -118,12 +154,20 @@ export function generateExpression(node, typed = false) {
118
154
  case 'ObjectExpression': {
119
155
  // Spread entries have key === null and spread === true (see
120
156
  // Parser.parseObjectLiteral), so check p.spread before p.key.
157
+ // Computed keys carry keyExpr; method shorthand carries
158
+ // method === true with a FunctionExpression value.
121
159
  const props = node.properties
122
- .map((p) =>
123
- p.spread
124
- ? `...${generateExpression(p.value, typed)}`
125
- : `${JSON.stringify(p.key)}: ${generateExpression(p.value, typed)}`,
126
- )
160
+ .map((p) => {
161
+ if (p.spread) return `...${generateExpression(p.value, typed)}`
162
+ const keySrc = p.keyExpr
163
+ ? `[${generateExpression(p.keyExpr, typed)}]`
164
+ : JSON.stringify(p.key)
165
+ if (p.method) {
166
+ const f = p.value
167
+ return `${f.isAsync ? 'async ' : ''}${keySrc}(${generateParams(f.params, typed)}) { ${statementsInline(f.body, typed)} }`
168
+ }
169
+ return `${keySrc}: ${generateExpression(p.value, typed)}`
170
+ })
127
171
  .join(', ')
128
172
  return `{ ${props} }`
129
173
  }
@@ -1,15 +1,17 @@
1
1
  import { generateStatement } from './generateStatement.js'
2
+ import { generateParams } from './generateExpression.js'
2
3
 
3
4
  /**
4
5
  * Compiles a MethodNode (used for both `computed` and `action` entries)
5
6
  * into a JS class method source string, indented for readability in
6
- * generated output.
7
+ * generated output. Parameters may have defaults (`page = 1`) and rest
8
+ * (`...args`).
7
9
  */
8
10
  export function generateMethod(node) {
9
- const params = node.params.map((p) => p.name).join(', ')
11
+ const params = generateParams(node.params)
10
12
  const body = node.body
11
13
  .map((stmt) => ` ${generateStatement(stmt)}`)
12
14
  .join('\n')
13
15
  const asyncPrefix = node.isAsync ? 'async ' : ''
14
16
  return ` ${asyncPrefix}${node.name}(${params}) {\n${body}\n }`
15
- }
17
+ }
@@ -1,8 +1,36 @@
1
1
  import { generateMethod } from './generateMethod.js'
2
2
  import { generateExpression } from './generateExpression.js'
3
+ import { generateStatement } from './generateStatement.js'
4
+
5
+ function statementSource(stmt) {
6
+ return generateStatement(stmt)
7
+ }
8
+
9
+ // A prop, state field, computed, action or capability that share a
10
+ // name all become members of the same class, so the later definition
11
+ // silently wins (or the constructor throws). Catch it at compile time.
12
+ function assertUniqueMembers(pageNode, className, capabilityNames) {
13
+ const seen = new Map()
14
+ const claim = (name, kind) => {
15
+ if (seen.has(name)) {
16
+ throw new Error(
17
+ `${className}: "${name}" is declared as both ${seen.get(name)} and ${kind}; names must be unique within a page`,
18
+ )
19
+ }
20
+ seen.set(name, kind)
21
+ }
22
+ for (const p of pageNode.props ?? []) claim(p.name, 'a prop')
23
+ for (const s of pageNode.state ?? []) claim(s.name, 'a state field')
24
+ for (const c of pageNode.computed ?? []) claim(c.name, 'a computed')
25
+ for (const a of pageNode.actions ?? []) claim(a.name, 'an action')
26
+ for (const n of capabilityNames) claim(n, 'a capability')
27
+ }
3
28
 
4
29
  /**
5
30
  * Compiles a full PageNode into JS source defining a component class.
31
+ * - props are lazy getters over `this.__props`, so a parent that
32
+ * passes `{ get value() { return count } }` stays live. Assigning
33
+ * to a prop stores a local (reactive) override.
6
34
  * - state entries become reactive-backed getter/setter pairs, so
7
35
  * `this.count` reads/writes go through the reactive() proxy and
8
36
  * correctly trigger dependent effects (template re-renders, computed
@@ -20,9 +48,43 @@ import { generateExpression } from './generateExpression.js'
20
48
  * @tylix/compiler's runtime).
21
49
  */
22
50
  export function generatePage(pageNode, className = 'Page', target = 'client') {
23
- const propAssignments = pageNode.props
24
- .map((p) => ` this.${p.name} = props.${p.name};`)
25
- .join('\n')
51
+ // pageNode.uses/needs/background may each name capabilities the page
52
+ // reads from directly (Auth.user, Theme.mode, etc.) --
53
+ // substituteCapabilityRefs already treats all three as the same
54
+ // "capability name" pool when rewriting bare references to
55
+ // `this.<Name>`, so the getters generated here must cover the same
56
+ // pool, not just `uses` alone.
57
+ const capabilityRefs = [
58
+ ...(pageNode.uses ?? []),
59
+ ...(pageNode.needs ?? []),
60
+ ...(pageNode.background ?? []),
61
+ ]
62
+ const seenCapabilities = new Set()
63
+ const uniqueCapabilityRefs = capabilityRefs.filter((c) => {
64
+ if (seenCapabilities.has(c.name)) return false
65
+ seenCapabilities.add(c.name)
66
+ return true
67
+ })
68
+
69
+ assertUniqueMembers(pageNode, className, seenCapabilities)
70
+
71
+ const hasProps = pageNode.props.length > 0
72
+ const propInit = hasProps
73
+ ? ` this.__props = props;\n this.__propOverrides = reactive({});\n`
74
+ : ''
75
+
76
+ const propAccessors = pageNode.props
77
+ .map(
78
+ (p) => ` get ${p.name}() {
79
+ const overrides = this.__propOverrides;
80
+ const local = overrides.${p.name};
81
+ return Object.prototype.hasOwnProperty.call(overrides, ${JSON.stringify(p.name)}) ? local : this.__props.${p.name};
82
+ }
83
+ set ${p.name}(value) {
84
+ this.__propOverrides.${p.name} = value;
85
+ }`,
86
+ )
87
+ .join('\n\n')
26
88
 
27
89
  const stateInit = pageNode.state
28
90
  .map((s) => ` ${s.name}: ${generateExpression(s.value)},`)
@@ -39,28 +101,6 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
39
101
  )
40
102
  .join('\n\n')
41
103
 
42
- // pageNode.uses may be absent on older/pre-capability ASTs (e.g.
43
- // anything compiled before this field existed), so default to []
44
- // rather than assuming every caller has been updated.
45
- // pageNode.uses/needs/background may each name capabilities the page
46
- // reads from directly (Auth.user, Theme.mode, etc.) -- substituteCapabilityRefs
47
- // already treats all three as the same "capability name" pool when
48
- // rewriting bare references to `this.<Name>`, so the getters generated
49
- // here must cover the same pool, not just `uses` alone, or a
50
- // needs-only or background-only capability resolves to undefined at
51
- // runtime with no compile-time signal that anything's wrong.
52
- const capabilityRefs = [
53
- ...(pageNode.uses ?? []),
54
- ...(pageNode.needs ?? []),
55
- ...(pageNode.background ?? []),
56
- ]
57
- const seenCapabilities = new Set()
58
- const uniqueCapabilityRefs = capabilityRefs.filter((c) => {
59
- if (seenCapabilities.has(c.name)) return false
60
- seenCapabilities.add(c.name)
61
- return true
62
- })
63
-
64
104
  const usesAccessors = uniqueCapabilityRefs
65
105
  .map(
66
106
  (u) => ` get ${u.name}() {
@@ -112,14 +152,12 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
112
152
  // contains the onMount call OR its method body -- there's no
113
153
  // runtime guard to rely on, because the code simply isn't there.
114
154
  //
115
- // IMPORTANT: onMount is no longer invoked from inside the
116
- // constructor. Pages that declare `needs` capabilities must have
117
- // those capabilities' async init() fully resolved (via __ready())
118
- // before onMount runs, or onMount's own logic (e.g. redirecting
119
- // based on Auth.user) races against that resolution and reads
120
- // stale/uninitialized capability state. The caller (renderPageDocument.js)
121
- // is responsible for awaiting __ready() and then calling __onMount()
122
- // explicitly, in that order.
155
+ // onMount is not invoked from inside the constructor: pages that
156
+ // declare `needs` capabilities must have those capabilities' async
157
+ // init() fully resolved (via __ready()) before onMount runs. The
158
+ // caller (renderPageDocument.js) awaits __ready() and then calls
159
+ // __onMount() explicitly, in that order -- for pages, layouts and
160
+ // child components alike.
123
161
  const onMountMethod =
124
162
  pageNode.onMount && target === 'client'
125
163
  ? (() => {
@@ -133,19 +171,11 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
133
171
 
134
172
  return `class ${className} {
135
173
  constructor(props = {}) {
136
- ${propAssignments ? propAssignments + '\n' : ''} this.__state = reactive({
174
+ ${propInit} this.__state = reactive({
137
175
  ${stateInit}
138
176
  });
139
177
  ${backgroundResolution ? backgroundResolution + '\n' : ''} }
140
178
 
141
- ${[stateAccessors, usesAccessors, computedGetters, actionMethods, readyMethod, onMountMethod].filter(Boolean).join('\n\n')}
179
+ ${[propAccessors, stateAccessors, usesAccessors, computedGetters, actionMethods, readyMethod, onMountMethod].filter(Boolean).join('\n\n')}
142
180
  }`
143
- }
144
-
145
- // Local import kept separate from generateMethod's own statement
146
- // formatting so computed getters and state accessors can share the
147
- // same statement codegen without generateMethod's parameter handling.
148
- import { generateStatement } from './generateStatement.js'
149
- function statementSource(stmt) {
150
- return generateStatement(stmt)
151
- }
181
+ }
@@ -1,4 +1,4 @@
1
- import { generateExpression } from './generateExpression.js'
1
+ import { generateExpression, generateParams } from './generateExpression.js'
2
2
 
3
3
  /**
4
4
  * Compiles a single statement AST node into a JS source line.
@@ -14,6 +14,9 @@ export function generateStatement(node, typed = false) {
14
14
  list.map((s) => ` ${generateStatement(s, typed)}`).join('\n')
15
15
 
16
16
  switch (node.type) {
17
+ case 'EmptyStatement':
18
+ return ';'
19
+
17
20
  case 'ReturnStatement':
18
21
  return node.argument ? `return ${expr(node.argument)};` : 'return;'
19
22
 
@@ -24,7 +27,10 @@ export function generateStatement(node, typed = false) {
24
27
  return `${expr(node.expression)};`
25
28
 
26
29
  case 'VariableDeclaration':
27
- return `${node.kind} ${generateDeclarationTarget(node.name, typed)} = ${expr(node.init)};`
30
+ return `${declarationSource(node, typed)};`
31
+
32
+ case 'FunctionDeclaration':
33
+ return `${node.isAsync ? 'async ' : ''}function ${node.name}(${generateParams(node.params, typed)}) {\n${stmts(node.body)}\n }`
28
34
 
29
35
  case 'IfStatement': {
30
36
  let out = `if (${expr(node.condition)}) {\n${stmts(node.consequent)}\n }`
@@ -37,6 +43,9 @@ export function generateStatement(node, typed = false) {
37
43
  case 'WhileStatement':
38
44
  return `while (${expr(node.condition)}) {\n${stmts(node.body)}\n }`
39
45
 
46
+ case 'DoWhileStatement':
47
+ return `do {\n${stmts(node.body)}\n } while (${expr(node.condition)});`
48
+
40
49
  // Each clause body is wrapped in its own braces so `const`/`let`
41
50
  // declared in one case can't collide with another, and a `break`
42
51
  // is appended so there is never accidental fallthrough. (A
@@ -54,7 +63,13 @@ export function generateStatement(node, typed = false) {
54
63
  }
55
64
 
56
65
  case 'ForInStatement':
57
- return `for (const ${node.varName} of ${expr(node.iterable)}) {\n${stmts(node.body)}\n }`
66
+ return `for (${node.declKind ?? 'const'} ${generateDeclarationTarget(node.varName, typed)} of ${expr(node.iterable)}) {\n${stmts(node.body)}\n }`
67
+
68
+ case 'ForKeysStatement':
69
+ return `for (${node.declKind ?? 'const'} ${generateDeclarationTarget(node.varName, typed)} in ${expr(node.object)}) {\n${stmts(node.body)}\n }`
70
+
71
+ case 'ForStatement':
72
+ return `for (${forHeaderSource(node, typed)}) {\n${stmts(node.body)}\n }`
58
73
 
59
74
  case 'ForRangeStatement':
60
75
  return `for (let ${node.varName} = ${expr(node.start)}; ${node.varName} < ${expr(node.end)}; ${node.varName}++) {\n${stmts(node.body)}\n }`
@@ -90,15 +105,44 @@ export function generateStatement(node, typed = false) {
90
105
  }
91
106
  }
92
107
 
93
- // Renders a VariableDeclaration's binding target -- a plain identifier
94
- // (the base case), or -- for destructuring -- a nested ObjectPattern/
95
- // ArrayPattern, each with optional per-field renames, defaults, and a
96
- // rest element, recursing through `binding` so patterns can nest
97
- // arbitrarily deep (e.g. `const { data: { id, name } } = result`)
98
- // instead of only supporting one flat level. Matches real JS
99
- // destructuring syntax so the generated line is exactly what a
100
- // hand-written `const { a } = x` would look like.
101
- function generateDeclarationTarget(target, typed = false) {
108
+ // `const a = 1, { b } = x` -- the declaration WITHOUT a trailing
109
+ // semicolon (used by statements and by C-style for headers). A null
110
+ // init (`let x`) emits just the target.
111
+ export function declarationSource(node, typed = false) {
112
+ const one = (name, init) =>
113
+ init == null
114
+ ? generateDeclarationTarget(name, typed)
115
+ : `${generateDeclarationTarget(name, typed)} = ${generateExpression(init, typed)}`
116
+ const parts = [
117
+ one(node.name, node.init),
118
+ ...(node.more ?? []).map((m) => one(m.name, m.init)),
119
+ ]
120
+ return `${node.kind} ${parts.join(', ')}`
121
+ }
122
+
123
+ // The three parts of a C-style `for (init; test; update)` header.
124
+ export function forHeaderSource(node, typed = false) {
125
+ const init = !node.init
126
+ ? ''
127
+ : node.init.type === 'VariableDeclaration'
128
+ ? declarationSource(node.init, typed)
129
+ : node.init.expressions.map((e) => generateExpression(e, typed)).join(', ')
130
+ const test = node.test ? generateExpression(node.test, typed) : ''
131
+ const update = (node.update ?? [])
132
+ .map((e) => generateExpression(e, typed))
133
+ .join(', ')
134
+ return `${init}; ${test}; ${update}`
135
+ }
136
+
137
+ // Renders a binding target -- a plain identifier (the base case), or
138
+ // -- for destructuring -- a nested ObjectPattern/ArrayPattern, each
139
+ // with optional per-field renames, defaults, and a rest element,
140
+ // recursing through `binding` so patterns can nest arbitrarily deep
141
+ // (e.g. `const { data: { id, name } } = result`) instead of only
142
+ // supporting one flat level. Matches real JS destructuring syntax so
143
+ // the generated line is exactly what a hand-written `const { a } = x`
144
+ // would look like.
145
+ export function generateDeclarationTarget(target, typed = false) {
102
146
  if (typeof target === 'string') {
103
147
  return target
104
148
  }