plainscript-lang 1.0.363 → 1.1.1

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 CHANGED
@@ -131,7 +131,7 @@ done
131
131
  </tr>
132
132
  </table>
133
133
 
134
- **Current version:** `v1.0.363` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
134
+ **Current version:** `v1.1.1` - 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
 
@@ -200,7 +200,7 @@ socket export plus `useMultiFileAuthState`, `makeCacheableSignalKeyStore`, and
200
200
  | `plainscript ir <file.pln>` | Emits the stable, backend-neutral compiler IR as JSON for tooling and diagnostics. |
201
201
  | `plainscript-lsp` | Runs the stdio Language Server Protocol service for editor diagnostics, hover, completion, definitions, and symbols. |
202
202
  | `plainscript build [file.pln]` | Compiles to `dist/`. With no argument, builds every `.pln` file under the source root, preserving names and folder structure. |
203
- | `plainscript check <file.pln>` | Checks syntax and dependencies only. Reports a per-file `✓` line (or an error). Never executes your program. |
203
+ | `plainscript check <file.pln>` | Resolves imports, runs static contract/type checking, validates generated JavaScript, and reports a per-file `✓` line (or an error). Never executes your program. |
204
204
  | `plainscript fmt <file.pln>` | Formats a PlainScript file in place. |
205
205
  | `plainscript new [name]` | Creates a new PlainScript project, npm-ready. |
206
206
  | `plainscript install` | Installs dependencies detected across the project's sources. |
@@ -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.0.363" }
264
+ "devDependencies": { "plainscript-lang": "^1.1.1" }
265
265
  }
266
266
  ```
267
267
 
@@ -365,9 +365,11 @@ All comparison operators:
365
365
  | `is not` | `!==` |
366
366
  | `different from` | `!==` |
367
367
  | `is greater than` / `is above` | `>` |
368
- | `more than` | `>` |
368
+ | `more than` / `is more than` | `>` |
369
369
  | `is less than` / `is below` | `<` |
370
- | `fewer than` | `<` |
370
+ | `fewer than` / `is fewer than` | `<` |
371
+ | `greater than or equal to` / `is more than or equal to` | `>=` |
372
+ | `less than or equal to` | `<=` |
371
373
  | `is at least` | `>=` |
372
374
  | `is at most` | `<=` |
373
375
  | `is empty` | `.length === 0` |
@@ -436,10 +438,21 @@ show greet({ id: 1, name: "Ada" })
436
438
  ```
437
439
 
438
440
  Missing required fields and incompatible values fail before the function body
439
- runs. The static checker now reports unknown fields, missing required fields,
440
- incompatible literal values, unknown contract names, arity errors, and invalid
441
- member access to editor tooling. Whole-program inference and exhaustiveness
442
- checking remain future work.
441
+ runs. Functions and intents can declare return contracts with `returns` or
442
+ `returning`; the checker validates returned values and reports missing returns.
443
+ Collection contracts can be used on mutable bindings:
444
+
445
+ ```text
446
+ let users as list of User is [{ id: 1, name: "Ada" }]
447
+ let usersById as dictionary of User is { first: { id: 1, name: "Ada" } }
448
+ ```
449
+
450
+ List elements, dictionary values, and nested record fields are checked
451
+ recursively. Optional and union element types are supported. The static checker
452
+ reports unknown fields, missing required fields, incompatible literal values,
453
+ unknown contract names, arity errors, invalid assignments, unsafe optional
454
+ member access, and invalid member access to editor tooling. Whole-program
455
+ inference and exhaustiveness checking remain future work.
443
456
 
444
457
  ### Language-server tooling
445
458
 
@@ -450,9 +463,10 @@ plainscript-lsp
450
463
  ```
451
464
 
452
465
  The server implements `initialize`, document open/change/close notifications,
453
- `textDocument/publishDiagnostics`, hover, completion, definition, and document
454
- symbol requests. Editors should launch it as a standard LSP process and send
455
- JSON-RPC messages using the normal `Content-Length` framing.
466
+ `textDocument/publishDiagnostics`, type-rich hover, completion, definition,
467
+ references, rename, signature help, and document-symbol requests. Editors
468
+ should launch it as a standard LSP process and send JSON-RPC messages using the
469
+ normal `Content-Length` framing.
456
470
 
457
471
  ### Intent declarations
458
472
 
@@ -758,7 +772,7 @@ PlainScript 1.0.2 closes most of the gap with TypeScript-class languages using i
758
772
  | Streams | `writeLine`, `appendLine` |
759
773
  | Collections | `keyMap/mapSet/mapGet/mapHas/mapDelete`, `newSet/addToSet` |
760
774
  | Dynamic modules | `loadModule("./m")` |
761
- | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check <expr> raises "msg"`; run files with `plainscript test` |
775
+ | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check object has field "name"`, and `check <expr> raises "msg"`; run files with `plainscript test` |
762
776
  | Exports | `export <name>` |
763
777
 
764
778
  </details>
@@ -813,7 +827,7 @@ Portable databases (SQLite native or WebAssembly):
813
827
  database "app.db" // probes better-sqlite3, falls back to sql.js
814
828
  ```
