plainscript-lang 1.0.363 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.0` - 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.0" }
265
265
  }
266
266
  ```
267
267
 
@@ -436,10 +436,21 @@ show greet({ id: 1, name: "Ada" })
436
436
  ```
437
437
 
438
438
  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.
439
+ runs. Functions and intents can declare return contracts with `returns` or
440
+ `returning`; the checker validates returned values and reports missing returns.
441
+ Collection contracts can be used on mutable bindings:
442
+
443
+ ```text
444
+ let users as list of User is [{ id: 1, name: "Ada" }]
445
+ let usersById as dictionary of User is { first: { id: 1, name: "Ada" } }
446
+ ```
447
+
448
+ List elements, dictionary values, and nested record fields are checked
449
+ recursively. Optional and union element types are supported. The static checker
450
+ reports unknown fields, missing required fields, incompatible literal values,
451
+ unknown contract names, arity errors, invalid assignments, unsafe optional
452
+ member access, and invalid member access to editor tooling. Whole-program
453
+ inference and exhaustiveness checking remain future work.
443
454
 
444
455
  ### Language-server tooling
445
456
 
@@ -450,9 +461,10 @@ plainscript-lsp
450
461
  ```
451
462
 
452
463
  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.
464
+ `textDocument/publishDiagnostics`, type-rich hover, completion, definition,
465
+ references, rename, signature help, and document-symbol requests. Editors
466
+ should launch it as a standard LSP process and send JSON-RPC messages using the
467
+ normal `Content-Length` framing.
456
468
 
457
469
  ### Intent declarations
458
470
 
@@ -813,7 +825,7 @@ Portable databases (SQLite native or WebAssembly):
813
825
  database "app.db" // probes better-sqlite3, falls back to sql.js
814
826
  ```
815
827
 
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:
828
+ `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
829
 
