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.
@@ -176,6 +176,7 @@ function parse(tokens) {
176
176
  let pos = 0;
177
177
  let _inRepeatCount = false;
178
178
  const declaredTypeNames = new Set(['any', 'number', 'text', 'boolean', 'null', 'object']);
179
+ let activeGenericNames = new Set();
179
180
  function peek() { return tokens[pos]; }
180
181
  function peekAt(offset) { return tokens[pos + offset] || { type: TOKEN.EOF }; }
181
182
  function advance() { return tokens[pos++]; }
@@ -1650,6 +1651,20 @@ function parseAsk() {
1650
1651
  ));
1651
1652
  }
1652
1653
  const name = advance().value;
1654
+ const genericParams = [];
1655
+ if (peek().type === TOKEN.LESS_THAN) {
1656
+ advance();
1657
+ while (peek().type !== TOKEN.GREATER_THAN) {
1658
+ const param = consume(TOKEN.IDENTIFIER, 'Expected a generic type parameter name.');
1659
+ if (genericParams.includes(param.value)) throw new Error(makeError(`Generic parameter "${param.value}" is declared more than once.`, param));
1660
+ genericParams.push(param.value);
1661
+ if (peek().type !== TOKEN.COMMA) break;
1662
+ advance();
1663
+ }
1664
+ consume(TOKEN.GREATER_THAN, 'Expected ">" after generic type parameters.');
1665
+ }
1666
+ const previousGenericNames = activeGenericNames;
1667
+ activeGenericNames = new Set(genericParams);
1653
1668
  consume(TOKEN.LPAREN, `Expected "(" after function name "${name}".`);
1654
1669
  const params = parseParamList();
1655
1670
  consume(TOKEN.RPAREN, 'Expected ")" to close the parameter list.');
@@ -1659,7 +1674,8 @@ function parseAsk() {
1659
1674
  returnType = parseTypeSpec();
1660
1675
  }
1661
1676
  const body = parseBody(`function "${name}"`);
1662
- return { type: 'FunctionDeclaration', name, params, returnType, body };
1677
+ activeGenericNames = previousGenericNames;
1678
+ return { type: 'FunctionDeclaration', name, params, returnType, body, genericParams };
1663
1679
  }
1664
1680
 