815
829
 
816
- `plainscript install` verifies that `better-sqlite3` actually loads. Since 1.0.363 the native engine ships as an **optional dependency**: installing `plainscript-lang` can never fail because a native binary is missing for the platform (e.g. Android/Termux), and programs that never open a database start without it. If the native module cannot be used, PlainScript warns and continues on the pure-JavaScript WebAssembly engine (`sql.js`) - the same program runs unchanged. An engine can be forced explicitly:
830
+ `plainscript install` verifies that `better-sqlite3` actually loads. The native engine ships as an **optional dependency**: installing `plainscript-lang` can never fail because a native binary is missing for the platform (e.g. Android/Termux), and programs that never open a database start without it. If the native module cannot be used, PlainScript warns and continues on the pure-JavaScript WebAssembly engine (`sql.js`) - the same program runs unchanged. An engine can be forced explicitly:
817
831
 
818
832
  ```plainscript
819
833
  database "app.db" using "native" // hard requirement: better-sqlite3
@@ -822,6 +836,28 @@ database "app.db" using "wasm" // hard requirement: sql.js
822
836
 
823
837
  The WebAssembly engine persists the whole database to disk after every write, so data survives restarts either way.
824
838
 
839
+ SQL blocks use bound PlainScript value placeholders. `{name}` or
840
+ `{imageHash(image)}` becomes a prepared statement parameter; the resulting value
841
+ is never concatenated into SQL text:
842
+
843
+ ```plainscript
844
+ remember email as request.body.email
845
+ remember rows as query
846
+ SELECT receipt_id FROM receipts WHERE email = {email}
847
+ done
848
+ ```
849
+
850
+ Placeholders are parsed as PlainScript expressions, while raw statement text or
851
+ malformed expressions are rejected at compile time. For complex expressions,
852
+ bind the expression first:
853
+
854
+ ```plainscript
855
+ remember receiptHash as imageHash(image)
856
+ remember rows as query
857
+ SELECT receipt_id FROM receipts WHERE hash = {receiptHash}
858
+ done
859
+ ```
860
+
825
861
  ### HTTP Client
826
862
 
827
863
  ```plainscript
@@ -1347,6 +1383,21 @@ export circleArea
1347
1383
 
1348
1384
  Imports are bundled per entry: `plainscript build` gives every source file its own standalone output under `dist/`, with imported code inlined. Functions, lambdas, records, and modules together are how you build your own vocabulary on top of the core verbs - a new reader puzzle (`validate(body, fields)`) is a one-line call, not a loop.
1349
1385
 
1386
+ ### npm and JavaScript imports
1387
+
1388
+ Named package exports may be given an explicit PlainScript local name:
1389
+
1390
+ ```plainscript
1391
+ import { createHash as hash, randomUUID } from "crypto"
1392
+ show hash
1393
+ ```
1394
+
1395
+ The compiler emits a CommonJS `require` followed by destructuring, so
1396
+ `createHash as hash` becomes the JavaScript binding `{ createHash: hash }`.
1397
+ Unaliased named imports retain their exported name. The same brace syntax is
1398
+ accepted for local PlainScript modules; aliased names become local bindings in
1399
+ the bundled output.
1400
+
1350
1401
  ---
1351
1402
 
1352
1403
  ## Express Integration
