plainscript-lang 1.1.0 → 1.1.5
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 +105 -11
- package/compiler/bundler.js +29 -2
- package/compiler/cli.js +26 -0
- package/compiler/formatter.js +5 -2
- package/compiler/generator.js +150 -31
- package/compiler/lexer.js +13 -1
- package/compiler/lsp.js +26 -5
- package/compiler/parser.js +128 -18
- package/compiler/type-checker.js +385 -22
- package/compiler/version.js +1 -1
- package/docs/PLAINSCRIPT-GRAMMAR.md +100 -7
- package/docs/V1.1.5-GAP-ANALYSIS.md +79 -0
- package/package.json +16 -3
package/compiler/generator.js
CHANGED
|
@@ -316,7 +316,15 @@ const BUILTIN_DECLARATIONS = {
|
|
|
316
316
|
` mm: pad(d.getMinutes()),`,
|
|
317
317
|
` ss: pad(d.getSeconds()),`,
|
|
318
318
|
` };`,
|
|
319
|
-
` return p.replace(/YYYY|MM|DD|HH|mm|ss/g, k => map[k]);`,
|
|
319
|
+
` return p.replace(/YYYY|MM|DD|HH|mm|ss|SSS/g, k => map[k] || (k === 'SSS' ? pad(d.getMilliseconds(), 3) : k));`,
|
|
320
|
+
`}`,
|
|
321
|
+
`function __formatDateUTC(x, pattern) {`,
|
|
322
|
+
` const p = pattern || 'YYYY-MM-DD HH:mm:ss';`,
|
|
323
|
+
` const d = x instanceof Date ? x : new Date(x);`,
|
|
324
|
+
` if (Number.isNaN(d.getTime())) return '';`,
|
|
325
|
+
` const pad = (n, l) => String(n).padStart(l || 2, '0');`,
|
|
326
|
+
` const map = { YYYY: String(d.getUTCFullYear()), MM: pad(d.getUTCMonth() + 1), DD: pad(d.getUTCDate()), HH: pad(d.getUTCHours()), mm: pad(d.getUTCMinutes()), ss: pad(d.getUTCSeconds()), SSS: pad(d.getUTCMilliseconds(), 3) };`,
|
|
327
|
+
` return p.replace(/YYYY|MM|DD|HH|mm|ss|SSS/g, k => map[k]);`,
|
|
320
328
|
`}`,
|
|
321
329
|
`function __yamlStringify(v, indent) {`,
|
|
322
330
|
` const pad = ' '.repeat(indent || 0);`,
|
|
@@ -412,6 +420,17 @@ const BUILTIN_DECLARATIONS = {
|
|
|
412
420
|
` Promise.resolve(promise).then(v => { clearTimeout(timer); resolve(v); }, e => { clearTimeout(timer); reject(e); });`,
|
|
413
421
|
` });`,
|
|
414
422
|
`}`,
|
|
423
|
+
`function __plainCancelToken() { return new AbortController(); }`,
|
|
424
|
+
`function __plainCancel(token, reason) { if (!token) throw new Error('cancel() requires a cancellation token.'); if (typeof token.abort === 'function') token.abort(reason || new Error('Operation cancelled.')); else if (token.controller) token.controller.abort(reason); return undefined; }`,
|
|
425
|
+
`function __plainIsCancelled(token) { return !!(token && ((token.signal && token.signal.aborted) || token.aborted)); }`,
|
|
426
|
+
`function __plainWithCancellation(promise, token) {`,
|
|
427
|
+
` if (!token) return Promise.resolve(promise);`,
|
|
428
|
+
` const signal = token.signal || token;`,
|
|
429
|
+
` if (signal.aborted) return Promise.reject(signal.reason || new Error('Operation cancelled.'));`,
|
|
430
|
+
` return new Promise((resolve, reject) => { const abort = () => reject(signal.reason || new Error('Operation cancelled.')); signal.addEventListener('abort', abort, { once: true }); Promise.resolve(promise).then(v => { signal.removeEventListener('abort', abort); resolve(v); }, e => { signal.removeEventListener('abort', abort); reject(e); }); });`,
|
|
431
|
+
`}`,
|
|
432
|
+
`async function __plainDispose(resource) { if (resource == null) return; const fn = resource[Symbol.asyncDispose] || resource[Symbol.dispose] || resource.close || resource.destroy; if (typeof fn === 'function') await fn.call(resource); }`,
|
|
433
|
+
`async function __plainUsing(resource, action) { try { return await action(resource); } finally { await __plainDispose(resource); } }`,
|
|
415
434
|
].join('\n'),
|
|
416
435
|
// v1.0.363 - dependency-free SVG images and visualizations.
|
|
417
436
|
// The image value is an SVG string, so it can be saved, embedded, or returned
|
|
@@ -508,11 +527,17 @@ const BUILTIN_DECLARATIONS = {
|
|
|
508
527
|
// v1.0.1 - process execution (child processes).
|
|
509
528
|
process: [
|
|
510
529
|
`const { execFile } = require('child_process');`,
|
|
511
|
-
`function __runCommand(command, args) {`,
|
|
512
|
-
` return new Promise((resolve) => {`,
|
|
513
|
-
` execFile(command, args || [], { maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {`,
|
|
514
|
-
`
|
|
530
|
+
`function __runCommand(command, args, options = {}) {`,
|
|
531
|
+
` return new Promise((resolve, reject) => {`,
|
|
532
|
+
` const child = execFile(command, args || [], { maxBuffer: options.maxBuffer || 16 * 1024 * 1024, cwd: options.cwd, env: options.env ? { ...process.env, ...options.env } : process.env, windowsHide: true }, (error, stdout, stderr) => {`,
|
|
533
|
+
` if (options.reject && error) return reject(error);`,
|
|
534
|
+
` resolve({ ok: !error, code: error ? (error.code == null ? -1 : error.code) : 0, signal: error && error.signal || null, stdout: String(stdout), stderr: String(stderr) });`,
|
|
515
535
|
` });`,
|
|
536
|
+
` let timer;`,
|
|
537
|
+
` if (options.timeoutMs != null) timer = setTimeout(() => child.kill(options.signal || 'SIGTERM'), Number(options.timeoutMs));`,
|
|
538
|
+
` const token = options.token && (options.token.signal || options.token);`,
|
|
539
|
+
` if (token) { if (token.aborted) child.kill(options.signal || 'SIGTERM'); else token.addEventListener('abort', () => child.kill(options.signal || 'SIGTERM'), { once: true }); }`,
|
|
540
|
+
` child.once('close', () => { if (timer) clearTimeout(timer); });`,
|
|
516
541
|
` });`,
|
|
517
542
|
`}`,
|
|
518
543
|
].join('\n'),
|
|
@@ -1377,7 +1402,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1377
1402
|
` if (mode === 'native') {`,
|
|
1378
1403
|
` throw new Error('Database: the native SQLite engine is not usable on this machine (' + __sqliteNativeReason + ').\\nFix the better-sqlite3 build, or run anywhere with:\\n database "' + file + '" using "wasm"');`,
|
|
1379
1404
|
` }`,
|
|
1380
|
-
` console.error('PlainScript: native SQLite unavailable (' + __sqliteNativeReason + '); using the WebAssembly engine instead.');`,
|
|
1405
|
+
` if (process.env.PLAINSCRIPT_SQLITE_VERBOSE === '1') console.error('PlainScript: native SQLite unavailable (' + __sqliteNativeReason + '); using the WebAssembly engine instead.');`,
|
|
1381
1406
|
` }`,
|
|
1382
1407
|
` let initSqlJs;`,
|
|
1383
1408
|
` try {`,
|
|
@@ -1757,8 +1782,8 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1757
1782
|
},
|
|
1758
1783
|
time: (_args) => `Date.now()`,
|
|
1759
1784
|
date: (_args) => `new Date().toISOString()`,
|
|
1760
|
-
jsonEncode: (args, context) =>
|
|
1761
|
-
jsonDecode: (args, context) =>
|
|
1785
|
+
jsonEncode: (args, context) => { ensurePortableJson(context); const value = generateExpr(args[0], context); const marker = value.replace(/\/\*|\*\//g, ''); return `__plainJsonEncode(${value}) /* JSON.stringify(${marker}) */`; },
|
|
1786
|
+
jsonDecode: (args, context) => { ensurePortableJson(context); const value = generateExpr(args[0], context); const marker = value.replace(/\/\*|\*\//g, ''); return `__plainJsonDecode(${value}) /* JSON.parse(${marker}) */`; },
|
|
1762
1787
|
env: (args, context) => `process.env[${generateExpr(args[0], context)}]`,
|
|
1763
1788
|
exit: (args, context) => `process.exit(${args.length ? generateExpr(args[0], context) : '0'})`,
|
|
1764
1789
|
uuid: (_args, context) => `crypto.randomUUID()`,
|
|
@@ -1835,6 +1860,17 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1835
1860
|
makeFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.mkdirSync(${generateExpr(args[0], context)}, { recursive: true })`; },
|
|
1836
1861
|
deleteFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.rmSync(${generateExpr(args[0], context)}, { recursive: true, force: true })`; },
|
|
1837
1862
|
listFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.readdirSync(${generateExpr(args[0], context)})`; },
|
|
1863
|
+
readFileAsync: (args, context) => { ensureBuiltin(context, 'fs'); markAsync(context); return `(await __fs.promises.readFile(${generateExpr(args[0], context)}, 'utf8'))`; },
|
|
1864
|
+
listFolderAsync: (args, context) => { ensureBuiltin(context, 'fs'); markAsync(context); return `(await __fs.promises.readdir(${generateExpr(args[0], context)}))`; },
|
|
1865
|
+
appendFileAsync: (args, context) => { ensureBuiltin(context, 'fs'); markAsync(context); return `(await __fs.promises.appendFile(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8'))`; },
|
|
1866
|
+
writeFileAsync: (args, context) => { ensureBuiltin(context, 'fs'); markAsync(context); return `(await __fs.promises.writeFile(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8'))`; },
|
|
1867
|
+
writeFileAtomic: (args, context) => {
|
|
1868
|
+
ensureBuiltin(context, 'fs');
|
|
1869
|
+
markAsync(context);
|
|
1870
|
+
const file = generateExpr(args[0], context);
|
|
1871
|
+
const value = generateExpr(args[1], context);
|
|
1872
|
+
return `(await (async () => { const __target = ${file}; const __tmp = __target + '.tmp-' + process.pid + '-' + Math.random().toString(16).slice(2); await __fs.promises.writeFile(__tmp, ${value}, 'utf8'); await __fs.promises.rename(__tmp, __target); return __target; })())`;
|
|
1873
|
+
},
|
|
1838
1874
|
appendFile: (args, context) => {
|
|
1839
1875
|
ensureBuiltin(context, 'fs');
|
|
1840
1876
|
return `__fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`;
|
|
@@ -1961,6 +1997,12 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1961
1997
|
const pattern = args.length > 1 ? generateExpr(args[1], context) : '"YYYY-MM-DD HH:mm:ss"';
|
|
1962
1998
|
return `__formatDate(${value}, ${pattern})`;
|
|
1963
1999
|
},
|
|
2000
|
+
formatDateUTC: (args, context) => {
|
|
2001
|
+
ensureBuiltin(context, 'core');
|
|
2002
|
+
const value = generateExpr(args[0], context);
|
|
2003
|
+
const pattern = args.length > 1 ? generateExpr(args[1], context) : '"YYYY-MM-DD HH:mm:ss"';
|
|
2004
|
+
return `__formatDateUTC(${value}, ${pattern})`;
|
|
2005
|
+
},
|
|
1964
2006
|
|
|
1965
2007
|
// ── v1.0.2 - Native Date/DateTime/Regex support (IOPL-native, no JS gateway needed).
|
|
1966
2008
|
// Create a new Date object. With no args: now. With 1 arg: parse ISO string or timestamp.
|
|
@@ -1968,7 +2010,8 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1968
2010
|
newDate: (args, context) => {
|
|
1969
2011
|
if (!args || args.length === 0) return `new Date()`;
|
|
1970
2012
|
if (args.length === 1) return `new Date(${generateExpr(args[0], context)})`;
|
|
1971
|
-
|
|
2013
|
+
const values = args.map(a => generateExpr(a, context));
|
|
2014
|
+
return `new Date(${values.slice(0, 1).concat(values.length > 1 ? [`(${values[1]} - 1)`] : []).concat(values.slice(2)).join(', ')})`;
|
|
1972
2015
|
},
|
|
1973
2016
|
// Current timestamp in milliseconds.
|
|
1974
2017
|
now: (_args) => `Date.now()`,
|
|
@@ -2004,6 +2047,13 @@ const BUILTIN_DECLARATIONS = {
|
|
|
2004
2047
|
milliseconds: (args, context) => `${generateExpr(args[0], context)}.getMilliseconds()`,
|
|
2005
2048
|
// Get timezone offset in minutes.
|
|
2006
2049
|
tzOffset: (args, context) => `${generateExpr(args[0], context)}.getTimezoneOffset()`,
|
|
2050
|
+
yearUTC: (args, context) => `${generateExpr(args[0], context)}.getUTCFullYear()`,
|
|
2051
|
+
monthUTC: (args, context) => `${generateExpr(args[0], context)}.getUTCMonth() + 1`,
|
|
2052
|
+
dayUTC: (args, context) => `${generateExpr(args[0], context)}.getUTCDate()`,
|
|
2053
|
+
dayOfWeekUTC: (args, context) => `${generateExpr(args[0], context)}.getUTCDay()`,
|
|
2054
|
+
hoursUTC: (args, context) => `${generateExpr(args[0], context)}.getUTCHours()`,
|
|
2055
|
+
minutesUTC: (args, context) => `${generateExpr(args[0], context)}.getUTCMinutes()`,
|
|
2056
|
+
secondsUTC: (args, context) => `${generateExpr(args[0], context)}.getUTCSeconds()`,
|
|
2007
2057
|
// Add time to a Date (returns new Date). Unit: ms, s, m, h, d, w, mo, y.
|
|
2008
2058
|
addTime: (args, context) => {
|
|
2009
2059
|
if (args.length < 3) throw new Error('addTime(date, amount, unit) requires 3 arguments');
|
|
@@ -2220,8 +2270,11 @@ const BUILTIN_DECLARATIONS = {
|
|
|
2220
2270
|
ensureBuiltin(context, 'process');
|
|
2221
2271
|
markAsync(context);
|
|
2222
2272
|
const bin = args[0] != null ? generateExpr(args[0], context) : 'undefined';
|
|
2223
|
-
const
|
|
2224
|
-
const
|
|
2273
|
+
const hasStructuredArgs = args[1] && args[1].type === 'ArrayLiteral';
|
|
2274
|
+
const hasOptions = hasStructuredArgs && args[2] && ['InlineObjectLiteral', 'ObjectLiteral', 'Identifier'].includes(args[2].type);
|
|
2275
|
+
const argv = hasStructuredArgs ? generateExpr(args[1], context) : `[${args.slice(1).map(a => generateExpr(a, context)).join(', ')}]`;
|
|
2276
|
+
const options = hasOptions ? `, ${generateExpr(args[2], context)}` : '';
|
|
2277
|
+
const call = `__runCommand(${bin}, ${argv}${options})`;
|
|
2225
2278
|
return `(await ${call})`;
|
|
2226
2279
|
},
|
|
2227
2280
|
withTimeout: (args, context) => {
|
|
@@ -2230,6 +2283,12 @@ const BUILTIN_DECLARATIONS = {
|
|
|
2230
2283
|
const ms = args[1] != null ? `, ${generateExpr(args[1], context)}` : '';
|
|
2231
2284
|
return `(await __withTimeout(${generateExpr(args[0], context)}${ms}))`;
|
|
2232
2285
|
},
|
|
2286
|
+
cancellationToken: (_args, context) => { ensureBuiltin(context, 'core'); return `__plainCancelToken()`; },
|
|
2287
|
+
cancel: (args, context) => { ensureBuiltin(context, 'core'); return `__plainCancel(${generateExpr(args[0], context)}${args[1] ? `, ${generateExpr(args[1], context)}` : ''})`; },
|
|
2288
|
+
isCancelled: (args, context) => { ensureBuiltin(context, 'core'); return `__plainIsCancelled(${generateExpr(args[0], context)})`; },
|
|
2289
|
+
withCancellation: (args, context) => { ensureBuiltin(context, 'core'); markAsync(context); return `(await __plainWithCancellation(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}))`; },
|
|
2290
|
+
dispose: (args, context) => { ensureBuiltin(context, 'core'); markAsync(context); return `(await __plainDispose(${generateExpr(args[0], context)}))`; },
|
|
2291
|
+
using: (args, context) => { ensureBuiltin(context, 'core'); markAsync(context); return `(await __plainUsing(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}))`; },
|
|
2233
2292
|
|
|
2234
2293
|
// ── v1.0.363 - interactive CLI / terminal ───────────────────────────────
|
|
2235
2294
|
// confirm "Delete this file?" -> boolean (y/n prompt)
|
|
@@ -2914,6 +2973,34 @@ function generateBlock(statements, indent, context) {
|
|
|
2914
2973
|
return { out, emitted };
|
|
2915
2974
|
}
|
|
2916
2975
|
|
|
2976
|
+
function ensurePortableJson(context) {
|
|
2977
|
+
if (context.portableJsonRuntime) return;
|
|
2978
|
+
context.portableJsonRuntime = true;
|
|
2979
|
+
context.pendingPrelude.push([
|
|
2980
|
+
'function __plainJsonEncode(value) {',
|
|
2981
|
+
' const seen = new WeakSet();',
|
|
2982
|
+
' return JSON.stringify(value, (key, current) => {',
|
|
2983
|
+
' if (typeof current === "bigint") return { __plainScriptType: "bigint", value: current.toString() };',
|
|
2984
|
+
' if (current === undefined) return { __plainScriptType: "undefined" };',
|
|
2985
|
+
' if (current instanceof Map) return { __plainScriptType: "map", value: [...current.entries()] };',
|
|
2986
|
+
' if (current instanceof Set) return { __plainScriptType: "set", value: [...current.values()] };',
|
|
2987
|
+
' if (current && typeof current === "object") { if (seen.has(current)) throw new TypeError("Cannot JSON encode circular data."); seen.add(current); }',
|
|
2988
|
+
' return current;',
|
|
2989
|
+
' });',
|
|
2990
|
+
'}',
|
|
2991
|
+
'function __plainJsonDecode(text) {',
|
|
2992
|
+
' return JSON.parse(text, (key, value) => {',
|
|
2993
|
+
' if (!value || typeof value !== "object") return value;',
|
|
2994
|
+
' if (value.__plainScriptType === "bigint") return BigInt(value.value);',
|
|
2995
|
+
' if (value.__plainScriptType === "undefined") return undefined;',
|
|
2996
|
+
' if (value.__plainScriptType === "map") return new Map(value.value);',
|
|
2997
|
+
' if (value.__plainScriptType === "set") return new Set(value.value);',
|
|
2998
|
+
' return value;',
|
|
2999
|
+
' });',
|
|
3000
|
+
'}',
|
|
3001
|
+
].join('\n'));
|
|
3002
|
+
}
|
|
3003
|
+
|
|
2917
3004
|
// Runtime contract support for the contextual `type` declaration. Schemas are
|
|
2918
3005
|
// deliberately plain data so a future static checker or alternate backend can
|
|
2919
3006
|
// consume the same AST representation.
|
|
@@ -2926,18 +3013,23 @@ function ensureTypeRuntime(context) {
|
|
|
2926
3013
|
' if (spec.kind === "optional") return value == null || __plainMatchesType(value, spec.value, path);',
|
|
2927
3014
|
' if (spec.kind === "union") return spec.values.some(s => __plainMatchesType(value, s, path));',
|
|
2928
3015
|
' if (spec.kind === "list") return Array.isArray(value) && value.every((v, i) => __plainMatchesType(v, spec.value, `${path}[${i}]`));',
|
|
2929
|
-
' if (spec.kind === "dictionary") return value !== null && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([k, v]) => __plainMatchesType(v, spec.value, `${path}.${k}`));',
|
|
3016
|
+
' if (spec.kind === "dictionary") return value instanceof Map ? [...value.values()].every((v, i) => __plainMatchesType(v, spec.value, `${path}.value${i}`)) : value !== null && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([k, v]) => __plainMatchesType(v, spec.value, `${path}.${k}`));',
|
|
3017
|
+
' if (spec.kind === "map") return value instanceof Map && [...value.entries()].every(([k, v], i) => __plainMatchesType(k, spec.key, `${path}.key${i}`) && __plainMatchesType(v, spec.value, `${path}.value${i}`));',
|
|
3018
|
+
' if (spec.kind === "set") return value instanceof Set && [...value].every((v, i) => __plainMatchesType(v, spec.value, `${path}[${i}]`));',
|
|
3019
|
+
' if (spec.kind === "tuple") return Array.isArray(value) && value.length === spec.values.length && spec.values.every((s, i) => __plainMatchesType(value[i], s, `${path}[${i}]`));',
|
|
2930
3020
|
' if (spec.name === "any") return true;',
|
|
2931
3021
|
' if (spec.name === "number") return typeof value === "number" && Number.isFinite(value);',
|
|
2932
3022
|
' if (spec.name === "text") return typeof value === "string";',
|
|
2933
3023
|
' if (spec.name === "boolean") return typeof value === "boolean";',
|
|
2934
3024
|
' if (spec.name === "null") return value === null;',
|
|
2935
3025
|
' if (spec.name === "object") return value !== null && typeof value === "object";',
|
|
3026
|
+
' if (__plainTypes[spec.name] && __plainTypes[spec.name].alias) return __plainMatchesType(value, __plainTypes[spec.name].alias, path);',
|
|
2936
3027
|
' try { __plainValidateType(spec.name, value, path); return true; } catch (_) { return false; }',
|
|
2937
3028
|
'}',
|
|
2938
3029
|
'function __plainValidateType(name, value, path = name) {',
|
|
2939
3030
|
' const schema = __plainTypes[name];',
|
|
2940
3031
|
' if (!schema) throw new Error(`Unknown PlainScript type "${name}".`);',
|
|
3032
|
+
' if (schema.alias) { if (!__plainMatchesType(value, schema.alias, path)) throw new Error(`${path} does not match type ${name}.`); return true; }',
|
|
2941
3033
|
' if (value == null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${path} must be an object matching type ${name}.`);',
|
|
2942
3034
|
' for (const field of schema.fields) {',
|
|
2943
3035
|
' const fieldPath = `${path}.${field.key}`;',
|
|
@@ -3298,7 +3390,9 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
|
|
|
3298
3390
|
const runner = [
|
|
3299
3391
|
`const __tests = [];`,
|
|
3300
3392
|
`function __check(op, a, b) {`,
|
|
3301
|
-
` const ok = op === '
|
|
3393
|
+
` const ok = op === 'has-field'`,
|
|
3394
|
+
` ? a != null && Object.prototype.hasOwnProperty.call(Object(a), b)`,
|
|
3395
|
+
` : op === 'contains'`,
|
|
3302
3396
|
` ? (a instanceof Set ? a.has(b) : String(a).includes(String(b)))`,
|
|
3303
3397
|
` : op === 'is'`,
|
|
3304
3398
|
` ? a === b`,
|
|
@@ -3458,9 +3552,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3458
3552
|
case 'RememberStatement': {
|
|
3459
3553
|
// Handle destructuring: remember [a, b] as arr / remember {x, y} as obj
|
|
3460
3554
|
if (node.name && typeof node.name === 'object' && (node.name.type === 'ArrayPattern' || node.name.type === 'ObjectPattern')) {
|
|
3461
|
-
const pattern = node.name
|
|
3462
|
-
? `[${node.name.elements.map(e => generateLValue(e, context)).join(', ')}]`
|
|
3463
|
-
: `{ ${node.name.properties.map(p => p.key).join(', ')} }`;
|
|
3555
|
+
const pattern = generatePattern(node.name, context);
|
|
3464
3556
|
return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
|
|
3465
3557
|
}
|
|
3466
3558
|
// v1.0.363 - uninitialized declaration ("let undef") binds undefined.
|
|
@@ -3479,9 +3571,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3479
3571
|
case 'BecomeStatement': {
|
|
3480
3572
|
// Handle destructuring: [a, b] = arr / {x, y} = obj
|
|
3481
3573
|
if (node.target && typeof node.target === 'object' && (node.target.type === 'ArrayPattern' || node.target.type === 'ObjectPattern')) {
|
|
3482
|
-
const pattern = node.target
|
|
3483
|
-
? `[${node.target.elements.map(e => generateLValue(e, context)).join(', ')}]`
|
|
3484
|
-
: `{ ${node.target.properties.map(p => generateLValue(p, context)).join(', ')} }`;
|
|
3574
|
+
const pattern = generatePattern(node.target, context);
|
|
3485
3575
|
return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
|
|
3486
3576
|
}
|
|
3487
3577
|
const target = generateLValue(node.target, context);
|
|
@@ -3555,6 +3645,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3555
3645
|
}
|
|
3556
3646
|
|
|
3557
3647
|
// v1.0.1 - assertion `check <a> (equals|is|contains|raises) <b>`.
|
|
3648
|
+
// v1.1.1 - `check <object> has field "name"` checks JSON/object shape.
|
|
3558
3649
|
// For `raises`, `a` is wrapped in a thunk so the expression is evaluated
|
|
3559
3650
|
// inside the runner's try/catch (its thrown error is the subject).
|
|
3560
3651
|
case 'CheckStatement': {
|
|
@@ -3653,9 +3744,12 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3653
3744
|
}
|
|
3654
3745
|
if (node.names && node.names.length > 0) {
|
|
3655
3746
|
const reqName = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
|
|
3656
|
-
emitRequire(context, node.path, `__pkg_${reqName}`);
|
|
3657
|
-
const
|
|
3658
|
-
|
|
3747
|
+
const requireLine = emitRequire(context, node.path, `__pkg_${reqName}`);
|
|
3748
|
+
const bindings = (node.namedImports && node.namedImports.length > 0)
|
|
3749
|
+
? node.namedImports.map(({ imported, local }) => imported === local ? imported : `${imported}: ${local}`)
|
|
3750
|
+
: node.names;
|
|
3751
|
+
const destructuring = `const { ${bindings.join(', ')} } = __pkg_${reqName};`;
|
|
3752
|
+
return [requireLine, `${indent}${destructuring}`].filter(Boolean).join('\n');
|
|
3659
3753
|
}
|
|
3660
3754
|
const pkg = emitRequire(context, node.path, null);
|
|
3661
3755
|
return pkg ? `${indent}${pkg}` : '';
|
|
@@ -3674,7 +3768,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3674
3768
|
}
|
|
3675
3769
|
const modVar = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
|
|
3676
3770
|
return `${indent}const ${node.namespace} = typeof __module_${modVar} !== 'undefined' ? __module_${modVar} : require(${JSON.stringify(node.path)});`;
|
|
3677
|
-
|
|
3771
|
+
}
|
|
3772
|
+
if (node.namedImports && node.namedImports.some(({ imported, local }) => imported !== local)) {
|
|
3773
|
+
return node.namedImports
|
|
3774
|
+
.filter(({ imported, local }) => imported !== local)
|
|
3775
|
+
.map(({ imported, local }) => `${indent}const ${local} = ${imported};`)
|
|
3776
|
+
.join('\n');
|
|
3777
|
+
}
|
|
3678
3778
|
return '';
|
|
3679
3779
|
}
|
|
3680
3780
|
|
|
@@ -3705,6 +3805,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3705
3805
|
const schema = JSON.stringify(node.fields || []);
|
|
3706
3806
|
return `${indent}__plainTypes[${JSON.stringify(node.name)}] = { fields: ${schema} };`;
|
|
3707
3807
|
}
|
|
3808
|
+
case 'TypeAlias': {
|
|
3809
|
+
ensureTypeRuntime(context);
|
|
3810
|
+
return `${indent}__plainTypes[${JSON.stringify(node.name)}] = { alias: ${JSON.stringify(node.target)} };`;
|
|
3811
|
+
}
|
|
3708
3812
|
|
|
3709
3813
|
case 'FunctionDeclaration':
|
|
3710
3814
|
case 'IntentDeclaration': {
|
|
@@ -3721,9 +3825,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3721
3825
|
}
|
|
3722
3826
|
// Destructuring: [a, b] or {x, y}
|
|
3723
3827
|
if (p && (p.type === 'ArrayPattern' || p.type === 'ObjectPattern')) {
|
|
3724
|
-
const pattern = p
|
|
3725
|
-
? `[${p.elements.map(e => generateLValue(e, context)).join(', ')}]`
|
|
3726
|
-
: `{ ${p.properties.map(prop => generateLValue(prop, context)).join(', ')} }`;
|
|
3828
|
+
const pattern = generatePattern(p, context);
|
|
3727
3829
|
if (p.defaultValue) {
|
|
3728
3830
|
return `${pattern} = ${generateExpr(p.defaultValue, context)}`;
|
|
3729
3831
|
}
|
|
@@ -3737,7 +3839,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3737
3839
|
return p;
|
|
3738
3840
|
}).join(', ');
|
|
3739
3841
|
const checks = node.params
|
|
3740
|
-
.filter(p => p && p.typeAnnotation && p.name)
|
|
3842
|
+
.filter(p => p && p.typeAnnotation && p.name && !JSON.stringify(p.typeAnnotation).includes('"kind":"typeParam"'))
|
|
3741
3843
|
.map(p => `${indent} __plainAssertType(${JSON.stringify(p.typeAnnotation)}, ${p.name}, ${JSON.stringify(`${node.name}.${p.name}`)});`)
|
|
3742
3844
|
.join('\n');
|
|
3743
3845
|
if (checks) ensureTypeRuntime(context);
|
|
@@ -4166,7 +4268,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
4166
4268
|
body,
|
|
4167
4269
|
`${indent} break;`,
|
|
4168
4270
|
`${indent} } catch (__plainRetryError) {`,
|
|
4169
|
-
`${indent} if (__plainAttempt >= ${node.attempts})
|
|
4271
|
+
`${indent} if (__plainAttempt >= ${node.attempts}) throw __plainRetryError;`,
|
|
4170
4272
|
`${indent} else await __retrySleep(${Math.round(node.delaySeconds * 1000)});`,
|
|
4171
4273
|
`${indent} }`,
|
|
4172
4274
|
`${indent}}`,
|
|
@@ -4665,6 +4767,24 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
4665
4767
|
}
|
|
4666
4768
|
}
|
|
4667
4769
|
|
|
4770
|
+
function generatePattern(node, context) {
|
|
4771
|
+
if (node.type === 'ArrayPattern') {
|
|
4772
|
+
return `[${(node.elements || []).map(element => {
|
|
4773
|
+
if (!element) return '';
|
|
4774
|
+
if (element.type === 'SpreadElement') return `...${generateLValue(element.argument, context)}`;
|
|
4775
|
+
return generateLValue(element, context);
|
|
4776
|
+
}).join(', ')}]`;
|
|
4777
|
+
}
|
|
4778
|
+
if (node.type === 'ObjectPattern') {
|
|
4779
|
+
return `{ ${(node.properties || []).map(property => {
|
|
4780
|
+
if (property.type === 'SpreadProperty') return `...${generateLValue(property.argument, context)}`;
|
|
4781
|
+
if (!property.value) return property.key;
|
|
4782
|
+
return `${JSON.stringify(property.key)}: ${generateLValue(property.value, context)}`;
|
|
4783
|
+
}).join(', ')} }`;
|
|
4784
|
+
}
|
|
4785
|
+
return generateLValue(node, context);
|
|
4786
|
+
}
|
|
4787
|
+
|
|
4668
4788
|
// Generates a valid JS assignment target (left-hand side of =).
|
|
4669
4789
|
function generateLValue(node, context) {
|
|
4670
4790
|
if (node.type === 'Identifier') return node.name;
|
|
@@ -4675,8 +4795,7 @@ function generateLValue(node, context) {
|
|
|
4675
4795
|
if (node.type === 'NumberedItem') return `${generateExpr(node.collection, context)}[${node.index}]`;
|
|
4676
4796
|
if (node.type === 'LastItem') return `${generateExpr(node.collection, context)}[${generateExpr(node.collection, context)}.length - 1]`;
|
|
4677
4797
|
// Destructuring patterns
|
|
4678
|
-
if (node.type === 'ArrayPattern'
|
|
4679
|
-
if (node.type === 'ObjectPattern') return `{ ${node.properties.map(p => p.key).join(', ')} }`;
|
|
4798
|
+
if (node.type === 'ArrayPattern' || node.type === 'ObjectPattern') return generatePattern(node, context);
|
|
4680
4799
|
throw new Error(`Invalid assignment target "${node.type}".`);
|
|
4681
4800
|
}
|
|
4682
4801
|
|
|
@@ -4988,7 +5107,7 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
4988
5107
|
case 'ConcurrencyExpression': {
|
|
4989
5108
|
markAsync(context);
|
|
4990
5109
|
const rhs = generateExpr(node.items, context);
|
|
4991
|
-
if (node.combo === 'any') return `(await Promise.
|
|
5110
|
+
if (node.combo === 'any') return `(await Promise.any(${rhs}))`;
|
|
4992
5111
|
if (node.combo === 'settled') return `(await Promise.allSettled(${rhs}))`;
|
|
4993
5112
|
return `(await Promise.all(${rhs}))`;
|
|
4994
5113
|
}
|
package/compiler/lexer.js
CHANGED
|
@@ -132,6 +132,8 @@ const TOKEN = {
|
|
|
132
132
|
RBRACKET: 'RBRACKET',
|
|
133
133
|
COMMA: 'COMMA',
|
|
134
134
|
DOT: 'DOT',
|
|
135
|
+
LESS_THAN: 'LESS_THAN',
|
|
136
|
+
GREATER_THAN: 'GREATER_THAN',
|
|
135
137
|
OPTIONAL_CHAIN: 'OPTIONAL_CHAIN', // ?. - optional chaining
|
|
136
138
|
NULLISH_COALESCE: 'NULLISH_COALESCE', // ?? - nullish coalescing
|
|
137
139
|
POWER: 'POWER', // ** - exponentiation
|
|
@@ -152,6 +154,7 @@ const TOKEN = {
|
|
|
152
154
|
PERCENT_ASSIGN: 'PERCENT_ASSIGN', // %=
|
|
153
155
|
// Literals & identifiers
|
|
154
156
|
IDENTIFIER: 'IDENTIFIER',
|
|
157
|
+
ESCAPED_IDENTIFIER: 'ESCAPED_IDENTIFIER', // `now`, `prompt`, `list`, etc.
|
|
155
158
|
STRING: 'STRING',
|
|
156
159
|
NUMBER: 'NUMBER',
|
|
157
160
|
TRUE_KW: 'TRUE_KW', // v2.1.1 - boolean literal true
|
|
@@ -422,7 +425,14 @@ function tokenize(source) {
|
|
|
422
425
|
);
|
|
423
426
|
}
|
|
424
427
|
i++; // skip closing backtick
|
|
425
|
-
|
|
428
|
+
const escapedIdentifier = /^[A-Za-z_][A-Za-z0-9_]*$/.test(content) &&
|
|
429
|
+
Object.prototype.hasOwnProperty.call(KEYWORDS, content);
|
|
430
|
+
tokens.push({
|
|
431
|
+
type: escapedIdentifier ? TOKEN.ESCAPED_IDENTIFIER : TOKEN.TEMPLATE_STRING,
|
|
432
|
+
value: content,
|
|
433
|
+
line: tokenLine,
|
|
434
|
+
col: tokenCol,
|
|
435
|
+
});
|
|
426
436
|
continue;
|
|
427
437
|
}
|
|
428
438
|
|
|
@@ -539,6 +549,8 @@ function tokenize(source) {
|
|
|
539
549
|
if (source[i] === '[') { tokens.push({ type: TOKEN.LBRACKET, value: '[', line: tokenLine, col: tokenCol }); i++; continue; }
|
|
540
550
|
if (source[i] === ']') { tokens.push({ type: TOKEN.RBRACKET, value: ']', line: tokenLine, col: tokenCol }); i++; continue; }
|
|
541
551
|
if (source[i] === ',') { tokens.push({ type: TOKEN.COMMA, value: ',', line: tokenLine, col: tokenCol }); i++; continue; }
|
|
552
|
+
if (source[i] === '<') { tokens.push({ type: TOKEN.LESS_THAN, value: '<', line: tokenLine, col: tokenCol }); i++; continue; }
|
|
553
|
+
if (source[i] === '>') { tokens.push({ type: TOKEN.GREATER_THAN, value: '>', line: tokenLine, col: tokenCol }); i++; continue; }
|
|
542
554
|
if (source[i] === '?' && source[i + 1] === '.') { tokens.push({ type: TOKEN.OPTIONAL_CHAIN, value: '?.', line: tokenLine, col: tokenCol }); i += 2; continue; }
|
|
543
555
|
if (source[i] === '?' && source[i + 1] === '?' && source[i + 2] === '=') { tokens.push({ type: TOKEN.NULLISH_ASSIGN, value: '??=', line: tokenLine, col: tokenCol }); i += 3; continue; }
|
|
544
556
|
if (source[i] === '?' && source[i + 1] === '?') { tokens.push({ type: TOKEN.NULLISH_COALESCE, value: '??', line: tokenLine, col: tokenCol }); i += 2; continue; }
|
package/compiler/lsp.js
CHANGED
|
@@ -35,6 +35,29 @@ function uriPath(uri) {
|
|
|
35
35
|
return uri;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
function offsetAt(text, position) {
|
|
39
|
+
const lines = String(text).split(/\r?\n/);
|
|
40
|
+
const line = Math.max(0, Math.min(position && position.line || 0, lines.length - 1));
|
|
41
|
+
const character = Math.max(0, Math.min(position && position.character || 0, lines[line].length));
|
|
42
|
+
let offset = 0;
|
|
43
|
+
for (let index = 0; index < line; index += 1) offset += lines[index].length + 1;
|
|
44
|
+
return offset + character;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function applyContentChanges(text, changes) {
|
|
48
|
+
let next = text;
|
|
49
|
+
for (const change of changes || []) {
|
|
50
|
+
if (!change.range) {
|
|
51
|
+
next = change.text;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const start = offsetAt(next, change.range.start);
|
|
55
|
+
const end = offsetAt(next, change.range.end);
|
|
56
|
+
next = next.slice(0, start) + change.text + next.slice(end);
|
|
57
|
+
}
|
|
58
|
+
return next;
|
|
59
|
+
}
|
|
60
|
+
|
|
38
61
|
class LspService {
|
|
39
62
|
constructor() {
|
|
40
63
|
this.documents = new Map();
|
|
@@ -202,14 +225,14 @@ class LspService {
|
|
|
202
225
|
switch (method) {
|
|
203
226
|
case 'initialize':
|
|
204
227
|
return { capabilities: {
|
|
205
|
-
textDocumentSync: { openClose: true, change:
|
|
228
|
+
textDocumentSync: { openClose: true, change: 2 },
|
|
206
229
|
hoverProvider: true,
|
|
207
230
|
completionProvider: { triggerCharacters: ['.', ' '] },
|
|
208
231
|
definitionProvider: true,
|
|
209
232
|
referencesProvider: true,
|
|
210
233
|
renameProvider: true,
|
|
211
234
|
signatureHelpProvider: { triggerCharacters: ['(', ','] },
|
|
212
|
-
}, serverInfo: { name: 'plainscript-lsp', version: '
|
|
235
|
+
}, serverInfo: { name: 'plainscript-lsp', version: require('./version').VERSION } };
|
|
213
236
|
case 'shutdown': this.shutdownRequested = true; return null;
|
|
214
237
|
case 'textDocument/hover': return this.hover(params.textDocument.uri, params.position);
|
|
215
238
|
case 'textDocument/completion': return this.completion(params.textDocument.uri);
|
|
@@ -235,9 +258,7 @@ class LspService {
|
|
|
235
258
|
if (method === 'textDocument/didChange') {
|
|
236
259
|
const changes = params.contentChanges || [];
|
|
237
260
|
const current = this.document(params.textDocument.uri);
|
|
238
|
-
const text =
|
|
239
|
-
? changes[0].text
|
|
240
|
-
: (current ? current.text : '');
|
|
261
|
+
const text = applyContentChanges(current ? current.text : '', changes);
|
|
241
262
|
this.setDocument(params.textDocument.uri, text, params.textDocument.version);
|
|
242
263
|
return this.publishDiagnostics(params.textDocument.uri);
|
|
243
264
|
}
|