1665
1681
  function parseIntentDeclaration() {
@@ -1690,8 +1706,8 @@ function parseAsk() {
1690
1706
  const primitiveTypeNames = new Set(['any', 'number', 'text', 'boolean', 'null', 'object']);
1691
1707
  function isTypeNameStart(token) {
1692
1708
  return token && token.type === TOKEN.IDENTIFIER &&
1693
- (declaredTypeNames.has(token.value) || primitiveTypeNames.has(token.value) ||
1694
- ['optional', 'list', 'dictionary'].includes(token.value) || /^[A-Z]/.test(token.value));
1709
+ (declaredTypeNames.has(token.value) || activeGenericNames.has(token.value) || primitiveTypeNames.has(token.value) ||
1710
+ ['optional', 'list', 'dictionary', 'map', 'set', 'tuple'].includes(token.value) || /^[A-Z]/.test(token.value));
1695
1711
  }
1696
1712
  function parseTypeAtom() {
1697
1713
  const token = peek();
@@ -1704,15 +1720,30 @@ function parseAsk() {
1704
1720
  advance();
1705
1721
  return { kind: 'optional', value: parseTypeSpec() };
1706
1722
  }
1707
- if (token.type === TOKEN.IDENTIFIER && (token.value === 'list' || token.value === 'dictionary')) {
1723
+ if (token.type === TOKEN.IDENTIFIER && (token.value === 'list' || token.value === 'dictionary' || token.value === 'set')) {
1708
1724
  const kind = advance().value;
1709
1725
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') advance();
1710
1726
  return { kind, value: parseTypeSpec() };
1711
1727
  }
1728
+ if (token.type === TOKEN.IDENTIFIER && token.value === 'map') {
1729
+ advance();
1730
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') advance();
1731
+ const key = parseTypeAtom();
1732
+ if (peek().type === TOKEN.TO || peek().type === TOKEN.IDENTIFIER && (peek().value === 'to' || peek().value === 'of')) advance();
1733
+ return { kind: 'map', key, value: parseTypeSpec() };
1734
+ }
1735
+ if (token.type === TOKEN.IDENTIFIER && token.value === 'tuple') {
1736
+ advance();
1737
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') advance();
1738
+ const values = [parseTypeAtom()];
1739
+ while (peek().type === TOKEN.COMMA) { advance(); values.push(parseTypeAtom()); }
1740
+ return { kind: 'tuple', values };
1741
+ }
1712
1742
  if (!isTypeNameStart(token) && token.type !== TOKEN.NULL_KW) {
1713
1743
  throw new Error(makeError('Expected a type name (number, text, boolean, object, or a declared type).', token));
1714
1744
  }
1715
1745
  advance();
1746
+ if (activeGenericNames.has(token.value)) return { kind: 'typeParam', name: token.value };
1716
1747
  return { kind: 'name', name: token.value };
1717
1748
  }
1718
1749
  function parseTypeSpec() {
@@ -1732,6 +1763,10 @@ function parseAsk() {
1732
1763
  throw new Error(makeError(`Type "${name}" is already declared.`, nameToken));
1733
1764
  }
1734
1765
  declaredTypeNames.add(name);
1766
+ if (peek().type === TOKEN.IS || peek().type === TOKEN.BE) {
1767
+ advance();
1768
+ return { type: 'TypeAlias', name, target: parseTypeSpec() };
1769
+ }
1735
1770
  const fields = [];
1736
1771
  while (!atBlockEnd()) {
1737
1772
  if (peek().type === TOKEN.EOF) {
@@ -6,12 +6,13 @@
6
6
 
7
7
  const { lowerToIR } = require('./ir');
8
8
 
9
- const PRIMITIVES = new Set(['any', 'number', 'text', 'boolean', 'null', 'object', 'list', 'dictionary']);
9
+ const PRIMITIVES = new Set(['any', 'number', 'text', 'boolean', 'null', 'object', 'list', 'dictionary', 'map', 'set', 'tuple']);
10
10
  const ASYNC_CALLS = new Set([
11
11
  'fetch', 'fetchJson', 'fetchBytes', 'sleep', 'sleepAsync', 'waitFor',
12
12
  'http', 'request', 'query', 'insert', 'update', 'delete', 'execute',
13
13
  'Promise.resolve', 'Promise.reject', 'Promise.all', 'Promise.allSettled',
14
14
  'Promise.race', 'Promise.any',
15
+ 'withCancellation', 'dispose', 'using',
15
16
  ]);
16
17
  const AUTO_AWAIT_CALLS = new Set(['fetchJson', 'fetchBytes']);
17
18
  const STANDARD_LIBRARY_ALIASES = new Map([
@@ -45,6 +46,9 @@ function typeName(spec) {
45
46
  if (spec.kind === 'optional') return `optional ${typeName(spec.value)}`;
46
47
  if (spec.kind === 'list') return `list of ${typeName(spec.value)}`;
47
48
  if (spec.kind === 'dictionary') return `dictionary of ${typeName(spec.value)}`;
49
+ if (spec.kind === 'map') return `map of ${typeName(spec.key)} to ${typeName(spec.value)}`;
50
+ if (spec.kind === 'set') return `set of ${typeName(spec.value)}`;
51
+ if (spec.kind === 'tuple') return `tuple of ${(spec.values || []).map(typeName).join(', ')}`;
48
52
  if (spec.kind === 'promise') return `Promise of ${typeName(spec.value)}`;
49
53
  if (spec.kind === 'union') return spec.values.map(typeName).join(' or ');
50
54
  return 'any';
@@ -54,6 +58,9 @@ function nameSpec(name) { return { kind: 'name', name }; }
54
58
  function listSpec(value = 'any') { return { kind: 'list', value }; }
55
59
  function dictionarySpec(value = 'any') { return { kind: 'dictionary', value }; }
56
60
  function promiseSpec(value = 'any') { return { kind: 'promise', value }; }
61
+ function mapSpec(key = 'any', value = 'any') { return { kind: 'map', key, value }; }
62
+ function setSpec(value = 'any') { return { kind: 'set', value }; }
63
+ function tupleSpec(values = []) { return { kind: 'tuple', values }; }
57
64
 
58
65
  function isNullSpec(spec) {
59
66
  return spec && ((spec.kind === 'name' && spec.name === 'null') || spec === 'null');
@@ -77,33 +84,51 @@ function withoutNull(spec) {
77
84
  return spec;
78
85
  }
79
86
 
80
- function specMatches(actual, expected, schemas) {
81
- if (!expected || expected === 'any' || (expected.kind === 'name' && expected.name === 'any') || !actual || actual === 'any') return true;
82
- if (expected.kind === 'optional') return isNullSpec(actual) || specMatches(actual, expected.value, schemas);
83
- if (expected.kind === 'promise') return isPromiseSpec(actual) && specMatches(actual.value, expected.value, schemas);
84
- if (expected.kind === 'union') return expected.values.some(item => specMatches(actual, item, schemas));
87
+ function specMatches(actual, expected, schemas, seen = new Set()) {
88
+ if (!expected || expected === 'any' || (expected.kind === 'name' && expected.name === 'any') || !actual) return true;
89
+ if (actual === 'any' || (actual.kind === 'name' && actual.name === 'any')) return true;
90
+ const pair = `${typeName(actual)}=>${typeName(expected)}`;
91
+ if (seen.has(pair)) return true;
92
+ seen.add(pair);
93
+ if (actual.kind === 'union' && expected.kind !== 'union') {
94
+ return actual.values.length > 0 && actual.values.every(value => specMatches(value, expected, schemas, seen));
95
+ }
96
+ if (expected.kind === 'optional') return isNullSpec(actual) || specMatches(actual, expected.value, schemas, seen);
97
+ if (expected.kind === 'promise') return isPromiseSpec(actual) && specMatches(actual.value, expected.value, schemas, seen);
98
+ if (expected.kind === 'union') return expected.values.some(item => specMatches(actual, item, schemas, seen));
85
99
  if (expected.kind === 'name') {
86
100
  if (expected.name === 'any') return true;
87
101
  if (expected.name === 'null') return isNullSpec(actual);
88
102
  if (expected.name === 'object') return typeName(actual) === 'object' || typeName(actual) === 'dictionary';
89
103
  if (expected.name === 'list' || expected.name === 'dictionary') return typeName(actual) === expected.name || actual.kind === expected.name;
104
+ const alias = schemas.get(expected.name);
105
+ if (alias && alias.type === 'TypeAlias') return specMatches(actual, alias.target, schemas, seen);
90
106
  if (typeof actual === 'string') return expected.name === actual;
91
- if (actual.kind === 'name') return expected.name === actual.name;
107
+ if (actual.kind === 'name') {
108
+ if (expected.name === actual.name) return true;
109
+ const actualAlias = schemas.get(actual.name);
110
+ return actualAlias && actualAlias.type === 'TypeAlias' ? specMatches(actualAlias.target, expected, schemas, seen) : false;
111
+ }
92
112
  return schemas.has(expected.name) && (typeName(actual) === 'object' || actual.kind === 'name');
93
113
  }
94
114
  if (expected.kind === 'list') {
95
115
  if (actual === 'list') return true;
96
116
  if (!actual || actual.kind !== 'list') return false;
97
- return specMatches(actual.value, expected.value, schemas);
117
+ return specMatches(actual.value, expected.value, schemas, seen);
98
118
  }
99
119
  if (expected.kind === 'dictionary') {
100
120
  if (actual === 'dictionary' || actual === 'object') return true;
101
121
  if (!actual || actual.kind !== 'dictionary') return false;
102
- return specMatches(actual.value, expected.value, schemas);
122
+ return specMatches(actual.value, expected.value, schemas, seen);
103
123
  }
104
124
  if (expected.kind === 'promise') {
105
- return isPromiseSpec(actual) && specMatches(actual.value, expected.value, schemas);
125
+ return isPromiseSpec(actual) && specMatches(actual.value, expected.value, schemas, seen);
126
+ }
127
+ if (expected.kind === 'map') {
128
+ return Boolean(actual && actual.kind === 'map') && specMatches(actual.key, expected.key, schemas, seen) && specMatches(actual.value, expected.value, schemas, seen);
106
129
  }
130
+ if (expected.kind === 'set') return Boolean(actual && actual.kind === 'set') && specMatches(actual.value, expected.value, schemas, seen);
131
+ if (expected.kind === 'tuple') return Boolean(actual && actual.kind === 'tuple') && actual.values.length === expected.values.length && expected.values.every((value, index) => specMatches(actual.values[index], value, schemas, seen));
107
132
  return true;
108
133
  }
109
134
 
@@ -117,7 +142,11 @@ function literalType(node) {
117
142
  case 'NullLiteral': return 'null';
118
143
  case 'ArrayLiteral': return 'list';
119
144
  case 'InlineObjectLiteral':
120
- case 'ObjectLiteral': return 'object';
145
+ case 'ObjectLiteral':
146
+ case 'DictionaryLiteral':
147
+ case 'SetLiteral':
148
+ case 'SetFromExpression':
149
+ case 'TupleLiteral': return 'object';
121
150
  default: return null;
122
151
  }
123
152
  }
@@ -131,12 +160,18 @@ function checkTypes(ast, options = {}) {
131
160
 
132
161
  function addTypeSpecErrors(spec, node) {
133
162
  if (!spec) return;
163
+ if (spec.kind === 'typeParam') return;
134
164
  if (spec.kind === 'name') {
135
165
  if (!PRIMITIVES.has(spec.name) && !schemas.has(spec.name)) {
136
166
  diagnostics.push(diagnostic(`Unknown type "${spec.name}". Declare it with type ${spec.name} ... done.`, node, 'PLN-TYPE-UNKNOWN'));
137
167
  }
138
- } else if (spec.kind === 'optional' || spec.kind === 'list' || spec.kind === 'dictionary' || spec.kind === 'promise') {
168
+ } else if (spec.kind === 'optional' || spec.kind === 'list' || spec.kind === 'dictionary' || spec.kind === 'set' || spec.kind === 'promise') {
139
169
  addTypeSpecErrors(spec.value, node);
170
+ } else if (spec.kind === 'map') {
171
+ addTypeSpecErrors(spec.key, node);
172
+ addTypeSpecErrors(spec.value, node);
173
+ } else if (spec.kind === 'tuple') {
174
+ (spec.values || []).forEach(value => addTypeSpecErrors(value, node));
140
175
  } else if (spec.kind === 'union') {
141
176
  spec.values.forEach(value => addTypeSpecErrors(value, node));
142
177
  }
@@ -148,6 +183,11 @@ function checkTypes(ast, options = {}) {
148
183
  schemas.set(node.name, node);
149
184
  symbols.set(node.name, { kind: 'type', node, type: nameSpec(node.name) });
150
185
  }
186
+ if (node.type === 'TypeAlias') {
187
+ if (schemas.has(node.name)) diagnostics.push(diagnostic(`Type "${node.name}" is declared more than once.`, node, 'PLN-TYPE-DUPLICATE'));
188
+ schemas.set(node.name, node);
189
+ symbols.set(node.name, { kind: 'type', node, type: node.target });
190
+ }
151
191
  if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
152
192
  functions.set(node.name, node);
153
193
  symbols.set(node.name, { kind: node.type === 'IntentDeclaration' ? 'intent' : 'function', node, type: node.returnType || 'any' });
@@ -159,6 +199,7 @@ function checkTypes(ast, options = {}) {
159
199
  if (node.type === 'TypeDeclaration') {
160
200
  for (const field of node.fields || []) addTypeSpecErrors(field.type, field);
161
201
  }
202
+ if (node.type === 'TypeAlias') addTypeSpecErrors(node.target, node);
162
203
  if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
163
204
  for (const param of node.params || []) if (param.typeAnnotation) addTypeSpecErrors(param.typeAnnotation, param);
164
205
  if (node.returnType) addTypeSpecErrors(node.returnType, node);
@@ -172,6 +213,18 @@ function checkTypes(ast, options = {}) {
172
213
  return field ? field.type : null;
173
214
  }
174
215
 
216
+ function unionMembers(spec, seen = new Set()) {
217
+ if (!spec) return [];
218
+ if (spec.kind === 'union') return spec.values.flatMap(value => unionMembers(value, seen));
219
+ if (spec.kind === 'name') {
220
+ if (seen.has(spec.name)) return [];
221
+ seen.add(spec.name);
222
+ const schema = schemas.get(spec.name);
223
+ if (schema && schema.type === 'TypeAlias') return unionMembers(schema.target, seen);
224
+ }
225
+ return [spec];
226
+ }
227
+
175
228
  function containsAsync(node, seen = new Set()) {
176
229
  if (!node || typeof node !== 'object' || seen.has(node)) return false;
177
230
  seen.add(node);
@@ -189,6 +242,71 @@ function checkTypes(ast, options = {}) {
189
242
  if (isPromiseSpec(declared)) return declared;
190
243
  return containsAsync(fn && fn.body) ? promiseSpec(declared) : declared;
191
244
  }
245
+ function substituteGeneric(spec, bindings) {
246
+ if (!spec || typeof spec !== 'object') return spec;
247
+ if (spec.kind === 'typeParam') return bindings.get(spec.name) || 'any';
248
+ if (spec.kind === 'union') return { kind: 'union', values: spec.values.map(value => substituteGeneric(value, bindings)) };
249
+ if (['optional', 'list', 'dictionary', 'set', 'promise'].includes(spec.kind)) return { ...spec, value: substituteGeneric(spec.value, bindings) };
250
+ if (spec.kind === 'map') return { ...spec, key: substituteGeneric(spec.key, bindings), value: substituteGeneric(spec.value, bindings) };
251
+ if (spec.kind === 'tuple') return { ...spec, values: spec.values.map(value => substituteGeneric(value, bindings)) };
252
+ return spec;
253
+ }
254
+ function bindGeneric(pattern, actual, bindings) {
255
+ if (!pattern || !actual) return;
256
+ if (pattern.kind === 'typeParam') { if (!bindings.has(pattern.name) || typeName(bindings.get(pattern.name)) === 'any') bindings.set(pattern.name, actual); return; }
257
+ if (pattern.kind === actual.kind && ['list', 'dictionary', 'set', 'optional', 'promise'].includes(pattern.kind)) bindGeneric(pattern.value, actual.value, bindings);
258
+ else if (pattern.kind === 'map' && actual.kind === 'map') {
259
+ bindGeneric(pattern.key, actual.key, bindings);
260
+ bindGeneric(pattern.value, actual.value, bindings);
261
+ } else if (pattern.kind === 'tuple' && actual.kind === 'tuple') {
262
+ for (let index = 0; index < Math.min(pattern.values.length, actual.values.length); index += 1) bindGeneric(pattern.values[index], actual.values[index], bindings);
263
+ }
264
+ else if (pattern.kind === 'union') for (const option of pattern.values) if (option.kind === 'typeParam' || option.kind === actual.kind) { bindGeneric(option, actual, bindings); break; }
265
+ }
266
+ function genericBindings(fn, args, env) {
267
+ const bindings = new Map();
268
+ if (!fn.genericParams || fn.genericParams.length === 0) return bindings;
269
+ for (let index = 0; index < Math.min(args.length, (fn.params || []).length); index += 1) {
270
+ const param = fn.params[index];
271
+ if (param.typeAnnotation) bindGeneric(param.typeAnnotation, infer(args[index], env, args[index]), bindings);
272
+ }
273
+ return bindings;
274
+ }
275
+
276
+ // v1.1.2 - stable return types for the deterministic standard library.
277
+ // Unknown JavaScript/npm calls remain `any` rather than being guessed.
278
+ const BUILTIN_RETURN_TYPES = new Map([
279
+ ...['abs', 'min', 'max', 'sqrt', 'pow', 'floor', 'ceil', 'round', 'trunc',
280
+ 'sign', 'random', 'randomInt', 'clamp', 'lerp', 'ln2', 'ln10', 'log2e',
281
+ 'log10e', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2', 'sinh',
282
+ 'cosh', 'tanh', 'exp', 'expm1', 'log', 'log1p', 'log2', 'log10', 'hypot',
283
+ 'cbrt', 'fileSize', 'charCodeAt', 'codePointAt', 'indexOf', 'lastIndexOf',
284
+ 'search', 'findIndex', 'findLastIndex'].map(name => [name, 'number']),
285
+ ...['lowercase', 'uppercase', 'trim', 'trimStart', 'trimEnd', 'toUpperCase', 'toLowerCase', 'slice',
286
+ 'substring', 'substr', 'replaceAll', 'toString', 'stringValueOf', 'join',
287
+ 'baseName', 'folderOf', 'extensionOf', 'fileType'].map(name => [name, 'text']),
288
+ ['length', 'number'],
289
+ ['charAt', 'text'], ['includes', 'boolean'], ['startsWith', 'boolean'],
290
+ ['endsWith', 'boolean'], ['split', listSpec('text')], ['matchAll', listSpec('any')],
291
+ ['walkFolder', listSpec('text')],
292
+ ['cancellationToken', 'object'], ['cancel', 'any'], ['isCancelled', 'boolean'],
293
+ ['withCancellation', 'any'], ['dispose', 'any'], ['using', 'any'],
294
+ ]);
295
+
296
+ const MEMBER_RETURN_TYPES = {
297
+ text: new Map([
298
+ ['toLowerCase', 'text'], ['toUpperCase', 'text'], ['trim', 'text'],
299
+ ['trimStart', 'text'], ['trimEnd', 'text'], ['slice', 'text'],
300
+ ['substring', 'text'], ['substr', 'text'], ['replaceAll', 'text'],
301
+ ['charAt', 'text'], ['toString', 'text'], ['includes', 'boolean'],
302
+ ['startsWith', 'boolean'], ['endsWith', 'boolean'], ['indexOf', 'number'],
303
+ ['lastIndexOf', 'number'], ['search', 'number'],
304
+ ]),
305
+ list: new Map([
306
+ ['includes', 'boolean'], ['indexOf', 'number'], ['lastIndexOf', 'number'],
307
+ ['join', 'text'], ['slice', 'list'],
308
+ ]),
309
+ };
192
310
 
193
311
  function isPromiseProducing(node, env) {
194
312
  return isPromiseSpec(infer(node, env, node));
@@ -220,9 +338,19 @@ function checkTypes(ast, options = {}) {
220
338
  if (literal === 'list') {
221
339
  const elements = (node.elements || []).filter(item => item && item.type !== 'SpreadElement').map(item => infer(item, env, origin));
222
340
  const first = elements[0] || 'any';
223
- return listSpec(elements.every(item => specMatches(item, first, schemas)) ? first : 'any');
341
+ if (elements.every(item => specMatches(item, first, schemas)) && elements.every(item => specMatches(first, item, schemas))) {
342
+ return listSpec(first);
343
+ }
344
+ const values = [];
345
+ for (const item of elements) if (!values.some(value => typeName(value) === typeName(item))) values.push(item);
346
+ return listSpec(values.length > 1 ? { kind: 'union', values } : (values[0] || 'any'));
347
+ }
348
+ if (literal === 'object') {
349
+ if (node.type === 'DictionaryLiteral') return mapSpec();
350
+ if (node.type === 'SetLiteral' || node.type === 'SetFromExpression') return setSpec();
351
+ if (node.type === 'TupleLiteral') return tupleSpec((node.elements || []).map(item => infer(item, env, origin)));
352
+ return node.type === 'ObjectLiteral' ? dictionarySpec('any') : 'object';
224
353
  }
225
- if (literal === 'object') return node.type === 'ObjectLiteral' ? dictionarySpec('any') : 'object';
226
354
  if (literal) return literal;
227
355
  if (node.type === 'MemberExpression') {
228
356
  let objectType = infer(node.object, env, origin);
@@ -231,22 +359,39 @@ function checkTypes(ast, options = {}) {
231
359
  objectType = withoutNull(objectType);
232
360
  }
233
361
  const schemaName = objectType && objectType.kind === 'name' ? objectType.name : objectType;
234
- if (schemaName && schemas.has(schemaName)) {
362
+ if (schemaName && schemas.has(schemaName) && schemas.get(schemaName).type !== 'TypeAlias') {
235
363
  const field = fieldSpec(schemaName, node.property);
236
364
  if (!field) diagnostics.push(diagnostic(`Type "${schemaName}" has no field named "${node.property}".`, origin, 'PLN-TYPE-FIELD'));
237
365
  return field || 'any';
238
366
  }
367
+ const members = unionMembers(objectType);
368
+ if (members.length > 1) {
369
+ const fields = members.map(member => member.kind === 'name' ? fieldSpec(member.name, node.property) : null).filter(Boolean);
370
+ if (fields.length) return fields.length === 1 ? fields[0] : { kind: 'union', values: fields };
371
+ }
239
372
  if (objectType && objectType.kind === 'dictionary') return objectType.value;
240
373
  return 'any';
241
374
  }
375
+ if (node.type === 'OptionalChainExpression') {
376
+ const objectType = withoutNull(infer(node.object, env, origin));
377
+ const methods = MEMBER_RETURN_TYPES[typeName(objectType)];
378
+ return methods && methods.get(node.property) ? methods.get(node.property) : 'any';
379
+ }
242
380
  if (node.type === 'IndexExpression') {
243
381
  const objectType = infer(node.object, env, origin);
244
- if (objectType && (objectType.kind === 'list' || objectType.kind === 'dictionary')) return objectType.value;
382
+ if (objectType && (objectType.kind === 'list' || objectType.kind === 'dictionary' || objectType.kind === 'set')) return objectType.value;
383
+ if (objectType && objectType.kind === 'map') return objectType.value;
245
384
  return 'any';
246
385
  }
247
386
  if (node.type === 'CallExpression') {
248
387
  const fn = functions.get(node.name);
249
- if (fn) return functionReturnType(fn);
388
+ if (fn) return substituteGeneric(functionReturnType(fn), genericBindings(fn, node.args || [], env));
389
+ if (node.name && BUILTIN_RETURN_TYPES.has(node.name)) return BUILTIN_RETURN_TYPES.get(node.name);
390
+ if (node.callee && node.callee.type === 'MemberExpression') {
391
+ const receiver = withoutNull(infer(node.callee.object, env, origin));
392
+ const methods = MEMBER_RETURN_TYPES[typeName(receiver)];
393
+ if (methods && methods.has(node.callee.property)) return methods.get(node.callee.property);
394
+ }
250
395
  if (ASYNC_CALLS.has(node.name)) return promiseSpec('any');
251
396
  if (node.callee && node.callee.type === 'MemberExpression' &&
252
397
  ASYNC_CALLS.has(`${node.callee.object.name}.${node.callee.property}`)) return promiseSpec('any');
@@ -351,6 +496,48 @@ function checkTypes(ast, options = {}) {
351
496
  }
352
497
  return ok;
353
498
  }
499
+ if (expected.kind === 'map') {
500
+ const actual = infer(node, env, origin);
501
+ if (node.type !== 'DictionaryLiteral') {
502
+ const ok = specMatches(actual, expected, schemas);
503
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-COLLECTION'));
504
+ return ok;
505
+ }
506
+ let ok = true;
507
+ for (const pair of node.pairs || []) {
508
+ if (!expectedMatchesNode(pair.key, expected.key, env, origin, `${path || 'Map'} key`, emit)) ok = false;
509
+ if (!expectedMatchesNode(pair.value, expected.value, env, origin, `${path || 'Map'} value`, emit)) ok = false;
510
+ }
511
+ return ok;
512
+ }
513
+ if (expected.kind === 'set') {
514
+ const actual = infer(node, env, origin);
515
+ if (node.type !== 'SetLiteral' && node.type !== 'SetFromExpression') {
516
+ const ok = specMatches(actual, expected, schemas);
517
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-COLLECTION'));
518
+ return ok;
519
+ }
520
+ let ok = true;
521
+ for (const [index, element] of (node.elements || []).entries()) {
522
+ if (!expectedMatchesNode(element, expected.value, env, origin, `${path || 'Set'} element ${index + 1}`, emit)) ok = false;
523
+ }
524
+ return ok;
525
+ }
526
+ if (expected.kind === 'tuple') {
527
+ const actual = infer(node, env, origin);
528
+ const elements = node.type === 'TupleLiteral' ? node.elements || [] : null;
529
+ if (!elements) {
530
+ const ok = specMatches(actual, expected, schemas);
531
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-COLLECTION'));
532
+ return ok;
533
+ }
534
+ let ok = elements.length === expected.values.length;
535
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received tuple of ${elements.length} value(s).`, origin, 'PLN-TYPE-COLLECTION'));
536
+ for (let index = 0; index < Math.min(elements.length, expected.values.length); index += 1) {
537
+ if (!expectedMatchesNode(elements[index], expected.values[index], env, origin, `${path || 'Tuple'} item ${index + 1}`, emit)) ok = false;
538
+ }
539
+ return ok;
540
+ }
354
541
  const actual = infer(node, env, origin);
355
542
  const ok = specMatches(actual, expected, schemas);
356
543
  if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-ARG'));
@@ -361,6 +548,25 @@ function checkTypes(ast, options = {}) {
361
548
  if (!node || typeof node !== 'object') return;
362
549
  if (node.type === 'MemberExpression' || node.type === 'IndexExpression') {
363
550
  infer(node, env, origin);
551
+ if (node.type === 'IndexExpression') {
552
+ const objectType = infer(node.object, env, origin);
553
+ const indexType = infer(node.index, env, origin);
554
+ if (objectType && objectType.kind === 'list' && typeName(indexType) !== 'number' && typeName(indexType) !== 'any') {
555
+ diagnostics.push(diagnostic(`List indexes must be number values, received ${typeName(indexType)}.`, origin, 'PLN-TYPE-INDEX'));
556
+ }
557
+ if (objectType && objectType.kind === 'dictionary' && typeName(indexType) !== 'text' && typeName(indexType) !== 'any') {
558
+ diagnostics.push(diagnostic(`Dictionary indexes must be text values, received ${typeName(indexType)}.`, origin, 'PLN-TYPE-INDEX'));
559
+ }
560
+ if (objectType && objectType.kind === 'map' && typeName(indexType) !== typeName(objectType.key) && typeName(indexType) !== 'any') {
561
+ diagnostics.push(diagnostic(`Map indexes must be ${typeName(objectType.key)} values, received ${typeName(indexType)}.`, origin, 'PLN-TYPE-INDEX'));
562
+ }
563
+ if (objectType && objectType.kind === 'tuple' && node.index && node.index.type === 'NumberLiteral') {
564
+ const index = Number(node.index.value);
565
+ if (!Number.isInteger(index) || index < 0 || index >= objectType.values.length) {
566
+ diagnostics.push(diagnostic(`Tuple index ${node.index.value} is outside the fixed tuple range 0..${objectType.values.length - 1}.`, origin, 'PLN-TYPE-INDEX'));
567
+ }
568
+ }
569
+ }
364
570
  checkExpression(node.object, env, origin);
365
571
  if (node.index) checkExpression(node.index, env, origin);
366
572
  return;
@@ -368,6 +574,7 @@ function checkTypes(ast, options = {}) {
368
574
  if (node.type === 'CallExpression') {
369
575
  const fn = functions.get(node.name);
370
576
  if (fn) {
577
+ const bindings = genericBindings(fn, node.args || [], env);
371
578
  const params = (fn.params || []).filter(param => param.name);
372
579
  if (node.args.length !== params.length && !params.some(param => param.type === 'RestElement')) {
373
580
  diagnostics.push(diagnostic(`Intent/function "${node.name}" expects ${params.length} argument(s), received ${node.args.length}.`, origin, 'PLN-TYPE-ARITY'));
@@ -377,7 +584,7 @@ function checkTypes(ast, options = {}) {
377
584
  const missingAwait = param && param.typeAnnotation && reportMissingAwait(
378
585
  arg, env, param.typeAnnotation, `Argument ${index + 1} of "${node.name}"`
379
586
  );
380
- if (param && param.typeAnnotation && !missingAwait) expectedMatchesNode(arg, param.typeAnnotation, env, origin, `Argument ${index + 1} of "${node.name}"`);
587
+ if (param && param.typeAnnotation && !missingAwait) expectedMatchesNode(arg, substituteGeneric(param.typeAnnotation, bindings), env, origin, `Argument ${index + 1} of "${node.name}"`);
381
588
  checkExpression(arg, env, origin);
382
589
  });
383
590
  } else {
@@ -416,6 +623,21 @@ function checkTypes(ast, options = {}) {
416
623
  function narrowEnvironment(env, condition, truthy) {
417
624
  const next = new Map(env);
418
625
  function apply(left, operator, right) {
626
+ if (left && left.type === 'MemberExpression' && left.object && left.object.type === 'Identifier' &&
627
+ right && (right.type === 'StringLiteral' || right.type === 'NumberLiteral' || right.type === 'BooleanLiteral')) {
628
+ const entry = next.get(left.object.name);
629
+ if (!entry) return;
630
+ const members = unionMembers(entry.type);
631
+ const narrowed = members.filter(member => {
632
+ if (member.kind !== 'name') return false;
633
+ const field = fieldSpec(member.name, left.property);
634
+ return field && ((right.type === 'StringLiteral' && typeName(field) === 'text') ||
635
+ (right.type === 'NumberLiteral' && typeName(field) === 'number') ||
636
+ (right.type === 'BooleanLiteral' && typeName(field) === 'boolean'));
637
+ });
638
+ if (narrowed.length) next.set(left.object.name, { ...entry, type: narrowed.length === 1 ? narrowed[0] : { kind: 'union', values: narrowed } });
639
+ return;
640
+ }
419
641
  if (!left || left.type !== 'Identifier' || !right || right.type !== 'NullLiteral') return;
420
642
  const entry = next.get(left.name);
421
643
  if (!entry || !isOptionalSpec(entry.type)) return;
@@ -430,6 +652,28 @@ function checkTypes(ast, options = {}) {
430
652
  return next;
431
653
  }
432
654
 
655
+ function checkMatchStatement(node, env) {
656
+ checkExpression(node.value, env, node);
657
+ const seen = new Set();
658
+ let hasTrue = false;
659
+ let hasFalse = false;
660
+ for (const item of node.cases || []) {
661
+ checkExpression(item.test, env, node);
662
+ const key = item.test && item.test.type === 'StringLiteral' ? `text:${item.test.value}`
663
+ : item.test && item.test.type === 'NumberLiteral' ? `number:${item.test.value}`
664
+ : item.test && item.test.type === 'BooleanLiteral' ? `boolean:${item.test.value}` : null;
665
+ if (key && seen.has(key)) diagnostics.push(diagnostic(`Duplicate match case ${key}.`, item.test, 'PLN-MATCH-DUPLICATE'));
666
+ if (key) seen.add(key);
667
+ if (item.test && item.test.type === 'BooleanLiteral') { if (item.test.value) hasTrue = true; else hasFalse = true; }
668
+ checkStatements(item.body || [], new Map(env));
669
+ }
670
+ if (node.defaultCase) checkStatements(node.defaultCase, new Map(env));
671
+ const valueType = infer(node.value, env, node);
672
+ if (typeName(valueType) === 'boolean' && !node.defaultCase && !(hasTrue && hasFalse)) {
673
+ diagnostics.push(diagnostic('Boolean match is not exhaustive; add cases for true and false or provide otherwise.', node, 'PLN-MATCH-NONEXHAUSTIVE'));
674
+ }
675
+ }
676
+
433
677
  function checkStatements(statements, env, returnType = null, functionName = null) {
434
678
  for (const node of statements || []) {
435
679
  if (!node) continue;
@@ -437,7 +681,7 @@ function checkTypes(ast, options = {}) {
437
681
  const missingAwait = reportMissingAwait(node.value, env, node.typeAnnotation, `Variable "${node.name}"`);
438
682
  if (node.typeAnnotation && !missingAwait) expectedMatchesNode(node.value, node.typeAnnotation, env, node, `Variable "${node.name}"`);
439
683
  const inferred = node.typeAnnotation || infer(node.value, env, node);
440
- env.set(node.name, { type: inferred || 'any', node });
684
+ env.set(node.name, { type: inferred || 'any', node, declared: Boolean(node.typeAnnotation) });
441
685
  symbols.set(node.name, { kind: 'variable', node, type: inferred || 'any' });
442
686
  checkExpression(node.value, env, node);
443
687
  } else if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
@@ -445,10 +689,22 @@ function checkTypes(ast, options = {}) {
445
689
  for (const param of node.params || []) if (param.name) nested.set(param.name, { type: param.typeAnnotation || 'any', node: param });
446
690
  checkStatements(node.body, nested, node.returnType || null, node.name);
447
691
  checkFunctionReturns(node, nested);
692
+ } else if (node.type === 'MatchStatement') {
693
+ checkMatchStatement(node, env);
448
694
  } else if (node.type === 'IfStatement') {
449
695
  checkExpression(node.condition, env, node);
450
696
  checkStatements(node.consequent, narrowEnvironment(env, node.condition, true), returnType, functionName);
451
697
  if (node.alternate) checkStatements(node.alternate, narrowEnvironment(env, node.condition, false), returnType, functionName);
698
+ } else if (['ForEachStatement', 'ForIndexStatement', 'WhileStatement', 'RepeatTimesStatement',
699
+ 'EveryStatement', 'EveryFrameStatement', 'AfterStatement', 'RetryStatement', 'RouteStatement',
700
+ 'ListenStatement', 'StreamStatement', 'RunParallelStatement', 'GatherStatement', 'TotalStatement',
701
+ 'WhenTargetedStatement', 'WhenHappensStatement', 'TelegramCommandStatement', 'TelegramCallbackStatement',
702
+ 'SocketMessageStatement', 'SocketConnectStatement', 'SocketDisconnectStatement'].includes(node.type)) {
703
+ for (const key of ['collection', 'count', 'start', 'end', 'over', 'condition', 'delay', 'port']) {
704
+ if (node[key]) checkExpression(node[key], env, node);
705
+ }
706
+ if (Array.isArray(node.body)) checkStatements(node.body, new Map(env), returnType, functionName);
707
+ else if (node.body && typeof node.body === 'object') checkExpression(node.body, new Map(env), node);
452
708
  } else if (node.type === 'BecomeStatement') {
453
709
  checkExpression(node.value, env, node);
454
710
  const actual = infer(node.value, env, node);
@@ -457,7 +713,20 @@ function checkTypes(ast, options = {}) {
457
713
  if (entry && entry.type && !specMatches(actual, entry.type, schemas)) {
458
714
  diagnostics.push(diagnostic(`Assignment to "${node.target.name}" expects ${typeName(entry.type)}, received ${typeName(actual)}.`, node, 'PLN-TYPE-ASSIGN'));
459
715
  }
460
- if (entry && node.op === '=') env.set(node.target.name, { ...entry, type: actual });
716
+ if (entry && node.op === '=' && !entry.declared) env.set(node.target.name, { ...entry, type: actual });
717
+ }
718
+ } else if (node.type === 'PutStatement') {
719
+ checkExpression(node.key, env, node);
720
+ checkExpression(node.value, env, node);
721
+ checkExpression(node.mapVar, env, node);
722
+ const target = node.mapVar && node.mapVar.type === 'Identifier' ? env.get(node.mapVar.name) : null;
723
+ if (target && target.type && target.type.kind === 'map') {
724
+ if (!specMatches(infer(node.key, env, node), target.type.key, schemas)) {
725
+ diagnostics.push(diagnostic(`Map key expects ${typeName(target.type.key)}, received ${typeName(infer(node.key, env, node))}.`, node.key, 'PLN-TYPE-ASSIGN'));
726
+ }
727
+ if (!specMatches(infer(node.value, env, node), target.type.value, schemas)) {
728
+ diagnostics.push(diagnostic(`Map value expects ${typeName(target.type.value)}, received ${typeName(infer(node.value, env, node))}.`, node.value, 'PLN-TYPE-ASSIGN'));
729
+ }
461
730
  }
462
731
  } else if (node.type === 'GiveStatement' || node.type === 'ReturnStatement') {
463
732
  checkExpression(node.value, env, node);
@@ -471,6 +740,10 @@ function checkTypes(ast, options = {}) {
471
740
  if (item.code === 'PLN-TYPE-ARG' || item.code === 'PLN-TYPE-ELEMENT' || item.code === 'PLN-TYPE-COLLECTION') item.code = 'PLN-TYPE-RETURN';
472
741
  }
473
742
  }
743
+ } else if (node.type === 'TryStatement') {
744
+ checkStatements(node.body || [], new Map(env), returnType, functionName);
745
+ for (const handler of node.catches || []) checkStatements(handler.body || [], new Map(env), returnType, functionName);
746
+ checkStatements(node.finallyBody || [], new Map(env), returnType, functionName);
474
747
  } else {
475
748
  for (const value of Object.values(node)) {
476
749
  if (value && typeof value === 'object') {
@@ -519,7 +792,12 @@ function checkTypes(ast, options = {}) {
519
792
  }
520
793
 
521
794
  checkStatements(ast.body, new Map());
522
- return { diagnostics, ir };
795
+ const uniqueDiagnostics = diagnostics.filter((item, index, all) => index === all.findIndex(other =>
796
+ other.code === item.code && other.message === item.message &&
797
+ other.range.start.line === item.range.start.line &&
798
+ other.range.start.character === item.range.start.character
799
+ ));
800
+ return { diagnostics: uniqueDiagnostics, ir };
523
801
  }
524
802
 
525
803
  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.1.1';
4
+ const VERSION = '1.1.5';
5
5
 
6
6
  module.exports = { VERSION };
@@ -4,7 +4,7 @@ This document is the single source of truth for the PlainScript language
4
4
  surface. Compiler behavior (`compiler/lexer.js`, `compiler/parser.js`,
5
5
  `compiler/generator.js`) overrides any prose in this or other docs.
6
6
 
7
- Version: 1.1.1
7
+ Version: 1.1.5
8
8
 
9
9
  ---
10
10
 
@@ -229,8 +229,12 @@ done
229
229
 
230
230
  The generated function validates `user` before entering its body. The static
231
231
  checker also validates literal arguments, typed bindings, return contracts,
232
- collection elements, nested fields, and known member access. It remains
233
- conservative for expressions whose types are unknown.
232
+ collection elements, nested fields, and known member access. Since v1.1.5,
233
+ canonical standard-library calls and common text/list methods propagate their
234
+ known return types through expressions, for example
235
+ `"Ada".toLowerCase().includes("a")` is known to be boolean and
236
+ `"a,b".split(",")` is known to be a list of text. Typed `set of T`, `map of K to V`, and fixed-size `tuple of A, B` contracts are checked recursively. It remains conservative for
237
+ unknown JavaScript/npm calls and treats them as `any`.
234
238
 
235
239
  ### Async values and Promise contracts
236
240