package/compiler/cli.js CHANGED
@@ -1000,6 +1000,16 @@ function cmdUpdate() {
1000
1000
  // file in dependency order, and verify the emitted JavaScript is syntactically
1001
1001
  // valid - all without writing anything to disk. Returns a deterministic
1002
1002
  // result record; `deps` are the npm packages the sources require.
1003
+ function annotateSourceTree(node, sourceFile, seen = new Set()) {
1004
+ if (!node || typeof node !== 'object' || seen.has(node)) return;
1005
+ seen.add(node);
1006
+ if (node.type) node.sourceFile = sourceFile;
1007
+ for (const value of Object.values(node)) {
1008
+ if (Array.isArray(value)) value.forEach(item => annotateSourceTree(item, sourceFile, seen));
1009
+ else if (value && typeof value === 'object') annotateSourceTree(value, sourceFile, seen);
1010
+ }
1011
+ }
1012
+
1003
1013
  function validateSource(absPath) {
1004
1014
  const rel = path.relative(process.cwd(), absPath) || absPath;
1005
1015
  const t0 = Date.now();
@@ -1007,11 +1017,16 @@ function validateSource(absPath) {
1007
1017
  // resolveDependencies parses each file too, so a parse error anywhere in
1008
1018
  // the import graph surfaces here with a "file.pln - Line:Col" prefix.
1009
1019
  const { context, parts, files } = generateBundle(absPath);
1010
- const typedAst = { type: 'Program', body: files.flatMap(file => file.ast ? file.ast.body : []) };
1020
+ const typedBodies = files.map(file => {
1021
+ const relFile = path.relative(process.cwd(), file.absPath) || file.absPath;
1022
+ annotateSourceTree(file.ast, relFile);
1023
+ return file.ast ? file.ast.body : [];
1024
+ });
1025
+ const typedAst = { type: 'Program', body: typedBodies.flat() };
1011
1026
  const typeResult = checkTypes(typedAst);
1012
1027
  if (typeResult.diagnostics.length > 0) {
1013
1028
  const details = typeResult.diagnostics.map(item =>
1014
- `${rel}:${item.range.start.line + 1}:${item.range.start.character + 1} ${item.code} ${item.message}`
1029
+ `${item.file || rel}:${item.range.start.line + 1}:${item.range.start.character + 1} ${item.code} ${item.message}`
1015
1030
  ).join('\n');
1016
1031
  throw new Error(`Static type checking failed:\n${details}`);
1017
1032
  }
@@ -3298,7 +3298,9 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3298
3298
  const runner = [
3299
3299
  `const __tests = [];`,
3300
3300
  `function __check(op, a, b) {`,
3301
- ` const ok = op === 'contains'`,
3301
+ ` const ok = op === 'has-field'`,
3302
+ ` ? a != null && Object.prototype.hasOwnProperty.call(Object(a), b)`,
3303
+ ` : op === 'contains'`,
3302
3304
  ` ? (a instanceof Set ? a.has(b) : String(a).includes(String(b)))`,
3303
3305
  ` : op === 'is'`,
3304
3306
  ` ? a === b`,
@@ -3555,6 +3557,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3555
3557
  }
3556
3558
 
3557
3559
  // v1.0.1 - assertion `check <a> (equals|is|contains|raises) <b>`.
3560
+ // v1.1.1 - `check <object> has field "name"` checks JSON/object shape.
3558
3561
  // For `raises`, `a` is wrapped in a thunk so the expression is evaluated
3559
3562
  // inside the runner's try/catch (its thrown error is the subject).
3560
3563
  case 'CheckStatement': {
@@ -3653,9 +3656,12 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3653
3656
  }
3654
3657
  if (node.names && node.names.length > 0) {
3655
3658
  const reqName = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
3656
- emitRequire(context, node.path, `__pkg_${reqName}`);
3657
- const destructuring = `const { ${node.names.join(', ')} } = __pkg_${reqName};`;
3658
- return `${indent}${destructuring}`;
3659
+ const requireLine = emitRequire(context, node.path, `__pkg_${reqName}`);
3660
+ const bindings = (node.namedImports && node.namedImports.length > 0)
3661
+ ? node.namedImports.map(({ imported, local }) => imported === local ? imported : `${imported}: ${local}`)
3662
+ : node.names;
3663
+ const destructuring = `const { ${bindings.join(', ')} } = __pkg_${reqName};`;
3664
+ return [requireLine, `${indent}${destructuring}`].filter(Boolean).join('\n');
3659
3665
  }
3660
3666
  const pkg = emitRequire(context, node.path, null);
3661
3667
  return pkg ? `${indent}${pkg}` : '';
@@ -3674,7 +3680,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3674
3680
  }
3675
3681
  const modVar = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
3676
3682
  return `${indent}const ${node.namespace} = typeof __module_${modVar} !== 'undefined' ? __module_${modVar} : require(${JSON.stringify(node.path)});`;
3677
- }
3683
+ }
3684
+ if (node.namedImports && node.namedImports.some(({ imported, local }) => imported !== local)) {
3685
+ return node.namedImports
3686
+ .filter(({ imported, local }) => imported !== local)
3687
+ .map(({ imported, local }) => `${indent}const ${local} = ${imported};`)
3688
+ .join('\n');
3689
+ }
3678
3690
  return '';
