plainscript-lang 0.1.7-rc → 1.0.0-beta
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/README.md +27 -2
- package/compiler/cli.js +1 -1
- package/compiler/generator.js +623 -10
- package/compiler/lexer.js +31 -2
- package/compiler/parser.js +537 -20
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +379 -0
- package/docs/PLINJS_SPEC.md +102 -2
- package/docs/index.html +18 -6
- package/docs/website/script.js +111 -36
- package/package.json +2 -2
package/compiler/generator.js
CHANGED
|
@@ -38,7 +38,27 @@ const JS_RESERVED = new Set([
|
|
|
38
38
|
|
|
39
39
|
const BUILTIN_DECLARATIONS = {
|
|
40
40
|
fs: `const fs = require('fs');`,
|
|
41
|
+
path: `const path = require('path');`,
|
|
41
42
|
crypto: `const crypto = require('crypto');`,
|
|
43
|
+
// v1.0.0 — env-file runtime. Applies KEY=VALUE pairs from a .env file to
|
|
44
|
+
// process.env. Blank lines and `#` comment lines are skipped.
|
|
45
|
+
dotenv: [
|
|
46
|
+
`function __loadEnvFile(path) {`,
|
|
47
|
+
` const fs = require('fs');`,
|
|
48
|
+
` let raw;`,
|
|
49
|
+
` try { raw = fs.readFileSync(path, 'utf8'); } catch (e) { return; }`,
|
|
50
|
+
` for (const line of raw.split(/\\r?\\n/)) {`,
|
|
51
|
+
` const trimmed = line.trim();`,
|
|
52
|
+
` if (!trimmed || trimmed.startsWith('#')) continue;`,
|
|
53
|
+
` const eq = trimmed.indexOf('=');`,
|
|
54
|
+
` if (eq < 0) continue;`,
|
|
55
|
+
` const k = trimmed.slice(0, eq).trim();`,
|
|
56
|
+
` let v = trimmed.slice(eq + 1).trim();`,
|
|
57
|
+
` if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith('\\'') && v.endsWith('\\''))) v = v.slice(1, -1);`,
|
|
58
|
+
` if (process.env[k] === undefined) process.env[k] = v;`,
|
|
59
|
+
` }`,
|
|
60
|
+
`}`,
|
|
61
|
+
].join('\n'),
|
|
42
62
|
// v1.1.1 — ask runtime (RFC-0011 §14)
|
|
43
63
|
ask: [
|
|
44
64
|
`const readline = require('readline');`,
|
|
@@ -66,6 +86,181 @@ const BUILTIN_DECLARATIONS = {
|
|
|
66
86
|
` }`,
|
|
67
87
|
`}`,
|
|
68
88
|
].join('\n'),
|
|
89
|
+
// v1.0.0 — shared runtime helpers for reflection, binary-size, YAML subset
|
|
90
|
+
// parsing/emitting, spread of timeouts, and set/map helpers. Injected lazily
|
|
91
|
+
// when any feature that needs them is used.
|
|
92
|
+
core: [
|
|
93
|
+
`function __typeOf(x) {`,
|
|
94
|
+
` if (x === null) return 'null';`,
|
|
95
|
+
` if (x === undefined) return 'undefined';`,
|
|
96
|
+
` const t = typeof x;`,
|
|
97
|
+
` if (t === 'string') return 'text';`,
|
|
98
|
+
` if (t === 'number') return 'number';`,
|
|
99
|
+
` if (t === 'boolean') return 'boolean';`,
|
|
100
|
+
` if (Array.isArray(x)) return 'array';`,
|
|
101
|
+
` if (t === 'object') return 'record';`,
|
|
102
|
+
` if (t === 'function') return 'function';`,
|
|
103
|
+
` return t;`,
|
|
104
|
+
`}`,
|
|
105
|
+
`function __sizeOf(x) {`,
|
|
106
|
+
` if (x == null) return 0;`,
|
|
107
|
+
` if (typeof x === 'string' || Array.isArray(x)) return x.length;`,
|
|
108
|
+
` if (x instanceof Map || x instanceof Set) return x.size;`,
|
|
109
|
+
` if (typeof x === 'object') return Object.keys(x).length;`,
|
|
110
|
+
` return 0;`,
|
|
111
|
+
`}`,
|
|
112
|
+
`function __formatDate(x, pattern) {`,
|
|
113
|
+
` const p = pattern || 'YYYY-MM-DD HH:mm:ss';`,
|
|
114
|
+
` let d = x instanceof Date ? x : new Date(x);`,
|
|
115
|
+
` if (Number.isNaN(d.getTime())) return '';`,
|
|
116
|
+
` const pad = (n, l) => String(n).padStart(l || 2, '0');`,
|
|
117
|
+
` const map = {`,
|
|
118
|
+
` YYYY: String(d.getFullYear()),`,
|
|
119
|
+
` MM: pad(d.getMonth() + 1),`,
|
|
120
|
+
` DD: pad(d.getDate()),`,
|
|
121
|
+
` HH: pad(d.getHours()),`,
|
|
122
|
+
` mm: pad(d.getMinutes()),`,
|
|
123
|
+
` ss: pad(d.getSeconds()),`,
|
|
124
|
+
` };`,
|
|
125
|
+
` return p.replace(/YYYY|MM|DD|HH|mm|ss/g, k => map[k]);`,
|
|
126
|
+
`}`,
|
|
127
|
+
`function __yamlStringify(v, indent) {`,
|
|
128
|
+
` const pad = ' '.repeat(indent || 0);`,
|
|
129
|
+
` if (v === null || v === undefined) return 'null';`,
|
|
130
|
+
` if (typeof v === 'string') return '"' + String(v).replace(/\\\\/g, '\\\\\\\\').replace(/"/g, '\\\\"') + '"';`,
|
|
131
|
+
` if (typeof v === 'number' || typeof v === 'boolean') return String(v);`,
|
|
132
|
+
` if (Array.isArray(v)) {`,
|
|
133
|
+
` const childPad = pad + ' ';`,
|
|
134
|
+
` return v.map(x => {`,
|
|
135
|
+
` if (typeof x === 'object' && x !== null && !Array.isArray(x)) {`,
|
|
136
|
+
` const inner = __yamlStringify(x, indent + 2).split('\\n')[0];`,
|
|
137
|
+
` return pad + '- ' + inner + __yamlStringify(x, indent + 4).split('\\n').slice(1).map(l => '\\n' + l).join('');`,
|
|
138
|
+
` }`,
|
|
139
|
+
` return pad + '- ' + __yamlStringify(x, indent + 2);`,
|
|
140
|
+
` }).join('\\n');`,
|
|
141
|
+
` }`,
|
|
142
|
+
` if (typeof v === 'object') {`,
|
|
143
|
+
` return Object.keys(v).map(k => {`,
|
|
144
|
+
` const val = __yamlStringify(v[k], 0);`,
|
|
145
|
+
` if (typeof v[k] === 'object' && v[k] !== null && !Array.isArray(v[k])) {`,
|
|
146
|
+
` return pad + k + ':\\n' + __yamlStringify(v[k], indent + 2);`,
|
|
147
|
+
` }`,
|
|
148
|
+
` return pad + k + ': ' + val;`,
|
|
149
|
+
` }).join('\\n');`,
|
|
150
|
+
` }`,
|
|
151
|
+
` return String(v);`,
|
|
152
|
+
`}`,
|
|
153
|
+
`function __yamlParse(text) {`,
|
|
154
|
+
` const lines = String(text).split(/\\r?\\n/);`,
|
|
155
|
+
` const root = {};`,
|
|
156
|
+
` let seq = null;`,
|
|
157
|
+
` let seqIndent = -1;`,
|
|
158
|
+
` const stack = [{ indent: -1, node: root }];`,
|
|
159
|
+
` for (const line0 of lines) {`,
|
|
160
|
+
` const trimmed = line0.trim();`,
|
|
161
|
+
` if (!trimmed || trimmed.startsWith('#')) continue;`,
|
|
162
|
+
` const indent = line0.length - line0.trimStart().length;`,
|
|
163
|
+
` const scalar = (s) => {`,
|
|
164
|
+
` const t = s.trim();`,
|
|
165
|
+
` if (t.length >= 2 && ((t[0] === '"' && t[t.length - 1] === '"') || (t[0] === "'" && t[t.length - 1] === "'"))) return t.slice(1, -1);`,
|
|
166
|
+
` if (t === 'true') return true;`,
|
|
167
|
+
` if (t === 'false') return false;`,
|
|
168
|
+
` if (t === 'null' || t === '~') return null;`,
|
|
169
|
+
` if (t !== '' && !isNaN(Number(t))) return Number(t);`,
|
|
170
|
+
` return t;`,
|
|
171
|
+
` };`,
|
|
172
|
+
` const m = trimmed.match(/^([^:#]+):(.*)$/);`,
|
|
173
|
+
` if (m) {`,
|
|
174
|
+
` const key = m[1].replace(/^['"]|['"]$/g, '').trim();`,
|
|
175
|
+
` const rest = m[2].trim();`,
|
|
176
|
+
` while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();`,
|
|
177
|
+
` const parent = stack[stack.length - 1].node;`,
|
|
178
|
+
` if (rest === '' || rest === '|') { const node = {}; parent[key] = node; stack.push({ indent, node }); }`,
|
|
179
|
+
` else if (rest === '[]') { parent[key] = []; }`,
|
|
180
|
+
` else { parent[key] = scalar(rest); }`,
|
|
181
|
+
` continue;`,
|
|
182
|
+
` }`,
|
|
183
|
+
` const lm = trimmed.match(/^-\\s*(.*)$/);`,
|
|
184
|
+
` if (lm) {`,
|
|
185
|
+
` while (seq && seqIndent >= indent) { seq = null; seqIndent = -1; }`,
|
|
186
|
+
` while (!seq && stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();`,
|
|
187
|
+
` const parent = stack[stack.length - 1].node;`,
|
|
188
|
+
` if (lm[1] && lm[1].includes(':')) {`,
|
|
189
|
+
` const km = lm[1].match(/^([^:]+):\\s*(.*)$/);`,
|
|
190
|
+
` if (seq) {`,
|
|
191
|
+
` const m2 = {}; seq[seq.length - 1] = typeof seq[seq.length - 1] === 'object' && seq[seq.length - 1] !== null ? seq[seq.length - 1] : m2;`,
|
|
192
|
+
` const node = seq[seq.length - 1];`,
|
|
193
|
+
` node[km[1].trim()] = km[2] ? scalar(km[2]) : {};`,
|
|
194
|
+
` } else {`,
|
|
195
|
+
` const node = {}; parent[km[1].trim()] = km[2] ? scalar(km[2]) : node; stack.push({ indent, node });`,
|
|
196
|
+
` }`,
|
|
197
|
+
` } else if (seq) {`,
|
|
198
|
+
` seq.push(scalar(lm[1]));`,
|
|
199
|
+
` } else if (Array.isArray(parent)) {`,
|
|
200
|
+
` parent.push(scalar(lm[1])); seq = parent; seqIndent = indent;`,
|
|
201
|
+
` } else {`,
|
|
202
|
+
` const lastKey = Object.keys(parent)[Object.keys(parent).length - 1];`,
|
|
203
|
+
` const arr = [];`,
|
|
204
|
+
` if (lastKey != null) parent[lastKey] = arr; else parent.__rootArray = arr;`,
|
|
205
|
+
` arr.push(scalar(lm[1]));`,
|
|
206
|
+
` seq = arr; seqIndent = indent;`,
|
|
207
|
+
` }`,
|
|
208
|
+
` continue;`,
|
|
209
|
+
` }`,
|
|
210
|
+
` }`,
|
|
211
|
+
` if (root.__rootArray) return root.__rootArray;`,
|
|
212
|
+
` return root;`,
|
|
213
|
+
`}`,
|
|
214
|
+
`function __withTimeout(promise, ms) {`,
|
|
215
|
+
` const timeout = ms == null ? 10000 : ms;`,
|
|
216
|
+
` return new Promise((resolve, reject) => {`,
|
|
217
|
+
` const timer = setTimeout(() => reject(new Error('Timed out after ' + timeout + 'ms.')), timeout);`,
|
|
218
|
+
` Promise.resolve(promise).then(v => { clearTimeout(timer); resolve(v); }, e => { clearTimeout(timer); reject(e); });`,
|
|
219
|
+
` });`,
|
|
220
|
+
`}`,
|
|
221
|
+
].join('\n'),
|
|
222
|
+
// v1.0.0 — process execution (child processes).
|
|
223
|
+
process: [
|
|
224
|
+
`const { execFile } = require('child_process');`,
|
|
225
|
+
`function __runCommand(command, args) {`,
|
|
226
|
+
` return new Promise((resolve) => {`,
|
|
227
|
+
` execFile(command, args || [], { maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {`,
|
|
228
|
+
` resolve({ ok: !error, code: error ? (error.code == null ? -1 : error.code) : 0, stdout: String(stdout), stderr: String(stderr) });`,
|
|
229
|
+
` });`,
|
|
230
|
+
` });`,
|
|
231
|
+
`}`,
|
|
232
|
+
].join('\n'),
|
|
233
|
+
// v1.0.0 — Map helpers.
|
|
234
|
+
mapset: [
|
|
235
|
+
`function __mapSet(map, key, value) { map.set(key, value); return map; }`,
|
|
236
|
+
].join('\n'),
|
|
237
|
+
// v1.0.0 — dynamic module loader.
|
|
238
|
+
loadmodule: [
|
|
239
|
+
`function __loadModule(spec) {`,
|
|
240
|
+
` const path = require('path');`,
|
|
241
|
+
` const target = (spec[0] === '.' ) ? path.resolve(process.cwd(), spec) : spec;`,
|
|
242
|
+
` try { return require(target); }`,
|
|
243
|
+
` catch (e) { if (spec[0] !== '.') return require(spec); throw e; }`,
|
|
244
|
+
`}`,
|
|
245
|
+
].join('\n'),
|
|
246
|
+
// v1.0.0 — recursive directory walker (returns full paths, files first).
|
|
247
|
+
walk: [
|
|
248
|
+
`function __walkFolder(dir) {`,
|
|
249
|
+
` const fs = require('fs');`,
|
|
250
|
+
` const path = require('path');`,
|
|
251
|
+
` const out = [];`,
|
|
252
|
+
` function rec(d) {`,
|
|
253
|
+
` for (const entry of fs.readdirSync(d)) {`,
|
|
254
|
+
` const full = path.join(d, entry);`,
|
|
255
|
+
` const st = fs.statSync(full);`,
|
|
256
|
+
` if (st.isDirectory()) rec(full);`,
|
|
257
|
+
` else out.push(full);`,
|
|
258
|
+
` }`,
|
|
259
|
+
` }`,
|
|
260
|
+
` rec(dir);`,
|
|
261
|
+
` return out;`,
|
|
262
|
+
`}`,
|
|
263
|
+
].join('\n'),
|
|
69
264
|
// v2.1.0 — request validation runtime. Returns the names of required
|
|
70
265
|
// fields whose value is missing (undefined/null/empty string) in data.
|
|
71
266
|
validation: [
|
|
@@ -558,6 +753,16 @@ const BUILTIN_DECLARATIONS = {
|
|
|
558
753
|
retry: [
|
|
559
754
|
`const __retrySleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));`,
|
|
560
755
|
].join('\n'),
|
|
756
|
+
// IOPL-native — event emitter runtime.
|
|
757
|
+
__emitter: 'const __emitter = new (require("events").EventEmitter)();',
|
|
758
|
+
// IOPL-native — line-by-line file streaming runtime.
|
|
759
|
+
__streamFile: [
|
|
760
|
+
`async function __streamFile(path, fn) {`,
|
|
761
|
+
` const fs = require('fs');`,
|
|
762
|
+
` const rl = require('readline').createInterface({ input: fs.createReadStream(path), crlfDelay: Infinity });`,
|
|
763
|
+
` for await (const line of rl) await fn(line);`,
|
|
764
|
+
`}`,
|
|
765
|
+
].join('\n'),
|
|
561
766
|
// v2.1.1 — SQLite runtime with a portable engine chain. Default order:
|
|
562
767
|
// better-sqlite3 (native binding) first, sql.js (WebAssembly) as fallback.
|
|
563
768
|
// Both engines are wrapped in the same tiny synchronous surface that PlainScript
|
|
@@ -892,6 +1097,23 @@ const STDLIB = {
|
|
|
892
1097
|
hasKey: (args, context) => `Object.prototype.hasOwnProperty.call(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
|
|
893
1098
|
merge: (args, context) => `{ ...${generateExpr(args[0], context)}, ...${generateExpr(args[1], context)} }`,
|
|
894
1099
|
|
|
1100
|
+
// ── v1.0.0 — nullable / regex / date helpers (IOPL-native).
|
|
1101
|
+
// first non-null, non-undefined argument — IOPL null-coalescing.
|
|
1102
|
+
coalesce: (args, context) =>
|
|
1103
|
+
`(() => { const __vals = [${args.map(a => generateExpr(a, context)).join(', ')}]; for (const __v of __vals) if (__v !== null && __v !== undefined) return __v; return undefined; })()`,
|
|
1104
|
+
// regex-aware replace (replace() is literal-only).
|
|
1105
|
+
regexReplace: (args, context) =>
|
|
1106
|
+
`String(${generateExpr(args[0], context)}).replace(new RegExp(${generateExpr(args[1], context)}, 'g'), ${args.length > 2 ? generateExpr(args[2], context) : '""'})`,
|
|
1107
|
+
// ISO/date-string → milliseconds since the Unix epoch (NaN on failure).
|
|
1108
|
+
parseDate: (args, context) => `Date.parse(String(${generateExpr(args[0], context)}))`,
|
|
1109
|
+
// milliseconds/Date → formatted text (YYYY-MM-DD HH:mm:ss by default).
|
|
1110
|
+
formatDate: (args, context) => {
|
|
1111
|
+
ensureBuiltin(context, 'core');
|
|
1112
|
+
const value = generateExpr(args[0], context);
|
|
1113
|
+
const pattern = args.length > 1 ? generateExpr(args[1], context) : '"YYYY-MM-DD HH:mm:ss"';
|
|
1114
|
+
return `__formatDate(${value}, ${pattern})`;
|
|
1115
|
+
},
|
|
1116
|
+
|
|
895
1117
|
// ── v2.1.0 — cache (Redis) accessors. All async.
|
|
896
1118
|
|
|
897
1119
|
cacheGet: (args, context) => {
|
|
@@ -964,6 +1186,130 @@ const STDLIB = {
|
|
|
964
1186
|
ensureBuiltin(context, 'auth');
|
|
965
1187
|
return `readToken(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
966
1188
|
},
|
|
1189
|
+
|
|
1190
|
+
// ── v1.0.0 — capability-gap stdlib (reflection, binary, concurrency, ...) ──
|
|
1191
|
+
|
|
1192
|
+
// Reflection
|
|
1193
|
+
typeOf: (args, context) => { ensureBuiltin(context, 'core'); return `__typeOf(${generateExpr(args[0], context)})`; },
|
|
1194
|
+
fieldsOf: (args, context) => `Object.keys(${generateExpr(args[0], context)})`,
|
|
1195
|
+
hasField: (args, context) => `Object.prototype.hasOwnProperty.call(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
|
|
1196
|
+
valueOf: (args, context) => {
|
|
1197
|
+
const [rec, key] = args.map(a => generateExpr(a, context));
|
|
1198
|
+
const fallback = args[2] != null ? generateExpr(args[2], context) : 'undefined';
|
|
1199
|
+
return `((__tmp) => (__tmp != null && Object.prototype.hasOwnProperty.call(__tmp, ${key})) ? __tmp[${key}] : ${fallback})(${rec})`;
|
|
1200
|
+
},
|
|
1201
|
+
sizeOf: (args, context) => { ensureBuiltin(context, 'core'); return `__sizeOf(${generateExpr(args[0], context)})`; },
|
|
1202
|
+
|
|
1203
|
+
// Binary
|
|
1204
|
+
base64Encode: (args, context) => `Buffer.from(String(${generateExpr(args[0], context)})).toString('base64')`,
|
|
1205
|
+
base64Decode: (args, context) => `Buffer.from(String(${generateExpr(args[0], context)}), 'base64').toString('utf8')`,
|
|
1206
|
+
textToBytes: (args, context) => `Buffer.from(String(${generateExpr(args[0], context)}), 'utf8')`,
|
|
1207
|
+
bytesToText: (args, context) => `Buffer.from(${generateExpr(args[0], context)}).toString('utf8')`,
|
|
1208
|
+
sha256: (args, context) => {
|
|
1209
|
+
ensureBuiltin(context, 'crypto');
|
|
1210
|
+
return `crypto.createHash('sha256').update(String(${generateExpr(args[0], context)})).digest('hex')`;
|
|
1211
|
+
},
|
|
1212
|
+
sha1: (args, context) => {
|
|
1213
|
+
ensureBuiltin(context, 'crypto');
|
|
1214
|
+
return `crypto.createHash('sha1').update(String(${generateExpr(args[0], context)})).digest('hex')`;
|
|
1215
|
+
},
|
|
1216
|
+
md5: (args, context) => {
|
|
1217
|
+
ensureBuiltin(context, 'crypto');
|
|
1218
|
+
return `crypto.createHash('md5').update(String(${generateExpr(args[0], context)})).digest('hex')`;
|
|
1219
|
+
},
|
|
1220
|
+
|
|
1221
|
+
// Serialization — minimal dependency-free YAML subset (see __yamlParse).
|
|
1222
|
+
yamlDecode: (args, context) => { ensureBuiltin(context, 'core'); return `__yamlParse(${generateExpr(args[0], context)})`; },
|
|
1223
|
+
yamlEncode: (args, context) => { ensureBuiltin(context, 'core'); return `__yamlStringify(${generateExpr(args[0], context)})`; },
|
|
1224
|
+
|
|
1225
|
+
// Configuration
|
|
1226
|
+
loadEnvFile: (_args, context) => {
|
|
1227
|
+
ensureBuiltin(context, 'dotenv');
|
|
1228
|
+
return `__loadEnvFile(${generateExpr(_args[0], context)})`;
|
|
1229
|
+
},
|
|
1230
|
+
|
|
1231
|
+
// CLI + process
|
|
1232
|
+
args: (_args) => `process.argv.slice(2)`,
|
|
1233
|
+
runCommand: (args, context) => {
|
|
1234
|
+
ensureBuiltin(context, 'process');
|
|
1235
|
+
markAsync(context);
|
|
1236
|
+
const bin = args[0] != null ? generateExpr(args[0], context) : 'undefined';
|
|
1237
|
+
const rest = args.slice(1).map(a => generateExpr(a, context));
|
|
1238
|
+
const call = `__runCommand(${bin}${rest.length ? ', [' + rest.join(', ') + ']' : ''})`;
|
|
1239
|
+
return `(await ${call})`;
|
|
1240
|
+
},
|
|
1241
|
+
withTimeout: (args, context) => {
|
|
1242
|
+
ensureBuiltin(context, 'core');
|
|
1243
|
+
markAsync(context);
|
|
1244
|
+
const ms = args[1] != null ? `, ${generateExpr(args[1], context)}` : '';
|
|
1245
|
+
return `(await __withTimeout(${generateExpr(args[0], context)}${ms}))`;
|
|
1246
|
+
},
|
|
1247
|
+
|
|
1248
|
+
// Generators / iterables
|
|
1249
|
+
spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
|
|
1250
|
+
|
|
1251
|
+
// v1.0.0 — dynamic module loading (the runtime companion to `import "./x.ps"`).
|
|
1252
|
+
// Resolves relative to the bundler's CWD so `loadModule("./m")` behaves like
|
|
1253
|
+
// `require.resolve` from the program root.
|
|
1254
|
+
loadModule: (args, context) => {
|
|
1255
|
+
ensureBuiltin(context, 'loadmodule');
|
|
1256
|
+
return `__loadModule(${generateExpr(args[0], context)})`;
|
|
1257
|
+
},
|
|
1258
|
+
|
|
1259
|
+
// Map / Set
|
|
1260
|
+
keyMap: (_args) => `new Map()`,
|
|
1261
|
+
mapSet: (args, context) => { ensureBuiltin(context, 'mapset'); return `__mapSet(${args.map(a => generateExpr(a, context)).join(', ')})`; },
|
|
1262
|
+
mapGet: (args, context) => `(${generateExpr(args[0], context)}).get(${generateExpr(args[1], context)})`,
|
|
1263
|
+
mapHas: (args, context) => `(${generateExpr(args[0], context)}).has(${generateExpr(args[1], context)})`,
|
|
1264
|
+
mapDelete: (args, context) => `(${generateExpr(args[0], context)}).delete(${generateExpr(args[1], context)})`,
|
|
1265
|
+
newSet: (_args) => `new Set()`,
|
|
1266
|
+
addToSet: (args, context) => `(${generateExpr(args[0], context)}).add(${generateExpr(args[1], context)})`,
|
|
1267
|
+
removeFromSet: (args, context) => `(${generateExpr(args[0], context)}).delete(${generateExpr(args[1], context)})`,
|
|
1268
|
+
setHas: (args, context) => `(${generateExpr(args[0], context)}).has(${generateExpr(args[1], context)})`,
|
|
1269
|
+
|
|
1270
|
+
// Filesystem metadata, walking, and path helpers
|
|
1271
|
+
fileSize: (args, context) => {
|
|
1272
|
+
ensureBuiltin(context, 'fs');
|
|
1273
|
+
return `fs.statSync(${generateExpr(args[0], context)}).size`;
|
|
1274
|
+
},
|
|
1275
|
+
fileType: (args, context) => {
|
|
1276
|
+
ensureBuiltin(context, 'fs');
|
|
1277
|
+
return `fs.statSync(${generateExpr(args[0], context)}).isDirectory() ? 'directory' : 'file'`;
|
|
1278
|
+
},
|
|
1279
|
+
lastModified: (args, context) => {
|
|
1280
|
+
ensureBuiltin(context, 'fs');
|
|
1281
|
+
return `new Date(fs.statSync(${generateExpr(args[0], context)}).mtimeMs).toISOString()`;
|
|
1282
|
+
},
|
|
1283
|
+
walkFolder: (args, context) => {
|
|
1284
|
+
ensureBuiltin(context, 'walk');
|
|
1285
|
+
return `__walkFolder(${generateExpr(args[0], context)})`;
|
|
1286
|
+
},
|
|
1287
|
+
joinPath: (_args, context) => {
|
|
1288
|
+
ensureBuiltin(context, 'path');
|
|
1289
|
+
return `path.join(${_args.map(a => generateExpr(a, context)).join(', ')})`;
|
|
1290
|
+
},
|
|
1291
|
+
baseName: (_args, context) => {
|
|
1292
|
+
ensureBuiltin(context, 'path');
|
|
1293
|
+
return `path.basename(${generateExpr(_args[0], context)})`;
|
|
1294
|
+
},
|
|
1295
|
+
folderOf: (_args, context) => {
|
|
1296
|
+
ensureBuiltin(context, 'path');
|
|
1297
|
+
return `path.dirname(${generateExpr(_args[0], context)})`;
|
|
1298
|
+
},
|
|
1299
|
+
extensionOf: (_args, context) => {
|
|
1300
|
+
ensureBuiltin(context, 'path');
|
|
1301
|
+
return `path.extname(${generateExpr(_args[0], context)})`;
|
|
1302
|
+
},
|
|
1303
|
+
|
|
1304
|
+
// Streams
|
|
1305
|
+
writeLine: (args, context) => {
|
|
1306
|
+
ensureBuiltin(context, 'fs');
|
|
1307
|
+
return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
|
|
1308
|
+
},
|
|
1309
|
+
appendLine: (args, context) => {
|
|
1310
|
+
ensureBuiltin(context, 'fs');
|
|
1311
|
+
return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
|
|
1312
|
+
},
|
|
967
1313
|
};
|
|
968
1314
|
|
|
969
1315
|
// Mark the enclosing program async when a call awaits at the top level.
|
|
@@ -1183,10 +1529,31 @@ function containsAsyncBlock(statements) {
|
|
|
1183
1529
|
return false;
|
|
1184
1530
|
}
|
|
1185
1531
|
|
|
1186
|
-
|
|
1187
|
-
|
|
1532
|
+
// True when any statement in a block (recursively, skipping nested function
|
|
1533
|
+
// declarations) contains a `yield`, which marks the enclosing function as a
|
|
1534
|
+
// generator (function*).
|
|
1535
|
+
function containsYield(statements) {
|
|
1536
|
+
for (const stmt of statements || []) {
|
|
1537
|
+
if (stmt.type === 'YieldStatement') return true;
|
|
1538
|
+
if (stmt.type === 'IfStatement') {
|
|
1539
|
+
if (containsYield(stmt.consequent)) return true;
|
|
1540
|
+
if (stmt.alternate && containsYield(stmt.alternate)) return true;
|
|
1541
|
+
} else if (stmt.type !== 'FunctionDeclaration' && stmt.body && Array.isArray(stmt.body)) {
|
|
1542
|
+
if (containsYield(stmt.body)) return true;
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
return false;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
function generate(ast, context = createGenerationContext()) { if (ast.type !== 'Program') {
|
|
1188
1549
|
throw new Error(`Expected a Program node but got "${ast.type}".`);
|
|
1189
1550
|
}
|
|
1551
|
+
// v1.0.0 — reset per-program test bookkeeping so repeated generate() calls
|
|
1552
|
+
// (build pipeline) start clean.
|
|
1553
|
+
__testCount = 0;
|
|
1554
|
+
__testCatchers = [];
|
|
1555
|
+
__inTest = false;
|
|
1556
|
+
|
|
1190
1557
|
const preludeStart = context.pendingPrelude.length;
|
|
1191
1558
|
const body = ast.body.map(node => generateStatement(node, '', context)).filter(Boolean).join('\n');
|
|
1192
1559
|
const lines = context.pendingPrelude.slice(preludeStart).concat(body).filter(Boolean);
|
|
@@ -1196,12 +1563,53 @@ function generate(ast, context = createGenerationContext()) {
|
|
|
1196
1563
|
const exported = ast.body
|
|
1197
1564
|
.filter(node => node.type === 'FunctionDeclaration')
|
|
1198
1565
|
.map(node => node.name);
|
|
1199
|
-
|
|
1566
|
+
const hasExplicitExport = ast.body.some(node => node.type === 'ExportStatement');
|
|
1567
|
+
// When the author uses explicit `export <name>`, they control the module
|
|
1568
|
+
// surface; skip the automatic function export so it does not clobber it.
|
|
1569
|
+
if (exported.length > 0 && !hasExplicitExport) {
|
|
1200
1570
|
lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
|
|
1201
1571
|
}
|
|
1572
|
+
|
|
1573
|
+
// v1.0.0 — native test runner. When any "test ... done" block exists, emit
|
|
1574
|
+
// the runner helper, register each test after its function declaration, and
|
|
1575
|
+
// execute them. Each failure prints a message and sets process.exitCode = 1.
|
|
1576
|
+
if (__testCatchers.length > 0) {
|
|
1577
|
+
const runner = [
|
|
1578
|
+
`const __tests = [];`,
|
|
1579
|
+
`function __check(op, a, b) {`,
|
|
1580
|
+
` const ok = op === 'contains'`,
|
|
1581
|
+
` ? String(a).includes(String(b))`,
|
|
1582
|
+
` : op === 'is'`,
|
|
1583
|
+
` ? a === b`,
|
|
1584
|
+
` : op === 'raises'`,
|
|
1585
|
+
` ? (() => { try { a(); } catch (e) { return String(e && e.message || '').includes(String(b)); } return false; })()`,
|
|
1586
|
+
` : a === b;`,
|
|
1587
|
+
` if (!ok) throw new Error('check failed: ' + op + ' ' + JSON.stringify(a) + ' vs ' + JSON.stringify(b));`,
|
|
1588
|
+
`}`,
|
|
1589
|
+
`function __runTests() {`,
|
|
1590
|
+
` let __passed = 0; let __failed = 0;`,
|
|
1591
|
+
` for (const __t of __tests) {`,
|
|
1592
|
+
` try { __t.fn(); console.log('PASS ' + __t.name); __passed++; }`,
|
|
1593
|
+
` catch (__e) { console.error('FAIL ' + __t.name + '\\n ' + (__e && __e.message)); __failed++; process.exitCode = 1; }`,
|
|
1594
|
+
` }`,
|
|
1595
|
+
` console.log(__passed + ' passed, ' + __failed + ' failed');`,
|
|
1596
|
+
`}`,
|
|
1597
|
+
].join('\n');
|
|
1598
|
+
lines.unshift(runner);
|
|
1599
|
+
for (const t of __testCatchers) {
|
|
1600
|
+
lines.push(`__tests.push({ name: ${JSON.stringify(t.name)}, fn: ${t.fnName} });`);
|
|
1601
|
+
}
|
|
1602
|
+
lines.push(`__runTests();`);
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1202
1605
|
return lines.join('\n');
|
|
1203
1606
|
}
|
|
1204
1607
|
|
|
1608
|
+
// ── v1.0.0 — test DSL bookkeeping ───────────────────────────────────────────
|
|
1609
|
+
let __testCount = 0;
|
|
1610
|
+
let __testCatchers = [];
|
|
1611
|
+
let __inTest = false;
|
|
1612
|
+
|
|
1205
1613
|
// ── Condition generation ────────────────────────────────────────────────────
|
|
1206
1614
|
|
|
1207
1615
|
function generateCondition(cond, context) {
|
|
@@ -1250,6 +1658,78 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1250
1658
|
case 'BecomeStatement':
|
|
1251
1659
|
return `${indent}${generateLValue(node.target, context)} = ${generateExpr(node.value, context)};`;
|
|
1252
1660
|
|
|
1661
|
+
// v1.0.0 — record kinds: `define a kind called "Person" with ... done`.
|
|
1662
|
+
// Names are emitted as a JS factory that returns a fresh plain object with
|
|
1663
|
+
// declared defaults. Constructors prompt for required fields at compile
|
|
1664
|
+
// time via `create a Person with ...` (see GenerateExpr CreateKind).
|
|
1665
|
+
case 'DefineKindStatement': {
|
|
1666
|
+
const members = node.fields.map(f =>
|
|
1667
|
+
`${JSON.stringify(f.key)}: ${f.value ? generateExpr(f.value, context) : 'undefined'}`
|
|
1668
|
+
);
|
|
1669
|
+
const defaults = `{ ${members.join(', ')} }`;
|
|
1670
|
+
return [
|
|
1671
|
+
`${indent}function __makeKind_${node.name}(${node.name}Fields) {`,
|
|
1672
|
+
`${indent} const __rec = ${defaults};`,
|
|
1673
|
+
`${indent} if (${node.name}Fields != null) {`,
|
|
1674
|
+
`${indent} for (const __k in ${node.name}Fields) {`,
|
|
1675
|
+
`${indent} if (!(Object.prototype.hasOwnProperty.call(__rec, __k))) throw new Error(${JSON.stringify('"' + node.name + '" has no field named "')} + __k + ${JSON.stringify('".')});`,
|
|
1676
|
+
`${indent} __rec[__k] = ${node.name}Fields[__k];`,
|
|
1677
|
+
`${indent} }`,
|
|
1678
|
+
`${indent} }`,
|
|
1679
|
+
`${indent} return __rec;`,
|
|
1680
|
+
`${indent}}`,
|
|
1681
|
+
`${indent}const ${node.name} = __makeKind_${node.name};`,
|
|
1682
|
+
].join('\n');
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
// v1.0.0 — load env file "<path>": apply KEY=VALUE pairs to process.env.
|
|
1686
|
+
// Blank lines and `#` comments are skipped; values keep their text.
|
|
1687
|
+
case 'LoadEnvFileStatement': {
|
|
1688
|
+
ensureBuiltin(context, 'dotenv');
|
|
1689
|
+
return `${indent}__loadEnvFile(${JSON.stringify(node.path)});`;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
// v1.0.0 — native test DSL. `test "<name>" ... done` registers a runnable
|
|
1693
|
+
// unit; all tests are executed after the program body with a tiny runner.
|
|
1694
|
+
case 'TestStatement': {
|
|
1695
|
+
__testCount++;
|
|
1696
|
+
const fnName = `__testFn_${__testCount}`;
|
|
1697
|
+
const prevInTest = __inTest;
|
|
1698
|
+
__inTest = true;
|
|
1699
|
+
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
1700
|
+
__inTest = prevInTest;
|
|
1701
|
+
__testCatchers.push({ name: node.name, fnName });
|
|
1702
|
+
return `${indent}function ${fnName}() {\n${body}\n${indent}}`;
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
// v1.0.0 — assertion `check <a> (equals|is|contains|raises) <b>`.
|
|
1706
|
+
// For `raises`, `a` is wrapped in a thunk so the expression is evaluated
|
|
1707
|
+
// inside the runner's try/catch (its thrown error is the subject).
|
|
1708
|
+
case 'CheckStatement': {
|
|
1709
|
+
if (!__inTest) {
|
|
1710
|
+
throw new Error('"check" can only be used inside a "test ... done" block.\n\nExample:\n test "addition"\n check 2 + 2 equals 4\n done');
|
|
1711
|
+
}
|
|
1712
|
+
const a = node.op === 'raises'
|
|
1713
|
+
? `(() => (${generateExpr(node.a, context)}))`
|
|
1714
|
+
: generateExpr(node.a, context);
|
|
1715
|
+
const b = generateExpr(node.b, context);
|
|
1716
|
+
return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
// v1.0.0 — export <name>: mark a top-level symbol for module.exports.
|
|
1720
|
+
case 'ExportStatement':
|
|
1721
|
+
return `${indent}module.exports.${node.name} = ${node.name};`;
|
|
1722
|
+
|
|
1723
|
+
// v1.0.0 — generators: `yield <expr>` (or bare `yield`).
|
|
1724
|
+
case 'YieldStatement': {
|
|
1725
|
+
if (!context.inFunction) {
|
|
1726
|
+
throw new Error('"yield" can only be used inside a function created with "make".\n\nExample:\n make countUp(n)\n let i = 0\n while i less than n\n i = i + 1\n yield i\n done\n done');
|
|
1727
|
+
}
|
|
1728
|
+
return node.value != null
|
|
1729
|
+
? `${indent}yield ${generateExpr(node.value, context)};`
|
|
1730
|
+
: `${indent}yield;`;
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1253
1733
|
case 'ExpressionStatement':
|
|
1254
1734
|
return `${indent}${generateExpr(node.expression, context)};`;
|
|
1255
1735
|
|
|
@@ -1321,12 +1801,19 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1321
1801
|
|
|
1322
1802
|
case 'FunctionDeclaration': {
|
|
1323
1803
|
const isAsync = containsAsyncBlock(node.body) ? 'async ' : '';
|
|
1324
|
-
const
|
|
1804
|
+
const isGen = containsYield(node.body) ? '*' : '';
|
|
1805
|
+
const paramStr = node.params.map(p => {
|
|
1806
|
+
if (typeof p === 'object') {
|
|
1807
|
+
if (p.defaultValue) return `${p.name} = ${generateExpr(p.defaultValue, context)}`;
|
|
1808
|
+
return p.name;
|
|
1809
|
+
}
|
|
1810
|
+
return p;
|
|
1811
|
+
}).join(', ');
|
|
1325
1812
|
const prevInFunction = context.inFunction;
|
|
1326
1813
|
context.inFunction = true;
|
|
1327
1814
|
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
1328
1815
|
context.inFunction = prevInFunction;
|
|
1329
|
-
return `${indent}${isAsync}function ${node.name}(${
|
|
1816
|
+
return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${body}\n${indent}}`;
|
|
1330
1817
|
}
|
|
1331
1818
|
|
|
1332
1819
|
case 'IfStatement': {
|
|
@@ -1550,16 +2037,46 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1550
2037
|
// ── v2.1.1 — error handling and retries
|
|
1551
2038
|
|
|
1552
2039
|
case 'TryStatement': {
|
|
1553
|
-
const tryBody = node.tryBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
1554
|
-
|
|
2040
|
+
const tryBody = (node.tryBody || node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2041
|
+
const tryBlock = `${indent}try {\n${tryBody}\n${indent}`;
|
|
2042
|
+
if (node.catches && node.catches.length > 0) {
|
|
2043
|
+
const lines = [tryBlock];
|
|
2044
|
+
for (let i = 0; i < node.catches.length; i++) {
|
|
2045
|
+
const c = node.catches[i];
|
|
2046
|
+
const errorName = c.name || c.param || '__plainError';
|
|
2047
|
+
const catchBody = c.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2048
|
+
const isFirst = i === 0;
|
|
2049
|
+
const isLast = i === node.catches.length - 1;
|
|
2050
|
+
if (isFirst) {
|
|
2051
|
+
lines.push(`${indent}} catch (${errorName}) {`);
|
|
2052
|
+
}
|
|
2053
|
+
if (c.errorType) {
|
|
2054
|
+
const cond = isFirst ? 'if' : 'else if';
|
|
2055
|
+
lines.push(`${indent} ${cond} (${errorName} instanceof ${c.errorType}) {`);
|
|
2056
|
+
lines.push(catchBody);
|
|
2057
|
+
lines.push(`${indent} }`);
|
|
2058
|
+
if (isLast) lines.push(`${indent}}`);
|
|
2059
|
+
} else {
|
|
2060
|
+
if (isFirst && isLast) {
|
|
2061
|
+
lines.push(catchBody);
|
|
2062
|
+
lines.push(`${indent}}`);
|
|
2063
|
+
} else {
|
|
2064
|
+
lines.push(`${indent} else {`);
|
|
2065
|
+
lines.push(catchBody);
|
|
2066
|
+
lines.push(`${indent} }`);
|
|
2067
|
+
if (isLast) lines.push(`${indent}}`);
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
return lines.join('\n');
|
|
2072
|
+
}
|
|
2073
|
+
let out = tryBlock;
|
|
1555
2074
|
if (node.recoverBody) {
|
|
1556
2075
|
const errorName = node.catchName || '__plainError';
|
|
1557
2076
|
const recoverBody = node.recoverBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
1558
2077
|
out += ` catch (${errorName}) {\n${recoverBody}\n${indent}}`;
|
|
1559
2078
|
} else {
|
|
1560
|
-
|
|
1561
|
-
// swallowed through an empty catch block.
|
|
1562
|
-
out += ' catch (__plainError) {}';
|
|
2079
|
+
out += `${indent}} catch (__plainError) {}`;
|
|
1563
2080
|
}
|
|
1564
2081
|
return out;
|
|
1565
2082
|
}
|
|
@@ -1865,6 +2382,79 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1865
2382
|
ensureBuiltin(context, 'websocket');
|
|
1866
2383
|
return `${indent}__wsBroadcast(__wsServer, ${generateExpr(node.value, context)});`;
|
|
1867
2384
|
|
|
2385
|
+
// ── IOPL-native features ──────────────────────────────────────────────
|
|
2386
|
+
|
|
2387
|
+
case 'GatherStatement': {
|
|
2388
|
+
const coll = generateExpr(node.collection, context);
|
|
2389
|
+
const body = generateExpr(node.body, context);
|
|
2390
|
+
return `${indent}${coll} = ${coll}.map(${node.item} => ${body});`;
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
case 'FilterStatement': {
|
|
2394
|
+
const coll = generateExpr(node.collection, context);
|
|
2395
|
+
const cond = generateCondition(node.condition, context);
|
|
2396
|
+
return `${indent}${coll} = ${coll}.filter(${node.item} => ${cond});`;
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
case 'TotalStatement': {
|
|
2400
|
+
const coll = generateExpr(node.collection, context);
|
|
2401
|
+
const body = generateExpr(node.body, context);
|
|
2402
|
+
return `${indent}${coll} = ${coll}.reduce((__sum, ${node.item}) => __sum + ${body}, 0);`;
|
|
2403
|
+
}
|
|
2404
|
+
|
|
2405
|
+
case 'MatchStatement': {
|
|
2406
|
+
const value = generateExpr(node.value, context);
|
|
2407
|
+
const lines = [`${indent}switch (${value}) {`];
|
|
2408
|
+
for (const c of node.cases) {
|
|
2409
|
+
const testVal = generateExpr(c.test, context);
|
|
2410
|
+
lines.push(`${indent} case ${testVal}:`);
|
|
2411
|
+
for (const s of c.body) lines.push(generateStatement(s, indent + ' ', context));
|
|
2412
|
+
lines.push(`${indent} break;`);
|
|
2413
|
+
}
|
|
2414
|
+
if (node.defaultCase) {
|
|
2415
|
+
lines.push(`${indent} default:`);
|
|
2416
|
+
for (const s of node.defaultCase) lines.push(generateStatement(s, indent + ' ', context));
|
|
2417
|
+
lines.push(`${indent} break;`);
|
|
2418
|
+
}
|
|
2419
|
+
lines.push(`${indent}}`);
|
|
2420
|
+
return lines.join('\n');
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2423
|
+
case 'RegexMatchStatement': {
|
|
2424
|
+
const source = generateExpr(node.source, context);
|
|
2425
|
+
const pattern = typeof node.pattern === 'string' ? JSON.stringify(node.pattern) : generateExpr(node.pattern, context);
|
|
2426
|
+
return `${indent}const ${node.name} = ${source}.match(new RegExp(${pattern}));`;
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
case 'EmitStatement': {
|
|
2430
|
+
ensureBuiltin(context, '__emitter');
|
|
2431
|
+
const event = typeof node.event === 'string' ? JSON.stringify(node.event) : generateExpr(node.event, context);
|
|
2432
|
+
const data = node.data ? generateExpr(node.data, context) : '';
|
|
2433
|
+
return `${indent}__emitter.emit(${event}${data ? ', ' + data : ''});`;
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
case 'WhenHappensStatement': {
|
|
2437
|
+
ensureBuiltin(context, '__emitter');
|
|
2438
|
+
const event = typeof node.event === 'string' ? JSON.stringify(node.event) : generateExpr(node.event, context);
|
|
2439
|
+
const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2440
|
+
return `${indent}__emitter.on(${event}, (${node.paramName}) => {\n${body}\n${indent}});`;
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
case 'StreamStatement': {
|
|
2444
|
+
ensureBuiltin(context, '__streamFile');
|
|
2445
|
+
markAsync(context);
|
|
2446
|
+
const filename = generateExpr(node.filename, context);
|
|
2447
|
+
const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2448
|
+
return `${indent}await __streamFile(${filename}, async (${node.paramName}) => {\n${body}\n${indent}});`;
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
case 'RunParallelStatement': {
|
|
2452
|
+
markAsync(context);
|
|
2453
|
+
const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2454
|
+
const resultName = node.resultName || '__parallelResults';
|
|
2455
|
+
return `${indent}const ${resultName} = await Promise.all([(async () => {\n${body}\n${indent}})()]);`;
|
|
2456
|
+
}
|
|
2457
|
+
|
|
1868
2458
|
default:
|
|
1869
2459
|
throw new Error(`Unknown statement type "${node.type}".`);
|
|
1870
2460
|
}
|
|
@@ -2024,6 +2614,29 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
2024
2614
|
ensureBuiltin(context, 'fs');
|
|
2025
2615
|
return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
|
|
2026
2616
|
|
|
2617
|
+
// v1.0.0 — record constructor: `create a Person with name "Ada" and age 17`
|
|
2618
|
+
// calls the kind factory that `define a kind called "Person"` registered.
|
|
2619
|
+
case 'CreateKindExpression': {
|
|
2620
|
+
const fields = node.pairs
|
|
2621
|
+
.map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
|
|
2622
|
+
.join(', ');
|
|
2623
|
+
return `${node.kind}({ ${fields} })`;
|
|
2624
|
+
}
|
|
2625
|
+
|
|
2626
|
+
// v1.0.0 — concurrency combinators: `all of [...]` / `any of [...]` /
|
|
2627
|
+
// `settled of [...]`. All are awaited; `settled` returns status records.
|
|
2628
|
+
case 'ConcurrencyExpression': {
|
|
2629
|
+
markAsync(context);
|
|
2630
|
+
const rhs = generateExpr(node.items, context);
|
|
2631
|
+
if (node.combo === 'any') return `(await Promise.race(${rhs}))`;
|
|
2632
|
+
if (node.combo === 'settled') return `(await Promise.allSettled(${rhs}))`;
|
|
2633
|
+
return `(await Promise.all(${rhs}))`;
|
|
2634
|
+
}
|
|
2635
|
+
|
|
2636
|
+
// v1.0.0 — `spread of <collection>` → a fresh array from an iterable.
|
|
2637
|
+
case 'SpreadExpression':
|
|
2638
|
+
return `[...${generateExpr(node.collection, context)}]`;
|
|
2639
|
+
|
|
2027
2640
|
default:
|
|
2028
2641
|
throw new Error(`Unknown expression type "${node.type}".`);
|
|
2029
2642
|
}
|