818
830
  ```plainscript
819
831
  database "app.db" using "native" // hard requirement: better-sqlite3
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
  }
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/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 = [];
@@ -1403,10 +1403,35 @@ function parse(tokens) {
1403
1403
  nameLine = nameToken.line;
1404
1404
  }
1405
1405
 
1406
+ let typeAnnotation = null;
1407
+ // Typed mutable binding: `let users as list of User is [...]`. The
1408
+ // lookahead keeps legacy `let value as 42` default/initializer syntax
1409
+ // unchanged because only a recognized type expression followed by `is` or
1410
+ // `be` enters this path.
1411
+ if (isLet && peek().type === TOKEN.AS && isTypeNameStart(peekAt(1))) {
1412
+ const saved = pos;
1413
+ advance();
1414
+ try {
1415
+ const candidate = parseTypeSpec();
1416
+ if (peek().type === TOKEN.IS || peek().type === TOKEN.BE) {
1417
+ typeAnnotation = candidate;
1418
+ advance();
1419
+ } else {
1420
+ pos = saved;
1421
+ }
1422
+ } catch (_) {
1423
+ pos = saved;
1424
+ }
1425
+ }
1426
+
1406
1427
  // Object literal: next token is IDENTIFIER (except dictionary/map) followed by IS or BE
1407
1428
  if (peek().type === TOKEN.IDENTIFIER && peek().value !== 'dictionary' && peek().value !== 'map' && (peekAt(1).type === TOKEN.IS || peekAt(1).type === TOKEN.BE) && !isObjectShorthandAmbiguousWithComparison()) {
1408
1429
  const init = parseInlineObjectLiteral(false);
1409
- return { type: 'RememberStatement', name: target, value: init, isLet, isConstant: !isLet };
1430
+ return { type: 'RememberStatement', name: target, value: init, typeAnnotation, isLet, isConstant: !isLet };
1431
+ }
1432
+
1433
+ if (typeAnnotation) {
1434
+ return { type: 'RememberStatement', name: target, value: parseExpression(), typeAnnotation, isLet, isConstant: !isLet };
1410
1435
  }
1411
1436
 
1412
1437
  // "let" uses "is" or "be" for simple vars, but also accepts "as" for both simple and destructuring
@@ -1417,7 +1442,7 @@ function parse(tokens) {
1417
1442
  // The statement's name token is on the declaration line; a next token on a
1418
1443
  // LATER line means no initializer follows on that line.
1419
1444
  if (!isDestructuring && typeof target === 'string' && peek().line > nameLine) {
1420
- return { type: 'RememberStatement', name: target, value: null, isLet, isConstant: !isLet };
1445
+ return { type: 'RememberStatement', name: target, value: null, typeAnnotation, isLet, isConstant: !isLet };
1421
1446
  }
1422
1447
  const assignToken = isLet ? ((peek().type === TOKEN.IS || peek().type === TOKEN.BE) ? peek().type : TOKEN.AS) : TOKEN.AS;
1423
1448
  const expectedKeyword = (isLet && (peek().type === TOKEN.IS || peek().type === TOKEN.BE)) ? (peek().type === TOKEN.BE ? 'be' : 'is') : 'as';
@@ -1428,7 +1453,7 @@ function parse(tokens) {
1428
1453
 
1429
1454
  // Object literal: next token is IDENTIFIER followed by IS or BE
1430
1455
  if (peek().type === TOKEN.IDENTIFIER && (peekAt(1).type === TOKEN.IS || peekAt(1).type === TOKEN.BE) && !isObjectShorthandAmbiguousWithComparison()) {
1431
- return { type: 'RememberStatement', name: target, value: parseObjectLiteral() };
1456
+ return { type: 'RememberStatement', name: target, value: parseObjectLiteral(), typeAnnotation };
1432
1457
  }
1433
1458
 
1434
1459
  // v2.1.0 - remember <name> as query|insert|update|delete … done
@@ -1447,7 +1472,7 @@ function parse(tokens) {
1447
1472
  }
1448
1473
 
1449
1474
  const value = parseExpression();
1450
- return { type: 'RememberStatement', name: target, value };
1475
+ return { type: 'RememberStatement', name: target, value, typeAnnotation };
1451
1476
  }
1452
1477
 
1453
1478
  // ask <variable>
@@ -1578,8 +1603,13 @@ function parseAsk() {
1578
1603
  consume(TOKEN.LPAREN, `Expected "(" after function name "${name}".`);
1579
1604
  const params = parseParamList();
1580
1605
  consume(TOKEN.RPAREN, 'Expected ")" to close the parameter list.');
1606
+ let returnType = null;
1607
+ if (peek().type === TOKEN.IDENTIFIER && (peek().value === 'returns' || peek().value === 'returning')) {
1608
+ advance();
1609
+ returnType = parseTypeSpec();
1610
+ }
1581
1611
  const body = parseBody(`function "${name}"`);
1582
- return { type: 'FunctionDeclaration', name, params, body };
1612
+ return { type: 'FunctionDeclaration', name, params, returnType, body };
1583
1613
  }
1584
1614
 
1585
1615
  function parseIntentDeclaration() {
@@ -1589,11 +1619,17 @@ function parseAsk() {
1589
1619
  consume(TOKEN.LPAREN, `Expected "(" after intent name "${name}".`);
1590
1620
  const params = parseParamList();
1591
1621
  consume(TOKEN.RPAREN, 'Expected ")" to close the intent parameter list.');
1622
+ let returnType = null;
1623
+ if (peek().type === TOKEN.IDENTIFIER && (peek().value === 'returns' || peek().value === 'returning')) {
1624
+ advance();
1625
+ returnType = parseTypeSpec();
1626
+ }
1592
1627
  const body = parseBody(`intent "${name}"`);
1593
1628
  return {
1594
1629
  type: 'IntentDeclaration',
1595
1630
  name,
1596
1631
  params,
1632
+ returnType,
1597
1633
  body,
1598
1634
  intent: { kind: 'declaration', name, parameterCount: params.length },
1599
1635
  };
@@ -1602,18 +1638,19 @@ function parseAsk() {
1602
1638
  const primitiveTypeNames = new Set(['any', 'number', 'text', 'boolean', 'null', 'object']);
1603
1639
  function isTypeNameStart(token) {
1604
1640
  return token && token.type === TOKEN.IDENTIFIER &&
1605
- (declaredTypeNames.has(token.value) || primitiveTypeNames.has(token.value) || /^[A-Z]/.test(token.value));
1641
+ (declaredTypeNames.has(token.value) || primitiveTypeNames.has(token.value) ||
1642
+ ['optional', 'list', 'dictionary'].includes(token.value) || /^[A-Z]/.test(token.value));
1606
1643
  }
1607
1644
  function parseTypeAtom() {
1608
1645
  const token = peek();
1609
1646
  if (token.type === TOKEN.IDENTIFIER && token.value === 'optional') {
1610
1647
  advance();
1611
- return { kind: 'optional', value: parseTypeAtom() };
1648
+ return { kind: 'optional', value: parseTypeSpec() };
1612
1649
  }
1613
1650
  if (token.type === TOKEN.IDENTIFIER && (token.value === 'list' || token.value === 'dictionary')) {
1614
1651
  const kind = advance().value;
1615
1652
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') advance();
1616
- return { kind, value: parseTypeAtom() };
1653
+ return { kind, value: parseTypeSpec() };
1617
1654
  }
1618
1655
  if (!isTypeNameStart(token) && token.type !== TOKEN.NULL_KW) {
1619
1656
  throw new Error(makeError('Expected a type name (number, text, boolean, object, or a declared type).', token));
@@ -1,11 +1,13 @@
1
- // Static type-checking foundation for PlainScript contracts.
1
+ // Static type checking for PlainScript contracts and v1.1 language depth.
2
2
  //
3
- // This checker is intentionally conservative: untyped programs remain valid,
4
- // while declared contracts, typed parameters, known fields, and literal call
5
- // arguments receive useful diagnostics before code generation.
3
+ // The checker is intentionally conservative: unknown expressions remain `any`,
4
+ // while declared contracts, typed bindings, known literals, calls, members,
5
+ // collections, and branch-local null checks receive deterministic diagnostics.
6
6
 
7
7
  const { lowerToIR } = require('./ir');
8
8
 
9
+ const PRIMITIVES = new Set(['any', 'number', 'text', 'boolean', 'null', 'object', 'list', 'dictionary']);
10
+
9
11
  function diagnostic(message, node, code = 'PLN-TYPE') {
10
12
  const line = node && node.line ? node.line : 1;
11
13
  const column = node && node.col ? node.col : 1;
@@ -14,6 +16,7 @@ function diagnostic(message, node, code = 'PLN-TYPE') {
14
16
  source: 'plainscript',
15
17
  code,
16
18
  message,
19
+ ...(node && node.sourceFile ? { file: node.sourceFile } : {}),
17
20
  range: {
18
21
  start: { line: line - 1, character: column - 1 },
19
22
  end: { line: line - 1, character: column },
@@ -23,6 +26,7 @@ function diagnostic(message, node, code = 'PLN-TYPE') {
23
26
 
24
27
  function typeName(spec) {
25
28
  if (!spec) return 'any';
29
+ if (typeof spec === 'string') return spec;
26
30
  if (spec.kind === 'name') return spec.name;
27
31
  if (spec.kind === 'optional') return `optional ${typeName(spec.value)}`;
28
32
  if (spec.kind === 'list') return `list of ${typeName(spec.value)}`;
@@ -31,27 +35,51 @@ function typeName(spec) {
31
35
  return 'any';
32
36
  }
33
37
 
38
+ function nameSpec(name) { return { kind: 'name', name }; }
39
+ function listSpec(value = 'any') { return { kind: 'list', value }; }
40
+ function dictionarySpec(value = 'any') { return { kind: 'dictionary', value }; }
41
+
34
42
  function isNullSpec(spec) {
35
- return spec && spec.kind === 'name' && spec.name === 'null';
43
+ return spec && ((spec.kind === 'name' && spec.name === 'null') || spec === 'null');
36
44
  }
37
45
 
38
46
  function isOptionalSpec(spec) {
39
47
  return spec && (spec.kind === 'optional' || (spec.kind === 'union' && spec.values.some(isNullSpec)));
40
48
  }
41
49
 
50
+ function withoutNull(spec) {
51
+ if (!spec) return spec;
52
+ if (spec.kind === 'optional') return spec.value;
53
+ if (spec.kind === 'union') {
54
+ const values = spec.values.filter(value => !isNullSpec(value));
55
+ return values.length === 1 ? values[0] : { kind: 'union', values };
56
+ }
57
+ return spec;
58
+ }
59
+
42
60
  function specMatches(actual, expected, schemas) {
43
- if (!expected || expected.kind === 'name' && expected.name === 'any' || !actual) return true;
44
- if (expected.kind === 'optional') return actual === 'null' || specMatches(actual, expected.value, schemas);
61
+ if (!expected || expected === 'any' || (expected.kind === 'name' && expected.name === 'any') || !actual || actual === 'any') return true;
62
+ if (expected.kind === 'optional') return isNullSpec(actual) || specMatches(actual, expected.value, schemas);
45
63
  if (expected.kind === 'union') return expected.values.some(item => specMatches(actual, item, schemas));
46
64
  if (expected.kind === 'name') {
47
- if (expected.name === 'null') return actual === 'null';
48
- if (expected.name === 'object') return actual === 'object' || typeof actual === 'object';
49
- if (expected.name === actual) return true;
50
- if (schemas.has(expected.name) && actual === 'object') return true;
51
- return false;
52
- }
53
- if (expected.kind === 'list') return actual === 'list' || actual === 'any';
54
- if (expected.kind === 'dictionary') return actual === 'dictionary' || actual === 'object' || actual === 'any';
65
+ if (expected.name === 'any') return true;
66
+ if (expected.name === 'null') return isNullSpec(actual);
67
+ if (expected.name === 'object') return typeName(actual) === 'object' || typeName(actual) === 'dictionary';
68
+ if (expected.name === 'list' || expected.name === 'dictionary') return typeName(actual) === expected.name || actual.kind === expected.name;
69
+ if (typeof actual === 'string') return expected.name === actual;
70
+ if (actual.kind === 'name') return expected.name === actual.name;
71
+ return schemas.has(expected.name) && (typeName(actual) === 'object' || actual.kind === 'name');
72
+ }
73
+ if (expected.kind === 'list') {
74
+ if (actual === 'list') return true;
75
+ if (!actual || actual.kind !== 'list') return false;
76
+ return specMatches(actual.value, expected.value, schemas);
77
+ }
78
+ if (expected.kind === 'dictionary') {
79
+ if (actual === 'dictionary' || actual === 'object') return true;
80
+ if (!actual || actual.kind !== 'dictionary') return false;
81
+ return specMatches(actual.value, expected.value, schemas);
82
+ }
55
83
  return true;
56
84
  }
57
85
 
@@ -80,8 +108,7 @@ function checkTypes(ast, options = {}) {
80
108
  function addTypeSpecErrors(spec, node) {
81
109
  if (!spec) return;
82
110
  if (spec.kind === 'name') {
83
- const primitives = new Set(['any', 'number', 'text', 'boolean', 'null', 'object']);
84
- if (!primitives.has(spec.name) && !schemas.has(spec.name)) {
111
+ if (!PRIMITIVES.has(spec.name) && !schemas.has(spec.name)) {
85
112
  diagnostics.push(diagnostic(`Unknown type "${spec.name}". Declare it with type ${spec.name} ... done.`, node, 'PLN-TYPE-UNKNOWN'));
86
113
  }
87
114
  } else if (spec.kind === 'optional' || spec.kind === 'list' || spec.kind === 'dictionary') {
@@ -95,12 +122,13 @@ function checkTypes(ast, options = {}) {
95
122
  if (node.type === 'TypeDeclaration') {
96
123
  if (schemas.has(node.name)) diagnostics.push(diagnostic(`Type "${node.name}" is declared more than once.`, node, 'PLN-TYPE-DUPLICATE'));
97
124
  schemas.set(node.name, node);
125
+ symbols.set(node.name, { kind: 'type', node, type: nameSpec(node.name) });
98
126
  }
99
127
  if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
100
128
  functions.set(node.name, node);
101
- symbols.set(node.name, { kind: node.type === 'IntentDeclaration' ? 'intent' : 'function', node });
129
+ symbols.set(node.name, { kind: node.type === 'IntentDeclaration' ? 'intent' : 'function', node, type: node.returnType || 'any' });
102
130
  }
103
- if (node.type === 'RememberStatement' && typeof node.name === 'string') symbols.set(node.name, { kind: 'variable', node });
131
+ if (node.type === 'RememberStatement' && typeof node.name === 'string') symbols.set(node.name, { kind: 'variable', node, type: node.typeAnnotation || 'any' });
104
132
  }
105
133
 
106
134
  for (const node of ast.body || []) {
@@ -108,10 +136,10 @@ function checkTypes(ast, options = {}) {
108
136
  for (const field of node.fields || []) addTypeSpecErrors(field.type, field);
109
137
  }
110
138
  if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
111
- for (const param of node.params || []) {
112
- if (param.typeAnnotation) addTypeSpecErrors(param.typeAnnotation, node);
113
- }
139
+ for (const param of node.params || []) if (param.typeAnnotation) addTypeSpecErrors(param.typeAnnotation, param);
140
+ if (node.returnType) addTypeSpecErrors(node.returnType, node);
114
141
  }
142
+ if (node.type === 'RememberStatement' && node.typeAnnotation) addTypeSpecErrors(node.typeAnnotation, node);
115
143
  }
116
144
 
117
145
  function fieldSpec(schemaName, fieldName) {
@@ -122,34 +150,149 @@ function checkTypes(ast, options = {}) {
122
150
 
123
151
  function infer(node, env, origin = node) {
124
152
  if (!node) return 'any';
125
- const literal = literalType(node);
126
- if (literal) return literal;
127
153
  if (node.type === 'Identifier') {
128
154
  const entry = env.get(node.name) || symbols.get(node.name);
129
155
  return entry && entry.type ? entry.type : 'any';
130
156
  }
157
+ const literal = literalType(node);
158
+ if (literal === 'list') {
159
+ const elements = (node.elements || []).filter(item => item && item.type !== 'SpreadElement').map(item => infer(item, env, origin));
160
+ const first = elements[0] || 'any';
161
+ return listSpec(elements.every(item => specMatches(item, first, schemas)) ? first : 'any');
162
+ }
163
+ if (literal === 'object') return node.type === 'ObjectLiteral' ? dictionarySpec('any') : 'object';
164
+ if (literal) return literal;
131
165
  if (node.type === 'MemberExpression') {
132
- const objectType = infer(node.object, env, origin);
133
- if (objectType && schemas.has(objectType)) {
134
- const field = fieldSpec(objectType, node.property);
135
- if (!field) diagnostics.push(diagnostic(`Type "${objectType}" has no field named "${node.property}".`, origin, 'PLN-TYPE-FIELD'));
136
- return field ? typeName(field) : 'any';
166
+ let objectType = infer(node.object, env, origin);
167
+ if (isOptionalSpec(objectType)) {
168
+ diagnostics.push(diagnostic(`Value may be null before accessing field "${node.property}". Check it first.`, origin, 'PLN-TYPE-OPTIONAL'));
169
+ objectType = withoutNull(objectType);
137
170
  }
171
+ const schemaName = objectType && objectType.kind === 'name' ? objectType.name : objectType;
172
+ if (schemaName && schemas.has(schemaName)) {
173
+ const field = fieldSpec(schemaName, node.property);
174
+ if (!field) diagnostics.push(diagnostic(`Type "${schemaName}" has no field named "${node.property}".`, origin, 'PLN-TYPE-FIELD'));
175
+ return field || 'any';
176
+ }
177
+ if (objectType && objectType.kind === 'dictionary') return objectType.value;
178
+ return 'any';
179
+ }
180
+ if (node.type === 'IndexExpression') {
181
+ const objectType = infer(node.object, env, origin);
182
+ if (objectType && (objectType.kind === 'list' || objectType.kind === 'dictionary')) return objectType.value;
138
183
  return 'any';
139
184
  }
140
185
  if (node.type === 'CallExpression') {
141
186
  const fn = functions.get(node.name);
142
- if (fn) return 'any';
187
+ return fn && fn.returnType ? fn.returnType : 'any';
188
+ }
189
+ if (node.type === 'BinaryExpression') {
190
+ if (['===', '!==', '>', '<', '>=', '<=', 'in'].includes(node.operator)) return 'boolean';
191
+ const left = infer(node.left, env, origin);
192
+ const right = infer(node.right, env, origin);
193
+ if (node.operator === '+' && (typeName(left) === 'text' || typeName(right) === 'text')) return 'text';
194
+ if (['+', '-', '*', '/', '%'].includes(node.operator) && typeName(left) === 'number' && typeName(right) === 'number') return 'number';
143
195
  return 'any';
144
196
  }
197
+ if (node.type === 'ConditionalExpression') {
198
+ const left = infer(node.consequent, env, origin);
199
+ const right = infer(node.alternate, env, origin);
200
+ return typeName(left) === typeName(right) ? left : { kind: 'union', values: [left, right] };
201
+ }
202
+ if (node.type === 'ConditionExpression' || node.type === 'BinaryCondition' || node.type === 'UnaryCondition' ||
203
+ node.type === 'BetweenCondition' || node.type === 'StringCondition' || node.type === 'InCondition' ||
204
+ node.type === 'NotInCondition' || node.type === 'LogicalCondition') return 'boolean';
145
205
  return 'any';
146
206
  }
147
207
 
208
+ function expectedMatchesNode(node, expected, env, origin, path, emit = true) {
209
+ if (!node || !expected) return true;
210
+ if (expected.kind === 'optional') {
211
+ if (node.type === 'NullLiteral') return true;
212
+ return expectedMatchesNode(node, expected.value, env, origin, path, emit);
213
+ }
214
+ if (expected.kind === 'union') {
215
+ const start = diagnostics.length;
216
+ for (const option of expected.values) {
217
+ diagnostics.length = start;
218
+ if (expectedMatchesNode(node, option, env, origin, path, false)) {
219
+ diagnostics.length = start;
220
+ return expectedMatchesNode(node, option, env, origin, path, emit);
221
+ }
222
+ }
223
+ diagnostics.length = start;
224
+ if (emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(infer(node, env, origin))}.`, origin, 'PLN-TYPE-ELEMENT'));
225
+ return false;
226
+ }
227
+ if (expected.kind === 'list') {
228
+ const actual = infer(node, env, origin);
229
+ if (node.type !== 'ArrayLiteral') {
230
+ const ok = specMatches(actual, expected, schemas);
231
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-COLLECTION'));
232
+ return ok;
233
+ }
234
+ let ok = true;
235
+ (node.elements || []).forEach((element, index) => {
236
+ if (element && element.type === 'SpreadElement') return;
237
+ if (!expectedMatchesNode(element, expected.value, env, origin, `${path || 'Collection'} element ${index + 1}`, emit)) ok = false;
238
+ });
239
+ return ok;
240
+ }
241
+ if (expected.kind === 'dictionary') {
242
+ const actual = infer(node, env, origin);
243
+ if (node.type !== 'ObjectLiteral' && node.type !== 'InlineObjectLiteral') {
244
+ const ok = specMatches(actual, expected, schemas);
245
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-COLLECTION'));
246
+ return ok;
247
+ }
248
+ let ok = true;
249
+ (node.properties || []).forEach(property => {
250
+ if (property.type === 'SpreadProperty') return;
251
+ if (!expectedMatchesNode(property.value, expected.value, env, origin, `${path || 'Dictionary'} value "${property.key}"`, emit)) ok = false;
252
+ });
253
+ return ok;
254
+ }
255
+ if (expected.kind === 'name' && schemas.has(expected.name) &&
256
+ (node.type === 'InlineObjectLiteral' || node.type === 'ObjectLiteral')) {
257
+ const schema = schemas.get(expected.name);
258
+ const properties = new Map((node.properties || []).map(property => [property.key, property]));
259
+ let ok = true;
260
+ for (const field of schema.fields || []) {
261
+ const property = properties.get(field.key);
262
+ if (!property) {
263
+ if (!isOptionalSpec(field.type)) {
264
+ if (emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}is missing required field "${field.key}" for type "${expected.name}".`, origin, 'PLN-TYPE-FIELD'));
265
+ ok = false;
266
+ }
267
+ continue;
268
+ }
269
+ const start = diagnostics.length;
270
+ if (!expectedMatchesNode(property.value, field.type, env, origin, `${path ? `${path} ` : ''}field "${field.key}"`, emit)) ok = false;
271
+ for (let index = start; index < diagnostics.length; index += 1) {
272
+ const item = diagnostics[index];
273
+ if (item.code === 'PLN-TYPE-ARG' || item.code === 'PLN-TYPE-ELEMENT' || item.code === 'PLN-TYPE-COLLECTION') item.code = 'PLN-TYPE-FIELD';
274
+ }
275
+ }
276
+ for (const property of node.properties || []) {
277
+ if (!(schema.fields || []).some(field => field.key === property.key)) {
278
+ if (emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}type "${expected.name}" has no field named "${property.key}".`, origin, 'PLN-TYPE-FIELD'));
279
+ ok = false;
280
+ }
281
+ }
282
+ return ok;
283
+ }
284
+ const actual = infer(node, env, origin);
285
+ const ok = specMatches(actual, expected, schemas);
286
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-ARG'));
287
+ return ok;
288
+ }
289
+
148
290
  function checkExpression(node, env, origin = node) {
149
291
  if (!node || typeof node !== 'object') return;
150
- if (node.type === 'MemberExpression') {
292
+ if (node.type === 'MemberExpression' || node.type === 'IndexExpression') {
151
293
  infer(node, env, origin);
152
294
  checkExpression(node.object, env, origin);
295
+ if (node.index) checkExpression(node.index, env, origin);
153
296
  return;
154
297
  }
155
298
  if (node.type === 'CallExpression') {
@@ -161,15 +304,23 @@ function checkTypes(ast, options = {}) {
161
304
  }
162
305
  node.args.forEach((arg, index) => {
163
306
  const param = params[index];
164
- if (!param || !param.typeAnnotation) return;
165
- const actual = infer(arg, env, origin);
166
- if (!specMatches(actual, param.typeAnnotation, schemas)) {
167
- diagnostics.push(diagnostic(`Argument ${index + 1} of "${node.name}" expects ${typeName(param.typeAnnotation)}, received ${actual}.`, origin, 'PLN-TYPE-ARG'));
168
- }
169
- validateLiteralAgainstSpec(arg, param.typeAnnotation, origin);
307
+ if (param && param.typeAnnotation) expectedMatchesNode(arg, param.typeAnnotation, env, origin, `Argument ${index + 1} of "${node.name}"`);
308
+ checkExpression(arg, env, origin);
170
309
  });
310
+ } else {
311
+ node.args.forEach(arg => checkExpression(arg, env, origin));
171
312
  }
172
- node.args.forEach(arg => checkExpression(arg, env, origin));
313
+ return;
314
+ }
315
+ if (node.type === 'BinaryExpression') {
316
+ checkExpression(node.left, env, origin);
317
+ checkExpression(node.right, env, origin);
318
+ return;
319
+ }
320
+ if (node.type === 'ConditionalExpression') {
321
+ checkExpression(node.condition, env, origin);
322
+ checkExpression(node.consequent, env, origin);
323
+ checkExpression(node.alternate, env, origin);
173
324
  return;
174
325
  }
175
326
  for (const value of Object.values(node)) {
@@ -180,54 +331,61 @@ function checkTypes(ast, options = {}) {
180
331
  }
181
332
  }
182
333
 
183
- function validateLiteralAgainstSpec(node, expected, origin) {
184
- if (!node || !expected) return;
185
- if (expected.kind === 'optional') {
186
- if (node.type !== 'NullLiteral') validateLiteralAgainstSpec(node, expected.value, origin);
187
- return;
188
- }
189
- if (expected.kind === 'union') {
190
- const actual = literalType(node);
191
- if (!expected.values.some(item => specMatches(actual, item, schemas))) {
192
- diagnostics.push(diagnostic(`Expected ${typeName(expected)}, received ${actual || 'an expression'}.`, origin, 'PLN-TYPE-ARG'));
193
- }
194
- return;
334
+ function narrowEnvironment(env, condition, truthy) {
335
+ const next = new Map(env);
336
+ function apply(left, operator, right) {
337
+ if (!left || left.type !== 'Identifier' || !right || right.type !== 'NullLiteral') return;
338
+ const entry = next.get(left.name);
339
+ if (!entry || !isOptionalSpec(entry.type)) return;
340
+ const isNonNull = operator === 'is not' || operator === '!==' || operator === 'different from';
341
+ if (truthy === isNonNull) next.set(left.name, { ...entry, type: withoutNull(entry.type) });
195
342
  }
196
- if (expected.kind !== 'name' || !schemas.has(expected.name) || node.type !== 'InlineObjectLiteral') return;
197
- const schema = schemas.get(expected.name);
198
- const properties = new Map((node.properties || []).map(property => [property.key, property]));
199
- for (const field of schema.fields || []) {
200
- const property = properties.get(field.key);
201
- if (!property) {
202
- if (!isOptionalSpec(field.type)) diagnostics.push(diagnostic(`Argument is missing required field "${field.key}" for type "${expected.name}".`, origin, 'PLN-TYPE-FIELD'));
203
- continue;
204
- }
205
- const actual = literalType(property.value);
206
- if (actual && !specMatches(actual, field.type, schemas)) {
207
- diagnostics.push(diagnostic(`Field "${field.key}" expects ${typeName(field.type)}, received ${actual}.`, origin, 'PLN-TYPE-FIELD'));
208
- }
209
- validateLiteralAgainstSpec(property.value, field.type, origin);
210
- }
211
- for (const property of node.properties || []) {
212
- if (!(schema.fields || []).some(field => field.key === property.key)) {
213
- diagnostics.push(diagnostic(`Type "${expected.name}" has no field named "${property.key}".`, origin, 'PLN-TYPE-FIELD'));
214
- }
343
+ if (condition && condition.type === 'ConditionExpression') return narrowEnvironment(next, condition.value, truthy);
344
+ if (condition && condition.type === 'BinaryCondition') apply(condition.left, condition.op, condition.right);
345
+ if (condition && condition.type === 'LogicalCondition' && condition.op === 'and' && truthy) {
346
+ narrowEnvironment(narrowEnvironment(next, condition.left, true), condition.right, true).forEach((value, key) => next.set(key, value));
215
347
  }
348
+ return next;
216
349
  }
217
350
 
218
- function checkStatements(statements, env) {
351
+ function checkStatements(statements, env, returnType = null, functionName = null) {
219
352
  for (const node of statements || []) {
220
353
  if (!node) continue;
221
354
  if (node.type === 'RememberStatement' && typeof node.name === 'string') {
222
- const type = literalType(node.value);
223
- env.set(node.name, { type: type || 'any', node });
355
+ if (node.typeAnnotation) expectedMatchesNode(node.value, node.typeAnnotation, env, node, `Variable "${node.name}"`);
356
+ const inferred = node.typeAnnotation || infer(node.value, env, node);
357
+ env.set(node.name, { type: inferred || 'any', node });
358
+ symbols.set(node.name, { kind: 'variable', node, type: inferred || 'any' });
224
359
  checkExpression(node.value, env, node);
225
360
  } else if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
226
361
  const nested = new Map(env);
227
- for (const param of node.params || []) {
228
- if (param.name) nested.set(param.name, { type: param.typeAnnotation && param.typeAnnotation.kind === 'name' ? param.typeAnnotation.name : 'any', node: param });
362
+ for (const param of node.params || []) if (param.name) nested.set(param.name, { type: param.typeAnnotation || 'any', node: param });
363
+ checkStatements(node.body, nested, node.returnType || null, node.name);
364
+ checkFunctionReturns(node, nested);
365
+ } else if (node.type === 'IfStatement') {
366
+ checkExpression(node.condition, env, node);
367
+ checkStatements(node.consequent, narrowEnvironment(env, node.condition, true), returnType, functionName);
368
+ if (node.alternate) checkStatements(node.alternate, narrowEnvironment(env, node.condition, false), returnType, functionName);
369
+ } else if (node.type === 'BecomeStatement') {
370
+ checkExpression(node.value, env, node);
371
+ const actual = infer(node.value, env, node);
372
+ if (node.target && node.target.type === 'Identifier') {
373
+ const entry = env.get(node.target.name);
374
+ if (entry && entry.type && !specMatches(actual, entry.type, schemas)) {
375
+ diagnostics.push(diagnostic(`Assignment to "${node.target.name}" expects ${typeName(entry.type)}, received ${typeName(actual)}.`, node, 'PLN-TYPE-ASSIGN'));
376
+ }
377
+ if (entry && node.op === '=') env.set(node.target.name, { ...entry, type: actual });
378
+ }
379
+ } else if (node.type === 'GiveStatement' || node.type === 'ReturnStatement') {
380
+ checkExpression(node.value, env, node);
381
+ if (returnType && node.value) {
382
+ const start = diagnostics.length;
383
+ expectedMatchesNode(node.value, returnType, env, node, `Function "${functionName}" return`);
384
+ for (let index = start; index < diagnostics.length; index += 1) {
385
+ const item = diagnostics[index];
386
+ if (item.code === 'PLN-TYPE-ARG' || item.code === 'PLN-TYPE-ELEMENT' || item.code === 'PLN-TYPE-COLLECTION') item.code = 'PLN-TYPE-RETURN';
387
+ }
229
388
  }
230
- checkStatements(node.body, nested);
231
389
  } else {
232
390
  for (const value of Object.values(node)) {
233
391
  if (value && typeof value === 'object') {
@@ -239,8 +397,44 @@ function checkTypes(ast, options = {}) {
239
397
  }
240
398
  }
241
399
 
400
+ function collectReturns(statements, result = []) {
401
+ for (const node of statements || []) {
402
+ if (!node || typeof node !== 'object') continue;
403
+ if (node.type === 'GiveStatement' || node.type === 'ReturnStatement') result.push(node);
404
+ for (const key of ['body', 'consequent', 'alternate', 'handlers', 'finalizer']) {
405
+ const child = node[key];
406
+ if (Array.isArray(child)) collectReturns(child, result);
407
+ else if (child && typeof child === 'object') collectReturns([child], result);
408
+ }
409
+ }
410
+ return result;
411
+ }
412
+
413
+ function checkFunctionReturns(fn, env) {
414
+ if (!fn.returnType) return;
415
+ const returns = collectReturns(fn.body);
416
+ if (returns.length === 0) {
417
+ diagnostics.push(diagnostic(`Function "${fn.name}" declares ${typeName(fn.returnType)} but does not return a value.`, fn, 'PLN-TYPE-RETURN-MISSING'));
418
+ return;
419
+ }
420
+ if (returns.some(statement => !statement.value) && !isOptionalSpec(fn.returnType)) {
421
+ diagnostics.push(diagnostic(`Function "${fn.name}" returns ${typeName(fn.returnType)} but this return has no value.`, fn, 'PLN-TYPE-RETURN'));
422
+ }
423
+ }
424
+
425
+ // Imports are resolved by the bundler before this checker receives a graph.
426
+ // A flattened graph therefore exposes declarations from every local module;
427
+ // report only names that are genuinely absent and ignore npm imports.
428
+ for (const node of ast.body || []) {
429
+ if (node.type !== 'ImportStatement' || !node.path || !node.path.endsWith('.pln') && !node.path.startsWith('.') && !node.path.startsWith('@/') && !node.path.startsWith('/')) continue;
430
+ const imported = node.names || (node.defaultImport ? [node.defaultImport] : []);
431
+ for (const name of imported) {
432
+ if (!symbols.has(name)) diagnostics.push(diagnostic(`Imported symbol "${name}" was not found in the resolved module graph.`, node, 'PLN-MODULE-UNKNOWN'));
433
+ }
434
+ }
435
+
242
436
  checkStatements(ast.body, new Map());
243
437
  return { diagnostics, ir };
244
438
  }
245
439
 
246
- module.exports = { checkTypes, typeName };
440
+ module.exports = { checkTypes, typeName, specMatches };
@@ -1,6 +1,6 @@
1
1
  // Single source of truth for the compiler version.
2
2
  // Consumed by cli.js help/version output.
3
3
 
4
- const VERSION = '1.0.363';
4
+ const VERSION = '1.1.0';
5
5
 
6
6
  module.exports = { VERSION };
@@ -151,6 +151,14 @@ let y be 6
151
151
  remember z as 7
152
152
  ```
153
153
 
154
+ Mutable bindings may carry a recursive collection or record contract between
155
+ the name and initializer:
156
+
157
+ ```text
158
+ let users as list of User is [{ id: 1, name: "Ada" }]
159
+ let usersById as dictionary of User is { first: { id: 1, name: "Ada" } }
160
+ ```
161
+
154
162
  Reassignment (word-formed; PlainScript has no `=` symbol):
155
163
 
156
164
  ```plainscript
@@ -206,9 +214,10 @@ make greet(user as User)
206
214
  done
207
215
  ```
208
216
 
209
- The generated function validates `user` before entering its body. This slice
210
- provides runtime contracts; static inference and compile-time field checking
211
- are not yet implemented.
217
+ The generated function validates `user` before entering its body. The static
218
+ checker also validates literal arguments, typed bindings, return contracts,
219
+ collection elements, nested fields, and known member access. It remains
220
+ conservative for expressions whose types are unknown.
212
221
 
213
222
  ## 5. Statements and blocks
214
223
 
@@ -134,6 +134,26 @@ done
134
134
  show add(2, 3)
135
135
  ```
136
136
 
137
+ Functions and intents may declare a return contract with `returns` (or the
138
+ equivalent `returning`) after the parameter list. The static checker validates
139
+ each `give`/`return` value and reports a missing return when a declared
140
+ function has no return value:
141
+
142
+ ```plainscript
143
+ make add(a as number, b as number) returns number
144
+ give a + b
145
+ done
146
+
147
+ intend greeting(name as text) returns text
148
+ give `Hello, ${name}`
149
+ done
150
+ ```
151
+
152
+ Return contracts use the same primitive, optional, list, dictionary, union, and
153
+ declared-record types as parameter contracts. Untyped functions remain valid,
154
+ and a function call with a return contract contributes that type to subsequent
155
+ static checking.
156
+
137
157
  Function parameters can have simple defaults:
138
158
 
139
159
  ```plainscript
@@ -211,6 +231,19 @@ The checker powers the stdio language server started with `plainscript-lsp`.
211
231
  The server publishes these diagnostics and provides hover, completion,
212
232
  definition, and document-symbol responses using standard LSP JSON-RPC framing.
213
233
 
234
+ Mutable bindings can declare recursive collection contracts with `as` before
235
+ the initializer:
236
+
237
+ ```text
238
+ let users as list of User is [{ id: 1, name: "Ada" }]
239
+ let usersById as dictionary of User is { first: { id: 1, name: "Ada" } }
240
+ ```
241
+
242
+ The checker validates every list element and dictionary value, including nested
243
+ record fields. Optional and union element types use the same rules as function
244
+ contracts. A known `list of T` or `dictionary of T` contributes `T` to indexed
245
+ access, and null checks narrow optional values within the checked branch.
246
+
214
247
  ## Control flow
215
248
 
216
249
  ```plainscript
@@ -0,0 +1,220 @@
1
+ # PlainScript v1.1.0: Typed Collections Design
2
+
3
+ **Status:** Design proposal
4
+ **Milestone:** v1.1.0 · Language Depth
5
+ **Predecessor:** Function return contracts
6
+
7
+ ## Purpose
8
+
9
+ Typed collections are the next increment after return contracts. Return contracts
10
+ make a function's result visible to the checker. Typed collections make the
11
+ shape of that result useful when it contains repeated or nested values.
12
+
13
+ The feature must solve one narrow problem well: when PlainScript has a declared
14
+ collection type and a collection literal is available, the checker must verify
15
+ every element against the declared element type. This includes nested lists,
16
+ dictionaries, and declared record contracts. The implementation must not become
17
+ a general-purpose whole-program inference system in this branch.
18
+
19
+ ## Proposed surface syntax
20
+
21
+ PlainScript already uses `list of T` and `dictionary of T` in record fields and
22
+ function parameter contracts. The same type expressions will be valid for local
23
+ mutable bindings by placing the annotation between the variable name and its
24
+ initializer:
25
+
26
+ ```text
27
+ type User
28
+ id is number
29
+ name is text
30
+ done
31
+
32
+ let users as list of User is [
33
+ { id: 1, name: "David" },
34
+ { id: 2, name: "Samuel" }
35
+ ]
36
+
37
+ let usersById as dictionary of User is {
38
+ first: { id: 1, name: "David" },
39
+ second: { id: 2, name: "Samuel" }
40
+ }
41
+ ```
42
+
43
+ The existing `let name is value` form remains unchanged. The existing
44
+ `remember name as value` form also remains unchanged in this milestone because
45
+ `as` is already its initializer separator. Typed immutable bindings are not
46
+ needed to establish collection checking and can be designed separately without
47
+ making `remember` ambiguous.
48
+
49
+ The feature does not introduce a new collection literal syntax. Square brackets
50
+ remain list literals, and braces remain object or dictionary literals according
51
+ to their existing parsing context.
52
+
53
+ ## Type model
54
+
55
+ The parser will continue to produce the existing recursive type-specification
56
+ shape:
57
+
58
+ ```text
59
+ name -> { kind: "name", name }
60
+ optional T -> { kind: "optional", value: T }
61
+ list of T -> { kind: "list", value: T }
62
+ dictionary of T -> { kind: "dictionary", value: T }
63
+ T or U -> { kind: "union", values: [T, U] }
64
+ ```
65
+
66
+ The checker should treat these specifications as recursive values rather than
67
+ flattening collection types to the single string `list` or `dictionary`. A
68
+ small internal `TypeRef` normalization layer may be introduced if the current
69
+ string-based inference prevents recursive comparisons. That refactoring belongs
70
+ inside the checker and must preserve existing diagnostic codes and messages for
71
+ primitive contracts.
72
+
73
+ A declared record name remains a named type. Its value is valid only when the
74
+ checker can verify an object literal against the corresponding `type`
75
+ declaration, or when the value's known type is that declared record. A plain
76
+ `object` remains intentionally less specific and accepts any object value.
77
+
78
+ ## Static checking rules
79
+
80
+ When a typed binding has an initializer, the checker performs these checks:
81
+
82
+ 1. `list of T` requires a list literal or a known list value. Every element is
83
+ checked recursively against `T`.
84
+ 2. `dictionary of T` requires an object or known dictionary value. Every value is
85
+ checked recursively against `T`; dictionary keys remain unconstrained text
86
+ keys.
87
+ 3. `optional T` accepts a missing value or `null`, and otherwise checks the
88
+ value against `T`.
89
+ 4. `T or U` accepts a value matching at least one branch. Literal diagnostics
90
+ should report the complete expected union when no branch matches.
91
+ 5. A named record type checks required fields, optional fields, unknown fields,
92
+ and each field value recursively. If a field itself has type `list of User`,
93
+ every list element is checked as a `User` record.
94
+ 6. A literal with an expression-valued element is not rejected merely because
95
+ the expression is not yet inferable. The checker reports a mismatch only
96
+ when the expression has a known incompatible type. Expression propagation is
97
+ the following v1.1.0 milestone.
98
+
99
+ For example, this program must produce a field diagnostic for the second list
100
+ element:
101
+
102
+ ```text
103
+ type User
104
+ id is number
105
+ name is text
106
+ done
107
+
108
+ make loadUsers() returns list of User
109
+ give [
110
+ { id: 1, name: "David" },
111
+ { id: "wrong", name: "Samuel" }
112
+ ]
113
+ done
114
+ ```
115
+
116
+ The diagnostic should identify the collection context and element path, such as
117
+ `Return value element 2 field "id" expects number, received text.` The exact
118
+ wording may evolve, but the diagnostic must retain the existing
119
+ `PLN-TYPE-FIELD` or `PLN-TYPE-RETURN` family and point to the collection's source
120
+ range until element-level source spans are available.
121
+
122
+ ## Contract propagation within this milestone
123
+
124
+ The checker should record a typed local binding's declared type in its
125
+ environment. A call to a function returning `list of User` or `dictionary of
126
+ User` should likewise retain that recursive return type rather than reducing it
127
+ to `list` or `dictionary`.
128
+
129
+ This milestone only requires enough propagation to validate collection values at
130
+ contract boundaries and to validate indexed access when the type is already
131
+ known. Indexing a known `list of T` may produce `T`, and reading a known
132
+ `dictionary of T` may produce `T`. Rich propagation through arbitrary operators,
133
+ branches, aliases, and callbacks belongs to the next expression-typing branch.
134
+
135
+ ## Runtime behavior
136
+
137
+ Typed collections do not add runtime behavior. Existing generated JavaScript
138
+ already represents lists as arrays and dictionaries as objects. Runtime record
139
+ validation remains the responsibility of the existing function-entry contract
140
+ checks. The new work is static validation of literal collection contents and
141
+ preservation of recursive type information in the checker.
142
+
143
+ If a typed collection is passed to a function at runtime, the generated program
144
+ must continue to use the same contract validation path as an equivalent record
145
+ field. The design must not introduce a second incompatible runtime validator.
146
+
147
+ ## Diagnostics
148
+
149
+ The implementation should add only diagnostics needed to explain collection
150
+ mismatches:
151
+
152
+ | Code | Meaning |
153
+ | --- | --- |
154
+ | `PLN-TYPE-COLLECTION` | A value is not a list or dictionary where the contract requires one. |
155
+ | `PLN-TYPE-ELEMENT` | A list element or dictionary value does not match its element type. |
156
+ | `PLN-TYPE-FIELD` | A nested declared record has a missing, invalid, or unknown field. |
157
+ | `PLN-TYPE-ARG` | A function argument does not match a collection parameter contract. |
158
+ | `PLN-TYPE-RETURN` | A return value does not match a collection return contract. |
159
+
160
+ Existing field and argument diagnostics should be reused where they already
161
+ explain the failure. New codes are justified only when they distinguish the
162
+ collection boundary from the nested value. Diagnostics should include the
163
+ expected recursive type using the existing `typeName` rendering, for example
164
+ `list of User` or `dictionary of optional text`.
165
+
166
+ ## Parser and checker changes
167
+
168
+ The implementation branch should make the following bounded changes:
169
+
170
+ - Extend `let` declarations to accept `let name as Type is value` and preserve
171
+ the parsed type on the `RememberStatement` node as `typeAnnotation`.
172
+ - Validate the annotation through the same unknown-type path used by parameter
173
+ and return contracts.
174
+ - Replace literal-only contract validation with a recursive validator that can
175
+ descend through `ArrayLiteral`, `InlineObjectLiteral`, and `ObjectLiteral`
176
+ nodes.
177
+ - Store the declared recursive type on the local checker environment.
178
+ - Preserve recursive return types from function calls.
179
+ - Add focused tests for lists, dictionaries, nested records, unions, optional
180
+ elements, invalid element values, and unknown nested contract names.
181
+ - Update the language specification and README examples only after the grammar
182
+ and checker tests pass.
183
+
184
+ No generator changes are expected unless the existing runtime contract emitter
185
+ cannot consume recursive collection specifications. No LSP feature work belongs
186
+ in this branch.
187
+
188
+ ## Explicit non-goals
189
+
190
+ This branch will not implement flow-sensitive narrowing, full operator typing,
191
+ collection mutation checking, generic type parameters, tuple types, inferred
192
+ annotations for every variable, cross-file type resolution, or advanced LSP
193
+ features. It will not attempt to prove that every possible runtime collection
194
+ value is valid. Static guarantees apply to values and expressions whose types
195
+ are known at the checking point.
196
+
197
+ ## Acceptance criteria
198
+
199
+ The branch is ready for review when all of the following hold:
200
+
201
+ - A valid `list of User` literal passes static checking.
202
+ - An invalid nested record inside a list produces a deterministic diagnostic.
203
+ - A valid `dictionary of User` literal passes static checking.
204
+ - An invalid dictionary value is reported without masking unrelated diagnostics.
205
+ - Nested lists and dictionaries recurse through at least two levels.
206
+ - Optional and union element types behave consistently with existing contracts.
207
+ - A function returning `list of User` preserves that return type for a caller.
208
+ - Existing untyped programs and existing parameter contracts remain unchanged.
209
+ - Focused type tests, LSP tests, documentation checks, and the full test suite
210
+ pass before the branch is opened.
211
+
212
+ ## References
213
+
214
+ [1]: https://github.com/ayoistooslick/plainscript/blob/main/docs/PLAINSCRIPT-SPEC.md "PlainScript language specification"
215
+ [2]: https://github.com/ayoistooslick/plainscript/blob/main/compiler/type-checker.js "PlainScript static type checker"
216
+ [3]: https://github.com/ayoistooslick/plainscript/blob/main/compiler/parser.js "PlainScript parser"
217
+ [4]: https://github.com/ayoistooslick/plainscript/blob/main/tests/types.test.js "PlainScript type tests"
218
+
219
+ The proposal is grounded in the existing contract syntax and checker behavior
220
+ specified in [1] and implemented in [2]–[4].
@@ -0,0 +1,21 @@
1
+ type User
2
+ id is number
3
+ name is text
4
+ done
5
+
6
+ let users as list of User is [
7
+ { id: 1, name: "Ada" },
8
+ { id: 2, name: "Grace" }
9
+ ]
10
+
11
+ let usersById as dictionary of User is {
12
+ first: { id: 1, name: "Ada" },
13
+ second: { id: 2, name: "Grace" }
14
+ }
15
+
16
+ make firstUser() returns User
17
+ give users[0]
18
+ done
19
+
20
+ show firstUser().name
21
+ show usersById.first.name
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plainscript-lang",
3
- "version": "1.0.363",
3
+ "version": "1.1.0",
4
4
  "description": "PlainScript - an Intent-Oriented Programming Language. When even a simple sentence can be code.",
5
5
  "main": "compiler/cli.js",
6
6
  "bin": {