3679
3691
  }
3680
3692
 
package/compiler/ir.js CHANGED
@@ -34,6 +34,7 @@ function lowerDeclaration(node) {
34
34
  parameters: lowerValue(node.params || []),
35
35
  body: lowerValue(node.body || []),
36
36
  };
37
+ if (node.returnType) out.returnType = lowerValue(node.returnType);
37
38
  if (node.type === 'IntentDeclaration') {
38
39
  out.intent = lowerValue(node.intent || { kind: 'declaration', name: node.name });
39
40
  }
package/compiler/lexer.js CHANGED
@@ -152,6 +152,7 @@ const TOKEN = {
152
152
  PERCENT_ASSIGN: 'PERCENT_ASSIGN', // %=
153
153
  // Literals & identifiers
154
154
  IDENTIFIER: 'IDENTIFIER',
155
+ ESCAPED_IDENTIFIER: 'ESCAPED_IDENTIFIER', // `now`, `prompt`, `list`, etc.
155
156
  STRING: 'STRING',
156
157
  NUMBER: 'NUMBER',
157
158
  TRUE_KW: 'TRUE_KW', // v2.1.1 - boolean literal true
@@ -422,7 +423,14 @@ function tokenize(source) {
422
423
  );
423
424
  }
424
425
  i++; // skip closing backtick
425
- tokens.push({ type: TOKEN.TEMPLATE_STRING, value: content, line: tokenLine, col: tokenCol });
426
+ const escapedIdentifier = /^[A-Za-z_][A-Za-z0-9_]*$/.test(content) &&
427
+ Object.prototype.hasOwnProperty.call(KEYWORDS, content);
428
+ tokens.push({
429
+ type: escapedIdentifier ? TOKEN.ESCAPED_IDENTIFIER : TOKEN.TEMPLATE_STRING,
430
+ value: content,
431
+ line: tokenLine,
432
+ col: tokenCol,
433
+ });
426
434
  continue;
427
435
  }
428
436
 
package/compiler/lsp.js CHANGED
@@ -7,7 +7,7 @@ const fs = require('fs');
7
7
  const { tokenize } = require('./lexer');
8
8
  const { parse } = require('./parser');
9
9
  const { lowerToIR } = require('./ir');
10
- const { checkTypes } = require('./type-checker');
10
+ const { checkTypes, typeName } = require('./type-checker');
11
11
 
