@tylix/compiler 0.4.2 → 0.5.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tylix/compiler",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "keywords": [
6
6
  "tylix",
@@ -15,6 +15,6 @@
15
15
  "typescript": "^5.9.3"
16
16
  },
17
17
  "devDependencies": {
18
- "jsdom": "^24.0.0"
18
+ "jsdom": "^29.1.1"
19
19
  }
20
20
  }
package/src/ast/nodes.js CHANGED
@@ -184,8 +184,18 @@ export function ContinueStatement() {
184
184
  return { type: 'ContinueStatement' }
185
185
  }
186
186
 
187
- export function ArrowFunctionExpr(params, body, paramTypes = null) {
188
- return { type: 'ArrowFunctionExpression', params, body, paramTypes }
187
+ export function ArrowFunctionExpr(
188
+ params,
189
+ body,
190
+ paramTypes = null,
191
+ isAsync = false,
192
+ ) {
193
+ // body is either an expression node, or a BlockStatement node for
194
+ // block-bodied arrows (`x => { ... }`). Block bodies are only valid
195
+ // in script code; the template generators reject BlockStatement
196
+ // with their normal "unsupported node type" error.
197
+ // isAsync marks `async x => ...` / `async (a, b) => ...`.
198
+ return { type: 'ArrowFunctionExpression', params, body, paramTypes, isAsync }
189
199
  }
190
200
 
191
201
  export function TemplateLiteralExpr(parts) {
@@ -195,6 +205,7 @@ export function TemplateLiteralExpr(parts) {
195
205
  export function SpreadElement(argument) {
196
206
  return { type: 'SpreadElement', argument }
197
207
  }
208
+
198
209
  export function TryStatement(tryBlock, catchParam, catchBlock, finallyBlock) {
199
210
  return {
200
211
  type: 'TryStatement',
@@ -204,3 +215,21 @@ export function TryStatement(tryBlock, catchParam, catchBlock, finallyBlock) {
204
215
  finallyBlock,
205
216
  }
206
217
  }
218
+
219
+ export function BlockStatement(body) {
220
+ return { type: 'BlockStatement', body }
221
+ }
222
+
223
+ export function ThrowStatement(argument) {
224
+ return { type: 'ThrowStatement', argument }
225
+ }
226
+
227
+ export function WhileStatement(condition, body) {
228
+ return { type: 'WhileStatement', condition, body }
229
+ }
230
+
231
+ // cases: [{ tests: Expression[] | null, body: Statement[] }]
232
+ // tests === null marks the `default` clause.
233
+ export function SwitchStatement(discriminant, cases) {
234
+ return { type: 'SwitchStatement', discriminant, cases }
235
+ }
@@ -13,62 +13,91 @@ import { generateExpression } from './generateExpression.js'
13
13
  // building the virtual .ts fed to the TypeScript compiler API), so
14
14
  // unlike generateExpression itself (shared between real JS and
15
15
  // virtual TS output), there's no "untyped" mode to preserve here.
16
+ //
17
+ // Block-bodied arrows never reach this file directly: they are
18
+ // emitted by generateExpression, which delegates their statements to
19
+ // generateStatement (typed), so there is no BlockStatement case here.
16
20
  export function emitStatementLines(node, sink, indent = ' ') {
17
21
  const line = node.line
18
22
  const push = (text) => sink.pushLine(`${indent}${text}`, line)
23
+ const expr = (n) => generateExpression(n, true)
24
+ const nested = (list) => {
25
+ for (const s of list) emitStatementLines(s, sink, indent + ' ')
26
+ }
19
27
 
20
28
  switch (node.type) {
21
29
  case 'ReturnStatement':
22
- push(
23
- node.argument
24
- ? `return ${generateExpression(node.argument, true)};`
25
- : 'return;',
26
- )
30
+ push(node.argument ? `return ${expr(node.argument)};` : 'return;')
31
+ break
32
+
33
+ case 'ThrowStatement':
34
+ push(`throw ${expr(node.argument)};`)
27
35
  break
28
36
 
29
37
  case 'ExpressionStatement':
30
- push(`${generateExpression(node.expression, true)};`)
38
+ push(`${expr(node.expression)};`)
31
39
  break
32
40
 
33
41
  case 'VariableDeclaration':
34
42
  push(
35
- `${node.kind} ${node.name} = ${generateExpression(node.init, true)};`,
43
+ `${node.kind} ${generateDeclarationTarget(node.name)} = ${expr(node.init)};`,
36
44
  )
37
45
  break
38
46
 
39
47
  case 'IfStatement':
40
- push(`if (${generateExpression(node.condition, true)}) {`)
41
- for (const s of node.consequent)
42
- emitStatementLines(s, sink, indent + ' ')
48
+ push(`if (${expr(node.condition)}) {`)
49
+ nested(node.consequent)
43
50
  if (node.alternate) {
44
51
  push('} else {')
45
- for (const s of node.alternate)
46
- emitStatementLines(s, sink, indent + ' ')
52
+ nested(node.alternate)
53
+ }
54
+ push('}')
55
+ break
56
+
57
+ case 'WhileStatement':
58
+ push(`while (${expr(node.condition)}) {`)
59
+ nested(node.body)
60
+ push('}')
61
+ break
62
+
63
+ // Mirrors generateStatement: every clause body sits in its own
64
+ // braces and ends with an automatic `break`, so the virtual file
65
+ // has the same scoping and no-fallthrough behavior as real output.
66
+ case 'SwitchStatement':
67
+ push(`switch (${expr(node.discriminant)}) {`)
68
+ for (const c of node.cases) {
69
+ if (c.tests === null) {
70
+ push(' default: {')
71
+ } else {
72
+ c.tests.forEach((t, i) => {
73
+ const isLast = i === c.tests.length - 1
74
+ push(` case ${expr(t)}:${isLast ? ' {' : ''}`)
75
+ })
76
+ }
77
+ for (const s of c.body) emitStatementLines(s, sink, indent + ' ')
78
+ push(' break;')
79
+ push(' }')
47
80
  }
48
81
  push('}')
49
82
  break
50
83
 
51
84
  case 'ForInStatement':
52
- push(
53
- `for (const ${node.varName} of ${generateExpression(node.iterable, true)}) {`,
54
- )
55
- for (const s of node.body) emitStatementLines(s, sink, indent + ' ')
85
+ push(`for (const ${node.varName} of ${expr(node.iterable)}) {`)
86
+ nested(node.body)
56
87
  push('}')
57
88
  break
58
89
 
59
90
  case 'ForRangeStatement':
60
91
  push(
61
- `for (let ${node.varName} = ${generateExpression(node.start, true)}; ${node.varName} < ${generateExpression(node.end, true)}; ${node.varName}++) {`,
92
+ `for (let ${node.varName} = ${expr(node.start)}; ${node.varName} < ${expr(node.end)}; ${node.varName}++) {`,
62
93
  )
63
- for (const s of node.body) emitStatementLines(s, sink, indent + ' ')
94
+ nested(node.body)
64
95
  push('}')
65
96
  break
66
97
 
67
98
  case 'RepeatStatement':
68
- push(
69
- `for (let __i = 0; __i < ${generateExpression(node.count, true)}; __i++) {`,
70
- )
71
- for (const s of node.body) emitStatementLines(s, sink, indent + ' ')
99
+ push(`for (let __i = 0; __i < ${expr(node.count)}; __i++) {`)
100
+ nested(node.body)
72
101
  push('}')
73
102
  break
74
103
 
@@ -80,7 +109,64 @@ export function emitStatementLines(node, sink, indent = ' ') {
80
109
  push('continue;')
81
110
  break
82
111
 
112
+ case 'TryStatement':
113
+ push('try {')
114
+ nested(node.tryBlock)
115
+ if (node.catchBlock) {
116
+ push(node.catchParam ? `} catch (${node.catchParam}) {` : '} catch {')
117
+ nested(node.catchBlock)
118
+ }
119
+ if (node.finallyBlock) {
120
+ push('} finally {')
121
+ nested(node.finallyBlock)
122
+ }
123
+ push('}')
124
+ break
125
+
83
126
  default:
84
127
  throw new Error(`emitStatementLines: unknown node type "${node.type}"`)
85
128
  }
86
129
  }
130
+
131
+ // Same binding-target rendering as generateStatement.js (kept as a
132
+ // local copy so that file's exports stay untouched): a plain
133
+ // identifier, or a nested ObjectPattern/ArrayPattern with renames,
134
+ // defaults and rest elements. If you change one, change both.
135
+ function generateDeclarationTarget(target) {
136
+ if (typeof target === 'string') {
137
+ return target
138
+ }
139
+
140
+ if (target.type === 'ObjectPattern') {
141
+ const parts = target.properties.map((p) => {
142
+ const bindingStr = generateDeclarationTarget(p.binding)
143
+ const needsColon = typeof p.binding !== 'string' || p.binding !== p.key
144
+ const lhs = needsColon ? `${p.key}: ${bindingStr}` : p.key
145
+ return p.defaultValue
146
+ ? `${lhs} = ${generateExpression(p.defaultValue, true)}`
147
+ : lhs
148
+ })
149
+ if (target.rest) {
150
+ parts.push(`...${target.rest}`)
151
+ }
152
+ return `{ ${parts.join(', ')} }`
153
+ }
154
+
155
+ if (target.type === 'ArrayPattern') {
156
+ const parts = target.elements.map((el) => {
157
+ if (el === null) return ''
158
+ const bindingStr = generateDeclarationTarget(el.binding)
159
+ return el.defaultValue
160
+ ? `${bindingStr} = ${generateExpression(el.defaultValue, true)}`
161
+ : bindingStr
162
+ })
163
+ if (target.rest) {
164
+ parts.push(`...${target.rest}`)
165
+ }
166
+ return `[${parts.join(', ')}]`
167
+ }
168
+
169
+ throw new Error(
170
+ `generateDeclarationTarget: unknown pattern type "${target.type}"`,
171
+ )
172
+ }
@@ -1,3 +1,16 @@
1
+ import { generateStatement } from './generateStatement.js'
2
+
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.
7
+
8
+ // Word operators (typeof) need a space before their operand;
9
+ // symbolic ones (!, -) must not get one.
10
+ function unaryPrefix(operator) {
11
+ return /^[a-z]/i.test(operator) ? `${operator} ` : operator
12
+ }
13
+
1
14
  /**
2
15
  * Compiles a single expression AST node into a JS (or, when
3
16
  * typed=true, TypeScript) source string. Used both for method-body
@@ -37,7 +50,7 @@ export function generateExpression(node, typed = false) {
37
50
  return `(${generateExpression(node.left, typed)} ${node.operator} ${generateExpression(node.right, typed)})`
38
51
 
39
52
  case 'UnaryExpression':
40
- return `(${node.operator}${generateExpression(node.argument, typed)})`
53
+ return `(${unaryPrefix(node.operator)}${generateExpression(node.argument, typed)})`
41
54
 
42
55
  case 'TernaryExpression':
43
56
  return `(${generateExpression(node.condition, typed)} ? ${generateExpression(node.consequent, typed)} : ${generateExpression(node.alternate, typed)})`
@@ -58,7 +71,21 @@ export function generateExpression(node, typed = false) {
58
71
  return `${name}: ${paramType ?? 'any'}`
59
72
  })
60
73
  .join(', ')
61
- return `(${params}) => (${generateExpression(node.body, typed)})`
74
+ const asyncPrefix = node.isAsync ? 'async ' : ''
75
+
76
+ // Block body: `x => { stmt stmt }`. Statements are emitted on
77
+ // one line separated by spaces; multi-line statements (if,
78
+ // for, try) keep their own newlines, which is still valid JS.
79
+ if (node.body.type === 'BlockStatement') {
80
+ const stmts = node.body.body
81
+ .map((s) => generateStatement(s, typed))
82
+ .join(' ')
83
+ return `${asyncPrefix}(${params}) => { ${stmts} }`
84
+ }
85
+
86
+ // Expression body is always parenthesized so an object literal
87
+ // body (`x => ({ ...x })`) is never parsed as a block.
88
+ return `${asyncPrefix}(${params}) => (${generateExpression(node.body, typed)})`
62
89
  }
63
90
 
64
91
  case 'TemplateLiteralExpression': {
@@ -77,23 +104,25 @@ export function generateExpression(node, typed = false) {
77
104
 
78
105
  case 'CallExpression': {
79
106
  const args = node.args
80
- .map((a) =>
81
- a.type === 'SpreadElement'
82
- ? `...${generateExpression(a.argument, typed)}`
83
- : generateExpression(a, typed),
84
- )
107
+ .map((a) => generateExpression(a, typed))
85
108
  .join(', ')
86
- return `${generateExpression(node.callee, typed)}(${args})`
109
+ return `${generateExpression(node.callee, typed)}${node.optional ? '?.' : ''}(${args})`
87
110
  }
88
111
 
89
112
  case 'AwaitExpression':
90
113
  return `await ${generateExpression(node.argument, typed)}`
91
114
 
115
+ case 'SpreadElement':
116
+ return `...${generateExpression(node.argument, typed)}`
117
+
92
118
  case 'ObjectExpression': {
119
+ // Spread entries have key === null and spread === true (see
120
+ // Parser.parseObjectLiteral), so check p.spread before p.key.
93
121
  const props = node.properties
94
- .map(
95
- (p) =>
96
- `${JSON.stringify(p.key)}: ${generateExpression(p.value, typed)}`,
122
+ .map((p) =>
123
+ p.spread
124
+ ? `...${generateExpression(p.value, typed)}`
125
+ : `${JSON.stringify(p.key)}: ${generateExpression(p.value, typed)}`,
97
126
  )
98
127
  .join(', ')
99
128
  return `{ ${props} }`
@@ -101,11 +130,7 @@ export function generateExpression(node, typed = false) {
101
130
 
102
131
  case 'ArrayExpression': {
103
132
  const elements = node.elements
104
- .map((e) =>
105
- e.type === 'SpreadElement'
106
- ? `...${generateExpression(e.argument, typed)}`
107
- : generateExpression(e, typed),
108
- )
133
+ .map((e) => generateExpression(e, typed))
109
134
  .join(', ')
110
135
  return `[${elements}]`
111
136
  }
@@ -125,4 +150,4 @@ function escapeTemplateText(text) {
125
150
  .replace(/\\/g, '\\\\')
126
151
  .replace(/`/g, '\\`')
127
152
  .replace(/\$\{/g, '\\${')
128
- }
153
+ }
@@ -2,55 +2,65 @@ import { generateExpression } from './generateExpression.js'
2
2
 
3
3
  /**
4
4
  * Compiles a single statement AST node into a JS source line.
5
+ *
6
+ * `typed` is threaded through to generateExpression so a block-bodied
7
+ * arrow compiled for the virtual .ts file keeps its `: any` param
8
+ * annotations on nested arrows. It defaults to false, so every
9
+ * existing caller (generateMethod, generateCapability) is unchanged.
5
10
  */
6
- export function generateStatement(node) {
11
+ export function generateStatement(node, typed = false) {
12
+ const expr = (n) => generateExpression(n, typed)
13
+ const stmts = (list) =>
14
+ list.map((s) => ` ${generateStatement(s, typed)}`).join('\n')
15
+
7
16
  switch (node.type) {
8
17
  case 'ReturnStatement':
9
- return node.argument
10
- ? `return ${generateExpression(node.argument)};`
11
- : 'return;'
18
+ return node.argument ? `return ${expr(node.argument)};` : 'return;'
19
+
20
+ case 'ThrowStatement':
21
+ return `throw ${expr(node.argument)};`
12
22
 
13
23
  case 'ExpressionStatement':
14
- return `${generateExpression(node.expression)};`
24
+ return `${expr(node.expression)};`
15
25
 
16
26
  case 'VariableDeclaration':
17
- return `${node.kind} ${generateDeclarationTarget(node.name)} = ${generateExpression(node.init)};`
27
+ return `${node.kind} ${generateDeclarationTarget(node.name, typed)} = ${expr(node.init)};`
18
28
 
19
29
  case 'IfStatement': {
20
- const cond = generateExpression(node.condition)
21
- const body = node.consequent
22
- .map((s) => ` ${generateStatement(s)}`)
23
- .join('\n')
24
- let out = `if (${cond}) {\n${body}\n }`
30
+ let out = `if (${expr(node.condition)}) {\n${stmts(node.consequent)}\n }`
25
31
  if (node.alternate) {
26
- const elseBody = node.alternate
27
- .map((s) => ` ${generateStatement(s)}`)
28
- .join('\n')
29
- out += ` else {\n${elseBody}\n }`
32
+ out += ` else {\n${stmts(node.alternate)}\n }`
30
33
  }
31
34
  return out
32
35
  }
33
36
 
34
- case 'ForInStatement': {
35
- const body = node.body
36
- .map((s) => ` ${generateStatement(s)}`)
37
- .join('\n')
38
- return `for (const ${node.varName} of ${generateExpression(node.iterable)}) {\n${body}\n }`
37
+ case 'WhileStatement':
38
+ return `while (${expr(node.condition)}) {\n${stmts(node.body)}\n }`
39
+
40
+ // Each clause body is wrapped in its own braces so `const`/`let`
41
+ // declared in one case can't collide with another, and a `break`
42
+ // is appended so there is never accidental fallthrough. (A
43
+ // user-written `break` inside a case therefore leaves the switch,
44
+ // not an enclosing loop -- same as JS.)
45
+ case 'SwitchStatement': {
46
+ const clauses = node.cases.map((c) => {
47
+ const labels =
48
+ c.tests === null
49
+ ? ' default:'
50
+ : c.tests.map((t) => ` case ${expr(t)}:`).join('\n')
51
+ return `${labels} {\n${stmts(c.body)}\n break;\n }`
52
+ })
53
+ return `switch (${expr(node.discriminant)}) {\n${clauses.join('\n')}\n }`
39
54
  }
40
55
 
41
- case 'ForRangeStatement': {
42
- const body = node.body
43
- .map((s) => ` ${generateStatement(s)}`)
44
- .join('\n')
45
- return `for (let ${node.varName} = ${generateExpression(node.start)}; ${node.varName} < ${generateExpression(node.end)}; ${node.varName}++) {\n${body}\n }`
46
- }
56
+ case 'ForInStatement':
57
+ return `for (const ${node.varName} of ${expr(node.iterable)}) {\n${stmts(node.body)}\n }`
47
58
 
48
- case 'RepeatStatement': {
49
- const body = node.body
50
- .map((s) => ` ${generateStatement(s)}`)
51
- .join('\n')
52
- return `for (let __i = 0; __i < ${generateExpression(node.count)}; __i++) {\n${body}\n }`
53
- }
59
+ case 'ForRangeStatement':
60
+ return `for (let ${node.varName} = ${expr(node.start)}; ${node.varName} < ${expr(node.end)}; ${node.varName}++) {\n${stmts(node.body)}\n }`
61
+
62
+ case 'RepeatStatement':
63
+ return `for (let __i = 0; __i < ${expr(node.count)}; __i++) {\n${stmts(node.body)}\n }`
54
64
 
55
65
  case 'BreakStatement':
56
66
  return 'break;'
@@ -59,26 +69,17 @@ export function generateStatement(node) {
59
69
  return 'continue;'
60
70
 
61
71
  case 'TryStatement': {
62
- const tryBody = node.tryBlock
63
- .map((s) => ` ${generateStatement(s)}`)
64
- .join('\n')
65
- let out = `try {\n${tryBody}\n }`
72
+ let out = `try {\n${stmts(node.tryBlock)}\n }`
66
73
 
67
74
  if (node.catchBlock) {
68
- const catchBody = node.catchBlock
69
- .map((s) => ` ${generateStatement(s)}`)
70
- .join('\n')
71
75
  const catchHeader = node.catchParam
72
76
  ? `catch (${node.catchParam})`
73
77
  : 'catch'
74
- out += ` ${catchHeader} {\n${catchBody}\n }`
78
+ out += ` ${catchHeader} {\n${stmts(node.catchBlock)}\n }`
75
79
  }
76
80
 
77
81
  if (node.finallyBlock) {
78
- const finallyBody = node.finallyBlock
79
- .map((s) => ` ${generateStatement(s)}`)
80
- .join('\n')
81
- out += ` finally {\n${finallyBody}\n }`
82
+ out += ` finally {\n${stmts(node.finallyBlock)}\n }`
82
83
  }
83
84
 
84
85
  return out
@@ -89,33 +90,29 @@ export function generateStatement(node) {
89
90
  }
90
91
  }
91
92
 
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
93
  // Renders a VariableDeclaration's binding target -- a plain identifier
99
94
  // (the base case), or -- for destructuring -- a nested ObjectPattern/
100
95
  // ArrayPattern, each with optional per-field renames, defaults, and a
101
96
  // rest element, recursing through `binding` so patterns can nest
102
97
  // arbitrarily deep (e.g. `const { data: { id, name } } = result`)
103
- // instead of only supporting one flat level.
104
- function generateDeclarationTarget(target) {
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) {
105
102
  if (typeof target === 'string') {
106
103
  return target
107
104
  }
108
105
 
109
106
  if (target.type === 'ObjectPattern') {
110
107
  const parts = target.properties.map((p) => {
111
- const bindingStr = generateDeclarationTarget(p.binding)
108
+ const bindingStr = generateDeclarationTarget(p.binding, typed)
112
109
  // Only emit "key: binding" when the binding differs from a bare
113
110
  // shorthand match on the key itself -- i.e. it was renamed or
114
111
  // it's a nested pattern (never just equal to the plain key string).
115
112
  const needsColon = typeof p.binding !== 'string' || p.binding !== p.key
116
113
  const lhs = needsColon ? `${p.key}: ${bindingStr}` : p.key
117
114
  return p.defaultValue
118
- ? `${lhs} = ${generateExpression(p.defaultValue)}`
115
+ ? `${lhs} = ${generateExpression(p.defaultValue, typed)}`
119
116
  : lhs
120
117
  })
121
118
  if (target.rest) {
@@ -127,9 +124,9 @@ function generateDeclarationTarget(target) {
127
124
  if (target.type === 'ArrayPattern') {
128
125
  const parts = target.elements.map((el) => {
129
126
  if (el === null) return ''
130
- const bindingStr = generateDeclarationTarget(el.binding)
127
+ const bindingStr = generateDeclarationTarget(el.binding, typed)
131
128
  return el.defaultValue
132
- ? `${bindingStr} = ${generateExpression(el.defaultValue)}`
129
+ ? `${bindingStr} = ${generateExpression(el.defaultValue, typed)}`
133
130
  : bindingStr
134
131
  })
135
132
  if (target.rest) {
@@ -141,4 +138,4 @@ function generateDeclarationTarget(target) {
141
138
  throw new Error(
142
139
  `generateDeclarationTarget: unknown pattern type "${target.type}"`,
143
140
  )
144
- }
141
+ }