plainscript-lang 1.1.1 → 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 +63 -8
- package/compiler/bundler.js +29 -2
- package/compiler/cli.js +26 -0
- package/compiler/formatter.js +5 -2
- package/compiler/generator.js +133 -26
- package/compiler/lexer.js +4 -0
- package/compiler/lsp.js +26 -5
- package/compiler/parser.js +39 -4
- package/compiler/type-checker.js +299 -21
- package/compiler/version.js +1 -1
- package/docs/PLAINSCRIPT-GRAMMAR.md +7 -3
- package/docs/V1.1.5-GAP-ANALYSIS.md +79 -0
- package/package.json +16 -3
package/README.md
CHANGED
|
@@ -131,7 +131,7 @@ done
|
|
|
131
131
|
</tr>
|
|
132
132
|
</table>
|
|
133
133
|
|
|
134
|
-
**Current version:** `v1.1.
|
|
134
|
+
**Current version:** `v1.1.5` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
|
|
135
135
|
|
|
136
136
|
---
|
|
137
137
|
|
|
@@ -261,7 +261,7 @@ For projects that need custom output or source directories, add a `plainscript.c
|
|
|
261
261
|
"build": "plainscript build",
|
|
262
262
|
"prepare": "plainscript build"
|
|
263
263
|
},
|
|
264
|
-
"devDependencies": { "plainscript-lang": "^1.1.
|
|
264
|
+
"devDependencies": { "plainscript-lang": "^1.1.5" }
|
|
265
265
|
}
|
|
266
266
|
```
|
|
267
267
|
|
|
@@ -421,7 +421,7 @@ PlainScript supports contextual `type` declarations for records and typed
|
|
|
421
421
|
function parameters. The compiler records the contract in the AST and emitted
|
|
422
422
|
programs validate typed arguments at runtime with clear field-level errors.
|
|
423
423
|
Primitive types are `number`, `text`, `boolean`, `object`, and `null`; contracts
|
|
424
|
-
also support `optional`, `list of`, `dictionary of`, and `or` unions.
|
|
424
|
+
also support `optional`, `list of`, `dictionary of`, `set of`, `map of K to V`, fixed-size `tuple of A, B`, and `or` unions. Named aliases are substituted across assignments, returns, and local imports.
|
|
425
425
|
|
|
426
426
|
```plainscript
|
|
427
427
|
type User
|
|
@@ -448,11 +448,66 @@ let usersById as dictionary of User is { first: { id: 1, name: "Ada" } }
|
|
|
448
448
|
```
|
|
449
449
|
|
|
450
450
|
List elements, dictionary values, and nested record fields are checked
|
|
451
|
-
recursively. Optional and union element types are supported. The
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
451
|
+
recursively. Optional and union element types are supported. The v1.1.5
|
|
452
|
+
checker also propagates known expression results through canonical standard
|
|
453
|
+
library calls and common text/list methods:
|
|
454
|
+
|
|
455
|
+
```plainscript
|
|
456
|
+
make normalized() returns text
|
|
457
|
+
give " Ada ".trim().toLowerCase()
|
|
458
|
+
done
|
|
459
|
+
|
|
460
|
+
make words() returns list of text
|
|
461
|
+
give "ada,grace".split(",")
|
|
462
|
+
done
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
Known math helpers, text conversions, collection operations, and member methods
|
|
466
|
+
now contribute their return types to argument and return-contract checking.
|
|
467
|
+
Unknown JavaScript/npm calls remain `any` rather than being guessed. The static
|
|
468
|
+
checker reports unknown fields, missing required fields, incompatible literal
|
|
469
|
+
values, unknown contract names, arity errors, invalid assignments, unsafe
|
|
470
|
+
optional member access, and invalid member access to editor tooling.
|
|
471
|
+
### Generic functions and aliases
|
|
472
|
+
|
|
473
|
+
Generic function parameters use angle brackets. The checker infers a concrete
|
|
474
|
+
type from each call and validates the result; generic parameters are erased
|
|
475
|
+
from runtime assertions because JavaScript cannot observe them directly.
|
|
476
|
+
|
|
477
|
+
```plainscript
|
|
478
|
+
type UserId is number
|
|
479
|
+
|
|
480
|
+
make id<T>(value as T) returns T
|
|
481
|
+
give value
|
|
482
|
+
done
|
|
483
|
+
|
|
484
|
+
let userId as UserId is id(42)
|
|
485
|
+
show userId
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
Aliases are checked wherever the aliased type is used, including across local
|
|
489
|
+
imports. Runtime checks still validate the underlying concrete type.
|
|
490
|
+
|
|
491
|
+
The checker narrows nullable values after guards such as `if value is not null`
|
|
492
|
+
and `if value is null`; optional member access remains available when a value
|
|
493
|
+
has not been narrowed. Structural pattern exhaustiveness is not yet enforced.
|
|
494
|
+
|
|
495
|
+
### Cancellation and disposal
|
|
496
|
+
|
|
497
|
+
The standard library provides explicit cancellation tokens and deterministic
|
|
498
|
+
cleanup helpers:
|
|
499
|
+
|
|
500
|
+
```plainscript
|
|
501
|
+
let token is cancellationToken()
|
|
502
|
+
remember ignored as cancel(token)
|
|
503
|
+
if isCancelled(token)
|
|
504
|
+
show "cancelled"
|
|
505
|
+
done
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
`dispose(resource)` can be used by a `using` scope to clean up resources. These
|
|
509
|
+
semantics are cooperative: an operation must inspect its token or call a
|
|
510
|
+
standard-library operation that accepts one.
|
|
456
511
|
|
|
457
512
|
### Language-server tooling
|
|
458
513
|
|
package/compiler/bundler.js
CHANGED
|
@@ -128,6 +128,32 @@ function getExportNames(ast) {
|
|
|
128
128
|
return names;
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
+
function getModuleSurface(ast) {
|
|
132
|
+
const explicit = getExportNames(ast);
|
|
133
|
+
if (ast.body.some(node => node.type === 'ExportStatement')) return new Set(explicit);
|
|
134
|
+
return new Set(ast.body
|
|
135
|
+
.filter(node => ['FunctionDeclaration', 'IntentDeclaration', 'TypeDeclaration', 'TypeAlias'].includes(node.type) && node.name)
|
|
136
|
+
.map(node => node.name));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function validateImportSurfaces(files) {
|
|
140
|
+
const astByAbs = new Map(files.map(file => [file.absPath, file.ast]));
|
|
141
|
+
for (const { absPath, ast } of files) {
|
|
142
|
+
for (const node of ast.body) {
|
|
143
|
+
if (node.type !== 'ImportStatement' || !node.path || !isLocalImportPath(node.path) || node.namespace) continue;
|
|
144
|
+
const dependency = astByAbs.get(resolveImportPath(path.dirname(absPath), node.path));
|
|
145
|
+
if (!dependency) continue;
|
|
146
|
+
const surface = getModuleSurface(dependency);
|
|
147
|
+
const imported = node.namedImports || (node.names || []).map(name => ({ imported: name, local: name }));
|
|
148
|
+
for (const item of imported) {
|
|
149
|
+
if (!surface.has(item.imported)) {
|
|
150
|
+
throw new Error(`Module "${node.path}" does not export "${item.imported}".\n\nExport it from the module or remove it from the import.`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
131
157
|
// Builds the export surface map for a resolved dependency graph:
|
|
132
158
|
// local import path (as written) -> exported names of that module. Used by
|
|
133
159
|
// namespace imports ("bring all from X as ns") which need the export surface
|
|
@@ -146,7 +172,7 @@ function buildSurfaces(files) {
|
|
|
146
172
|
// Union of explicit exports plus auto-exported function declarations
|
|
147
173
|
const explicit = getExportNames(depAst);
|
|
148
174
|
const funcs = depAst.body
|
|
149
|
-
.filter(n =>
|
|
175
|
+
.filter(n => ['FunctionDeclaration', 'IntentDeclaration', 'TypeDeclaration', 'TypeAlias'].includes(n.type) && n.name)
|
|
150
176
|
.map(n => n.name);
|
|
151
177
|
const hasExplicit = depAst.body.some(n => n.type === 'ExportStatement');
|
|
152
178
|
const surface = hasExplicit ? explicit : [...new Set([...explicit, ...funcs])];
|
|
@@ -186,6 +212,7 @@ function buildSurfaces(files) {
|
|
|
186
212
|
// bundled programs behave identically no matter which command produced them.
|
|
187
213
|
function generateBundle(entryPath, options = {}) {
|
|
188
214
|
const files = resolveDependencies(entryPath);
|
|
215
|
+
validateImportSurfaces(files);
|
|
189
216
|
const context = createGenerationContext(options);
|
|
190
217
|
context.bundled = true;
|
|
191
218
|
context.importSurfaces = buildSurfaces(files);
|
|
@@ -229,4 +256,4 @@ function bundle(entryPath, options = {}) {
|
|
|
229
256
|
return js;
|
|
230
257
|
}
|
|
231
258
|
|
|
232
|
-
module.exports = { bundle, generateBundle, buildSurfaces, resolveDependencies };
|
|
259
|
+
module.exports = { bundle, generateBundle, buildSurfaces, resolveDependencies, validateImportSurfaces };
|
package/compiler/cli.js
CHANGED
|
@@ -401,6 +401,7 @@ function compile(filePath, options = {}) {
|
|
|
401
401
|
stage('Resolving imports', () => {
|
|
402
402
|
files = resolveDependencies(absPath);
|
|
403
403
|
});
|
|
404
|
+
stage('Checking module graph', () => checkResolvedGraph(files));
|
|
404
405
|
stage('Building dependency graph', () => files);
|
|
405
406
|
stage('Checking runtime dependencies', () => ensureDependencies(files, true));
|
|
406
407
|
// Shared bundle pipeline: one context across the whole dependency graph so
|
|
@@ -494,6 +495,31 @@ function compile(filePath, options = {}) {
|
|
|
494
495
|
return js;
|
|
495
496
|
}
|
|
496
497
|
|
|
498
|
+
function checkResolvedGraph(files) {
|
|
499
|
+
const declarations = new Map();
|
|
500
|
+
for (const file of files) {
|
|
501
|
+
const sourceFile = path.relative(process.cwd(), file.absPath) || file.absPath;
|
|
502
|
+
for (const node of file.ast.body || []) {
|
|
503
|
+
if (!node.name || !['RememberStatement', 'FunctionDeclaration', 'IntentDeclaration', 'TypeDeclaration', 'TypeAlias'].includes(node.type)) continue;
|
|
504
|
+
const owners = declarations.get(node.name) || [];
|
|
505
|
+
owners.push(sourceFile);
|
|
506
|
+
declarations.set(node.name, owners);
|
|
507
|
+
node.sourceFile = sourceFile;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
const collisions = [...declarations.entries()].filter(([, owners]) => new Set(owners).size > 1);
|
|
511
|
+
if (collisions.length) {
|
|
512
|
+
throw new Error(`Module graph contains colliding top-level declarations:\n${collisions.map(([name, owners]) => ` ${name}: ${owners.join(', ')}`).join('\n')}\n\nRename the declarations or import them through an isolated module boundary.`);
|
|
513
|
+
}
|
|
514
|
+
const result = checkTypes({ type: 'Program', body: files.flatMap(file => file.ast.body || []) });
|
|
515
|
+
if (result.diagnostics.length) {
|
|
516
|
+
const details = result.diagnostics.map(item =>
|
|
517
|
+
`${item.file || '<source>'}:${item.range.start.line + 1}:${item.range.start.character + 1} ${item.code} ${item.message}`
|
|
518
|
+
).join('\n');
|
|
519
|
+
throw new Error(`Static type checking failed:\n${details}`);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
497
523
|
// ── Commands ─────────────────────────────────────────────────────────────────
|
|
498
524
|
|
|
499
525
|
// Node resolves require(...) against the temp file's location, so a scratch
|
package/compiler/formatter.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
const INDENT = ' '; // 4 spaces
|
|
11
11
|
|
|
12
12
|
// Keywords whose line CLOSES a block (printed at depth - 1).
|
|
13
|
-
const DEDENT_WORDS = new Set(['done', 'end', 'otherwise', 'recover']);
|
|
13
|
+
const DEDENT_WORDS = new Set(['done', 'end', 'otherwise', 'else', 'recover', 'finally']);
|
|
14
14
|
|
|
15
15
|
// Patterns whose line OPENS a new block (next line indented).
|
|
16
16
|
const INDENT_STARTERS = [
|
|
@@ -18,6 +18,7 @@ const INDENT_STARTERS = [
|
|
|
18
18
|
/^to\s+\S+/, // to add a and b together ...
|
|
19
19
|
/^if\s+/, // if ...
|
|
20
20
|
/^otherwise\b/, // otherwise
|
|
21
|
+
/^else\b/, // else
|
|
21
22
|
/^for\s+each\s+/, // for each ...
|
|
22
23
|
/^for\s+every\s+/, // for every ... in ...
|
|
23
24
|
/^for\s+index\s+/, // for index i from ... to ...
|
|
@@ -40,6 +41,7 @@ const INDENT_STARTERS = [
|
|
|
40
41
|
/^transaction\s*$/, // transaction (v2.1 atomic DB block)
|
|
41
42
|
/^try\s*$/, // try (v2.1.1 error handling)
|
|
42
43
|
/^recover\b/, // recover [as name] (v2.1.1 error handling)
|
|
44
|
+
/^finally\s*$/, // finally (v2.1.1 error handling)
|
|
43
45
|
/^retry\s+\d+\s+times\b/, // retry N times ... (v2.1.1 retries)
|
|
44
46
|
/^every\s+\d+\s+(seconds?|minutes?|hours?|days?)\b/, // every 5 minutes (v2.1)
|
|
45
47
|
/^every\s+N\s+(seconds?|minutes?|hours?|days?)\b/, // every N seconds (variable)
|
|
@@ -148,7 +150,8 @@ function format(source) {
|
|
|
148
150
|
// (e.g. make, if, for each) when prior content exists.
|
|
149
151
|
// Simple statements like remember/show/becomes are NOT block openers and
|
|
150
152
|
// do NOT get a blank line inserted before them.
|
|
151
|
-
|
|
153
|
+
const isContinuation = ['else', 'finally', 'otherwise'].includes(firstWord);
|
|
154
|
+
if (depth === 0 && opensBlock(content) && !isContinuation && output.length > 0) {
|
|
152
155
|
let lastNonEmpty = output.length - 1;
|
|
153
156
|
while (lastNonEmpty >= 0 && output[lastNonEmpty] === '') lastNonEmpty--;
|
|
154
157
|
|
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}`;',
|
|
@@ -3460,9 +3552,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3460
3552
|
case 'RememberStatement': {
|
|
3461
3553
|
// Handle destructuring: remember [a, b] as arr / remember {x, y} as obj
|
|
3462
3554
|
if (node.name && typeof node.name === 'object' && (node.name.type === 'ArrayPattern' || node.name.type === 'ObjectPattern')) {
|
|
3463
|
-
const pattern = node.name
|
|
3464
|
-
? `[${node.name.elements.map(e => generateLValue(e, context)).join(', ')}]`
|
|
3465
|
-
: `{ ${node.name.properties.map(p => p.key).join(', ')} }`;
|
|
3555
|
+
const pattern = generatePattern(node.name, context);
|
|
3466
3556
|
return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
|
|
3467
3557
|
}
|
|
3468
3558
|
// v1.0.363 - uninitialized declaration ("let undef") binds undefined.
|
|
@@ -3481,9 +3571,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3481
3571
|
case 'BecomeStatement': {
|
|
3482
3572
|
// Handle destructuring: [a, b] = arr / {x, y} = obj
|
|
3483
3573
|
if (node.target && typeof node.target === 'object' && (node.target.type === 'ArrayPattern' || node.target.type === 'ObjectPattern')) {
|
|
3484
|
-
const pattern = node.target
|
|
3485
|
-
? `[${node.target.elements.map(e => generateLValue(e, context)).join(', ')}]`
|
|
3486
|
-
: `{ ${node.target.properties.map(p => generateLValue(p, context)).join(', ')} }`;
|
|
3574
|
+
const pattern = generatePattern(node.target, context);
|
|
3487
3575
|
return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
|
|
3488
3576
|
}
|
|
3489
3577
|
const target = generateLValue(node.target, context);
|
|
@@ -3717,6 +3805,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3717
3805
|
const schema = JSON.stringify(node.fields || []);
|
|
3718
3806
|
return `${indent}__plainTypes[${JSON.stringify(node.name)}] = { fields: ${schema} };`;
|
|
3719
3807
|
}
|
|
3808
|
+
case 'TypeAlias': {
|
|
3809
|
+
ensureTypeRuntime(context);
|
|
3810
|
+
return `${indent}__plainTypes[${JSON.stringify(node.name)}] = { alias: ${JSON.stringify(node.target)} };`;
|
|
3811
|
+
}
|
|
3720
3812
|
|
|
3721
3813
|
case 'FunctionDeclaration':
|
|
3722
3814
|
case 'IntentDeclaration': {
|
|
@@ -3733,9 +3825,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3733
3825
|
}
|
|
3734
3826
|
// Destructuring: [a, b] or {x, y}
|
|
3735
3827
|
if (p && (p.type === 'ArrayPattern' || p.type === 'ObjectPattern')) {
|
|
3736
|
-
const pattern = p
|
|
3737
|
-
? `[${p.elements.map(e => generateLValue(e, context)).join(', ')}]`
|
|
3738
|
-
: `{ ${p.properties.map(prop => generateLValue(prop, context)).join(', ')} }`;
|
|
3828
|
+
const pattern = generatePattern(p, context);
|
|
3739
3829
|
if (p.defaultValue) {
|
|
3740
3830
|
return `${pattern} = ${generateExpr(p.defaultValue, context)}`;
|
|
3741
3831
|
}
|
|
@@ -3749,7 +3839,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3749
3839
|
return p;
|
|
3750
3840
|
}).join(', ');
|
|
3751
3841
|
const checks = node.params
|
|
3752
|
-
.filter(p => p && p.typeAnnotation && p.name)
|
|
3842
|
+
.filter(p => p && p.typeAnnotation && p.name && !JSON.stringify(p.typeAnnotation).includes('"kind":"typeParam"'))
|
|
3753
3843
|
.map(p => `${indent} __plainAssertType(${JSON.stringify(p.typeAnnotation)}, ${p.name}, ${JSON.stringify(`${node.name}.${p.name}`)});`)
|
|
3754
3844
|
.join('\n');
|
|
3755
3845
|
if (checks) ensureTypeRuntime(context);
|
|
@@ -4178,7 +4268,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
4178
4268
|
body,
|
|
4179
4269
|
`${indent} break;`,
|
|
4180
4270
|
`${indent} } catch (__plainRetryError) {`,
|
|
4181
|
-
`${indent} if (__plainAttempt >= ${node.attempts})
|
|
4271
|
+
`${indent} if (__plainAttempt >= ${node.attempts}) throw __plainRetryError;`,
|
|
4182
4272
|
`${indent} else await __retrySleep(${Math.round(node.delaySeconds * 1000)});`,
|
|
4183
4273
|
`${indent} }`,
|
|
4184
4274
|
`${indent}}`,
|
|
@@ -4677,6 +4767,24 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
4677
4767
|
}
|
|
4678
4768
|
}
|
|
4679
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
|
+
|
|
4680
4788
|
// Generates a valid JS assignment target (left-hand side of =).
|
|
4681
4789
|
function generateLValue(node, context) {
|
|
4682
4790
|
if (node.type === 'Identifier') return node.name;
|
|
@@ -4687,8 +4795,7 @@ function generateLValue(node, context) {
|
|
|
4687
4795
|
if (node.type === 'NumberedItem') return `${generateExpr(node.collection, context)}[${node.index}]`;
|
|
4688
4796
|
if (node.type === 'LastItem') return `${generateExpr(node.collection, context)}[${generateExpr(node.collection, context)}.length - 1]`;
|
|
4689
4797
|
// Destructuring patterns
|
|
4690
|
-
if (node.type === 'ArrayPattern'
|
|
4691
|
-
if (node.type === 'ObjectPattern') return `{ ${node.properties.map(p => p.key).join(', ')} }`;
|
|
4798
|
+
if (node.type === 'ArrayPattern' || node.type === 'ObjectPattern') return generatePattern(node, context);
|
|
4692
4799
|
throw new Error(`Invalid assignment target "${node.type}".`);
|
|
4693
4800
|
}
|
|
4694
4801
|
|
|
@@ -5000,7 +5107,7 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
5000
5107
|
case 'ConcurrencyExpression': {
|
|
5001
5108
|
markAsync(context);
|
|
5002
5109
|
const rhs = generateExpr(node.items, context);
|
|
5003
|
-
if (node.combo === 'any') return `(await Promise.
|
|
5110
|
+
if (node.combo === 'any') return `(await Promise.any(${rhs}))`;
|
|
5004
5111
|
if (node.combo === 'settled') return `(await Promise.allSettled(${rhs}))`;
|
|
5005
5112
|
return `(await Promise.all(${rhs}))`;
|
|
5006
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
|
|
@@ -547,6 +549,8 @@ function tokenize(source) {
|
|
|
547
549
|
if (source[i] === '[') { tokens.push({ type: TOKEN.LBRACKET, value: '[', line: tokenLine, col: tokenCol }); i++; continue; }
|
|
548
550
|
if (source[i] === ']') { tokens.push({ type: TOKEN.RBRACKET, value: ']', line: tokenLine, col: tokenCol }); i++; continue; }
|
|
549
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; }
|
|
550
554
|
if (source[i] === '?' && source[i + 1] === '.') { tokens.push({ type: TOKEN.OPTIONAL_CHAIN, value: '?.', line: tokenLine, col: tokenCol }); i += 2; continue; }
|
|
551
555
|
if (source[i] === '?' && source[i + 1] === '?' && source[i + 2] === '=') { tokens.push({ type: TOKEN.NULLISH_ASSIGN, value: '??=', line: tokenLine, col: tokenCol }); i += 3; continue; }
|
|
552
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
|
}
|