12
12
  function parsePosition(message) {
13
13
  const match = /Line (\d+), Column (\d+)/.exec(String(message));
@@ -108,20 +108,21 @@ class LspService {
108
108
  const type = (result.ast.body || []).find(node => node.type === 'TypeDeclaration' && node.name === hit.word);
109
109
  const fn = (result.ast.body || []).find(node => (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') && node.name === hit.word);
110
110
  if (type) {
111
- const fields = (type.fields || []).map(field => `- ${field.key}: ${JSON.stringify(field.type)}`).join('\n');
111
+ const fields = (type.fields || []).map(field => `- ${field.key}: ${typeName(field.type)}`).join('\n');
112
112
  return { contents: { kind: 'markdown', value: `**type ${type.name}**\n\n${fields}` } };
113
113
  }
114
114
  if (fn) {
115
- const params = (fn.params || []).map(param => `${param.name}${param.typeAnnotation ? ` as ${JSON.stringify(param.typeAnnotation)}` : ''}`).join(', ');
115
+ const params = (fn.params || []).map(param => `${param.name}${param.typeAnnotation ? ` as ${typeName(param.typeAnnotation)}` : ''}`).join(', ');
116
116
  const prefix = fn.type === 'IntentDeclaration' ? 'intend' : 'make';
117
- return { contents: { kind: 'markdown', value: `${prefix} ${fn.name}(${params})` } };
117
+ const returns = fn.returnType ? ` returns ${typeName(fn.returnType)}` : '';
118
+ return { contents: { kind: 'markdown', value: `**${prefix} ${fn.name}(${params})${returns}**` } };
118
119
  }
119
120
  return null;
120
121
  }
121
122
 
122
123
  completion(uri) {
123
124
  const result = this.analyze(uri);
124
- const labels = ['remember', 'show', 'make', 'intend', 'type', 'if', 'otherwise', 'for', 'while', 'done', 'give', 'match', 'test'];
125
+ const labels = ['remember', 'show', 'make', 'intend', 'type', 'if', 'otherwise', 'for', 'while', 'done', 'give', 'match', 'test', 'list', 'dictionary', 'optional', 'returns'];
125
126
  if (result.ast) {
126
127
  for (const node of result.ast.body) {
127
128
  if (node.name) labels.push(node.name);
@@ -148,6 +149,55 @@ class LspService {
148
149
  }];
149
150
  }
150
151
 
152
+ references(uri, position) {
153
+ const document = this.document(uri);
154
+ if (!document) return [];
155
+ const hit = wordAt(document.text, position);
156
+ if (!hit) return [];
157
+ const escaped = hit.word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
158
+ const pattern = new RegExp(`\\b${escaped}\\b`, 'g');
159
+ const locations = [];
160
+ document.text.split(/\r?\n/).forEach((line, lineIndex) => {
161
+ let match;
162
+ while ((match = pattern.exec(line))) {
163
+ locations.push({ uri, range: {
164
+ start: { line: lineIndex, character: match.index },
165
+ end: { line: lineIndex, character: match.index + hit.word.length },
166
+ }});
167
+ }
168
+ });
169
+ return locations;
170
+ }
171
+
172
+ rename(uri, position, newName) {
173
+ if (!newName || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(newName)) return null;
174
+ const references = this.references(uri, position);
175
+ if (!references.length) return null;
176
+ return { changes: { [uri]: references.map(location => ({ range: location.range, newText: newName })) } };
177
+ }
178
+
179
+ signatureHelp(uri, position) {
180
+ const document = this.document(uri);
181
+ const result = this.analyze(uri);
182
+ if (!document || !result.ast) return null;
183
+ const line = (document.text.split(/\r?\n/)[position.line] || '').slice(0, position.character);
184
+ const match = /([A-Za-z_$][A-Za-z0-9_$]*)\([^()]*$/.exec(line);
185
+ if (!match) return null;
186
+ const fn = (result.ast.body || []).find(node =>
187
+ (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') && node.name === match[1]
188
+ );
189
+ if (!fn) return null;
190
+ const parameters = (fn.params || []).map(param => ({
191
+ label: `${param.name}${param.typeAnnotation ? ` as ${typeName(param.typeAnnotation)}` : ''}`,
192
+ }));
193
+ const activeParameter = (line.slice(match.index).match(/,/g) || []).length;
194
+ const returns = fn.returnType ? ` returns ${typeName(fn.returnType)}` : '';
195
+ return { signatures: [{
196
+ label: `${match[1]}(${parameters.map(param => param.label).join(', ')})${returns}`,
197
+ parameters,
198
+ }], activeParameter };
199
+ }
200
+
151
201
  request(method, params = {}) {
152
202
  switch (method) {
153
203
  case 'initialize':
@@ -156,11 +206,17 @@ class LspService {
156
206
  hoverProvider: true,
157
207
  completionProvider: { triggerCharacters: ['.', ' '] },
158
208
  definitionProvider: true,
209
+ referencesProvider: true,
210
+ renameProvider: true,
211
+ signatureHelpProvider: { triggerCharacters: ['(', ','] },
159
212
  }, serverInfo: { name: 'plainscript-lsp', version: '1.0.0' } };
160
213
  case 'shutdown': this.shutdownRequested = true; return null;
161
214
  case 'textDocument/hover': return this.hover(params.textDocument.uri, params.position);
162
215
  case 'textDocument/completion': return this.completion(params.textDocument.uri);
163
216
  case 'textDocument/definition': return this.definition(params.textDocument.uri, params.position);
217
+ case 'textDocument/references': return this.references(params.textDocument.uri, params.position);
218
+ case 'textDocument/rename': return this.rename(params.textDocument.uri, params.position, params.newName);
219
+ case 'textDocument/signatureHelp': return this.signatureHelp(params.textDocument.uri, params.position);
164
220
  case 'textDocument/documentSymbol': return this.symbols(params.textDocument.uri);
165
221
  case 'workspace/symbol': {
166
222
  const all = [];