plainscript-lang 1.1.0 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,9 +6,23 @@
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
+ const ASYNC_CALLS = new Set([
11
+ 'fetch', 'fetchJson', 'fetchBytes', 'sleep', 'sleepAsync', 'waitFor',
12
+ 'http', 'request', 'query', 'insert', 'update', 'delete', 'execute',
13
+ 'Promise.resolve', 'Promise.reject', 'Promise.all', 'Promise.allSettled',
14
+ 'Promise.race', 'Promise.any',
15
+ 'withCancellation', 'dispose', 'using',
16
+ ]);
17
+ const AUTO_AWAIT_CALLS = new Set(['fetchJson', 'fetchBytes']);
18
+ const STANDARD_LIBRARY_ALIASES = new Map([
19
+ ['lower', 'lowercase'],
20
+ ['upper', 'uppercase'],
21
+ ['to_lower', 'lowercase'],
22
+ ['to_upper', 'uppercase'],
23
+ ]);
10
24
 
11
- function diagnostic(message, node, code = 'PLN-TYPE') {
25
+ function diagnostic(message, node, code = 'PLN-TYPE', details = {}) {
12
26
  const line = node && node.line ? node.line : 1;
13
27
  const column = node && node.col ? node.col : 1;
14
28
  return {
@@ -16,6 +30,7 @@ function diagnostic(message, node, code = 'PLN-TYPE') {
16
30
  source: 'plainscript',
17
31
  code,
18
32
  message,
33
+ ...details,
19
34
  ...(node && node.sourceFile ? { file: node.sourceFile } : {}),
20
35
  range: {
21
36
  start: { line: line - 1, character: column - 1 },
@@ -31,6 +46,10 @@ function typeName(spec) {
31
46
  if (spec.kind === 'optional') return `optional ${typeName(spec.value)}`;
32
47
  if (spec.kind === 'list') return `list of ${typeName(spec.value)}`;
33
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(', ')}`;
52
+ if (spec.kind === 'promise') return `Promise of ${typeName(spec.value)}`;
34
53
  if (spec.kind === 'union') return spec.values.map(typeName).join(' or ');
35
54
  return 'any';
36
55
  }
@@ -38,6 +57,10 @@ function typeName(spec) {
38
57
  function nameSpec(name) { return { kind: 'name', name }; }
39
58
  function listSpec(value = 'any') { return { kind: 'list', value }; }
40
59
  function dictionarySpec(value = 'any') { return { kind: 'dictionary', value }; }
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 }; }
41
64
 
42
65
  function isNullSpec(spec) {
43
66
  return spec && ((spec.kind === 'name' && spec.name === 'null') || spec === 'null');
@@ -47,6 +70,10 @@ function isOptionalSpec(spec) {
47
70
  return spec && (spec.kind === 'optional' || (spec.kind === 'union' && spec.values.some(isNullSpec)));
48
71
  }
49
72
 
73
+ function isPromiseSpec(spec) {
74
+ return Boolean(spec && spec.kind === 'promise');
75
+ }
76
+
50
77
  function withoutNull(spec) {
51
78
  if (!spec) return spec;
52
79
  if (spec.kind === 'optional') return spec.value;
@@ -57,29 +84,51 @@ function withoutNull(spec) {
57
84
  return spec;
58
85
  }
59
86
 
60
- function specMatches(actual, expected, 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);
63
- 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));
64
99
  if (expected.kind === 'name') {
65
100
  if (expected.name === 'any') return true;
66
101
  if (expected.name === 'null') return isNullSpec(actual);
67
102
  if (expected.name === 'object') return typeName(actual) === 'object' || typeName(actual) === 'dictionary';
68
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);
69
106
  if (typeof actual === 'string') return expected.name === actual;
70
- 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
+ }
71
112
  return schemas.has(expected.name) && (typeName(actual) === 'object' || actual.kind === 'name');
72
113
  }
73
114
  if (expected.kind === 'list') {
74
115
  if (actual === 'list') return true;
75
116
  if (!actual || actual.kind !== 'list') return false;
76
- return specMatches(actual.value, expected.value, schemas);
117
+ return specMatches(actual.value, expected.value, schemas, seen);
77
118
  }
78
119
  if (expected.kind === 'dictionary') {
79
120
  if (actual === 'dictionary' || actual === 'object') return true;
80
121
  if (!actual || actual.kind !== 'dictionary') return false;
81
- return specMatches(actual.value, expected.value, schemas);
122
+ return specMatches(actual.value, expected.value, schemas, seen);
123
+ }
124
+ if (expected.kind === 'promise') {
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);
82
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));
83
132
  return true;
84
133
  }
85
134
 
@@ -93,7 +142,11 @@ function literalType(node) {
93
142
  case 'NullLiteral': return 'null';
94
143
  case 'ArrayLiteral': return 'list';
95
144
  case 'InlineObjectLiteral':
96
- case 'ObjectLiteral': return 'object';
145
+ case 'ObjectLiteral':
146
+ case 'DictionaryLiteral':
147
+ case 'SetLiteral':
148
+ case 'SetFromExpression':
149
+ case 'TupleLiteral': return 'object';
97
150
  default: return null;
98
151
  }
99
152
  }
@@ -107,12 +160,18 @@ function checkTypes(ast, options = {}) {
107
160
 
108
161
  function addTypeSpecErrors(spec, node) {
109
162
  if (!spec) return;
163
+ if (spec.kind === 'typeParam') return;
110
164
  if (spec.kind === 'name') {
111
165
  if (!PRIMITIVES.has(spec.name) && !schemas.has(spec.name)) {
112
166
  diagnostics.push(diagnostic(`Unknown type "${spec.name}". Declare it with type ${spec.name} ... done.`, node, 'PLN-TYPE-UNKNOWN'));
113
167
  }
114
- } else if (spec.kind === 'optional' || spec.kind === 'list' || spec.kind === 'dictionary') {
168
+ } else if (spec.kind === 'optional' || spec.kind === 'list' || spec.kind === 'dictionary' || spec.kind === 'set' || spec.kind === 'promise') {
115
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));
116
175
  } else if (spec.kind === 'union') {
117
176
  spec.values.forEach(value => addTypeSpecErrors(value, node));
118
177
  }
@@ -124,6 +183,11 @@ function checkTypes(ast, options = {}) {
124
183
  schemas.set(node.name, node);
125
184
  symbols.set(node.name, { kind: 'type', node, type: nameSpec(node.name) });
126
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
+ }
127
191
  if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
128
192
  functions.set(node.name, node);
129
193
  symbols.set(node.name, { kind: node.type === 'IntentDeclaration' ? 'intent' : 'function', node, type: node.returnType || 'any' });
@@ -135,6 +199,7 @@ function checkTypes(ast, options = {}) {
135
199
  if (node.type === 'TypeDeclaration') {
136
200
  for (const field of node.fields || []) addTypeSpecErrors(field.type, field);
137
201
  }
202
+ if (node.type === 'TypeAlias') addTypeSpecErrors(node.target, node);
138
203
  if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
139
204
  for (const param of node.params || []) if (param.typeAnnotation) addTypeSpecErrors(param.typeAnnotation, param);
140
205
  if (node.returnType) addTypeSpecErrors(node.returnType, node);
@@ -148,6 +213,121 @@ function checkTypes(ast, options = {}) {
148
213
  return field ? field.type : null;
149
214
  }
150
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
+
228
+ function containsAsync(node, seen = new Set()) {
229
+ if (!node || typeof node !== 'object' || seen.has(node)) return false;
230
+ seen.add(node);
231
+ if (node.type === 'AwaitExpression') return true;
232
+ if (node.type === 'CallExpression' && (ASYNC_CALLS.has(node.name) ||
233
+ (node.callee && node.callee.type === 'MemberExpression' &&
234
+ ASYNC_CALLS.has(`${node.callee.object.name}.${node.callee.property}`)))) return true;
235
+ return Object.values(node).some(value => Array.isArray(value)
236
+ ? value.some(item => containsAsync(item, seen))
237
+ : value && typeof value === 'object' && containsAsync(value, seen));
238
+ }
239
+
240
+ function functionReturnType(fn) {
241
+ const declared = fn && fn.returnType ? fn.returnType : 'any';
242
+ if (isPromiseSpec(declared)) return declared;
243
+ return containsAsync(fn && fn.body) ? promiseSpec(declared) : declared;
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
+ };
310
+
311
+ function isPromiseProducing(node, env) {
312
+ return isPromiseSpec(infer(node, env, node));
313
+ }
314
+
315
+ function isAutoAwaitedCall(node) {
316
+ return node && node.type === 'CallExpression' && AUTO_AWAIT_CALLS.has(node.name);
317
+ }
318
+
319
+ function reportMissingAwait(node, env, expected, label) {
320
+ if (!node || node.type === 'AwaitExpression' || !isPromiseProducing(node, env) || isAutoAwaitedCall(node)) return false;
321
+ if (expected && (isPromiseSpec(expected) || typeName(expected) === 'any')) return false;
322
+ const producer = node.type === 'CallExpression' ? node.name : 'async expression';
323
+ diagnostics.push(diagnostic(
324
+ `${label} receives a Promise from "${producer}". Use "wait for" to resolve it.\nExample: remember result as wait for ${producer}(...).`,
325
+ node,
326
+ 'PLN-ASYNC-MISSING-AWAIT'
327
+ ));
328
+ return true;
329
+ }
330
+
151
331
  function infer(node, env, origin = node) {
152
332
  if (!node) return 'any';
153
333
  if (node.type === 'Identifier') {
@@ -158,9 +338,19 @@ function checkTypes(ast, options = {}) {
158
338
  if (literal === 'list') {
159
339
  const elements = (node.elements || []).filter(item => item && item.type !== 'SpreadElement').map(item => infer(item, env, origin));
160
340
  const first = elements[0] || 'any';
161
- 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';
162
353
  }
163
- if (literal === 'object') return node.type === 'ObjectLiteral' ? dictionarySpec('any') : 'object';
164
354
  if (literal) return literal;
165
355
  if (node.type === 'MemberExpression') {
166
356
  let objectType = infer(node.object, env, origin);
@@ -169,22 +359,47 @@ function checkTypes(ast, options = {}) {
169
359
  objectType = withoutNull(objectType);
170
360
  }
171
361
  const schemaName = objectType && objectType.kind === 'name' ? objectType.name : objectType;
172
- if (schemaName && schemas.has(schemaName)) {
362
+ if (schemaName && schemas.has(schemaName) && schemas.get(schemaName).type !== 'TypeAlias') {
173
363
  const field = fieldSpec(schemaName, node.property);
174
364
  if (!field) diagnostics.push(diagnostic(`Type "${schemaName}" has no field named "${node.property}".`, origin, 'PLN-TYPE-FIELD'));
175
365
  return field || 'any';
176
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
+ }
177
372
  if (objectType && objectType.kind === 'dictionary') return objectType.value;
178
373
  return 'any';
179
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
+ }
180
380
  if (node.type === 'IndexExpression') {
181
381
  const objectType = infer(node.object, env, origin);
182
- 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;
183
384
  return 'any';
184
385
  }
185
386
  if (node.type === 'CallExpression') {
186
387
  const fn = functions.get(node.name);
187
- return fn && fn.returnType ? fn.returnType : 'any';
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
+ }
395
+ if (ASYNC_CALLS.has(node.name)) return promiseSpec('any');
396
+ if (node.callee && node.callee.type === 'MemberExpression' &&
397
+ ASYNC_CALLS.has(`${node.callee.object.name}.${node.callee.property}`)) return promiseSpec('any');
398
+ return 'any';
399
+ }
400
+ if (node.type === 'AwaitExpression') {
401
+ const awaited = infer(node.value, env, origin);
402
+ return isPromiseSpec(awaited) ? awaited.value : awaited;
188
403
  }
189
404
  if (node.type === 'BinaryExpression') {
190
405
  if (['===', '!==', '>', '<', '>=', '<=', 'in'].includes(node.operator)) return 'boolean';
@@ -281,6 +496,48 @@ function checkTypes(ast, options = {}) {
281
496
  }
282
497
  return ok;
283
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
+ }
284
541
  const actual = infer(node, env, origin);
285
542
  const ok = specMatches(actual, expected, schemas);
286
543
  if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-ARG'));
@@ -291,6 +548,25 @@ function checkTypes(ast, options = {}) {
291
548
  if (!node || typeof node !== 'object') return;
292
549
  if (node.type === 'MemberExpression' || node.type === 'IndexExpression') {
293
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
+ }
294
570
  checkExpression(node.object, env, origin);
295
571
  if (node.index) checkExpression(node.index, env, origin);
296
572
  return;
@@ -298,16 +574,29 @@ function checkTypes(ast, options = {}) {
298
574
  if (node.type === 'CallExpression') {
299
575
  const fn = functions.get(node.name);
300
576
  if (fn) {
577
+ const bindings = genericBindings(fn, node.args || [], env);
301
578
  const params = (fn.params || []).filter(param => param.name);
302
579
  if (node.args.length !== params.length && !params.some(param => param.type === 'RestElement')) {
303
580
  diagnostics.push(diagnostic(`Intent/function "${node.name}" expects ${params.length} argument(s), received ${node.args.length}.`, origin, 'PLN-TYPE-ARITY'));
304
581
  }
305
582
  node.args.forEach((arg, index) => {
306
583
  const param = params[index];
307
- if (param && param.typeAnnotation) expectedMatchesNode(arg, param.typeAnnotation, env, origin, `Argument ${index + 1} of "${node.name}"`);
584
+ const missingAwait = param && param.typeAnnotation && reportMissingAwait(
585
+ arg, env, param.typeAnnotation, `Argument ${index + 1} of "${node.name}"`
586
+ );
587
+ if (param && param.typeAnnotation && !missingAwait) expectedMatchesNode(arg, substituteGeneric(param.typeAnnotation, bindings), env, origin, `Argument ${index + 1} of "${node.name}"`);
308
588
  checkExpression(arg, env, origin);
309
589
  });
310
590
  } else {
591
+ if (STANDARD_LIBRARY_ALIASES.has(node.name)) {
592
+ const canonical = STANDARD_LIBRARY_ALIASES.get(node.name);
593
+ diagnostics.push(diagnostic(
594
+ `Unknown PlainScript function "${node.name}". It is not a standard-library function. Use "${canonical}(...)" or, for a JavaScript member method, "value.toLowerCase()" / "value.toUpperCase()".`,
595
+ origin,
596
+ 'PLN-NAMESPACE-UNKNOWN',
597
+ { category: 'namespace', explanation: `The canonical standard-library name is ${canonical}.`, suggestion: canonical }
598
+ ));
599
+ }
311
600
  node.args.forEach(arg => checkExpression(arg, env, origin));
312
601
  }
313
602
  return;
@@ -334,6 +623,21 @@ function checkTypes(ast, options = {}) {
334
623
  function narrowEnvironment(env, condition, truthy) {
335
624
  const next = new Map(env);
336
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
+ }
337
641
  if (!left || left.type !== 'Identifier' || !right || right.type !== 'NullLiteral') return;
338
642
  const entry = next.get(left.name);
339
643
  if (!entry || !isOptionalSpec(entry.type)) return;
@@ -348,13 +652,36 @@ function checkTypes(ast, options = {}) {
348
652
  return next;
349
653
  }
350
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
+
351
677
  function checkStatements(statements, env, returnType = null, functionName = null) {
352
678
  for (const node of statements || []) {
353
679
  if (!node) continue;
354
680
  if (node.type === 'RememberStatement' && typeof node.name === 'string') {
355
- if (node.typeAnnotation) expectedMatchesNode(node.value, node.typeAnnotation, env, node, `Variable "${node.name}"`);
681
+ const missingAwait = reportMissingAwait(node.value, env, node.typeAnnotation, `Variable "${node.name}"`);
682
+ if (node.typeAnnotation && !missingAwait) expectedMatchesNode(node.value, node.typeAnnotation, env, node, `Variable "${node.name}"`);
356
683
  const inferred = node.typeAnnotation || infer(node.value, env, node);
357
- env.set(node.name, { type: inferred || 'any', node });
684
+ env.set(node.name, { type: inferred || 'any', node, declared: Boolean(node.typeAnnotation) });
358
685
  symbols.set(node.name, { kind: 'variable', node, type: inferred || 'any' });
359
686
  checkExpression(node.value, env, node);
360
687
  } else if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
@@ -362,10 +689,22 @@ function checkTypes(ast, options = {}) {
362
689
  for (const param of node.params || []) if (param.name) nested.set(param.name, { type: param.typeAnnotation || 'any', node: param });
363
690
  checkStatements(node.body, nested, node.returnType || null, node.name);
364
691
  checkFunctionReturns(node, nested);
692
+ } else if (node.type === 'MatchStatement') {
693
+ checkMatchStatement(node, env);
365
694
  } else if (node.type === 'IfStatement') {
366
695
  checkExpression(node.condition, env, node);
367
696
  checkStatements(node.consequent, narrowEnvironment(env, node.condition, true), returnType, functionName);
368
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);
369
708
  } else if (node.type === 'BecomeStatement') {
370
709
  checkExpression(node.value, env, node);
371
710
  const actual = infer(node.value, env, node);
@@ -374,18 +713,37 @@ function checkTypes(ast, options = {}) {
374
713
  if (entry && entry.type && !specMatches(actual, entry.type, schemas)) {
375
714
  diagnostics.push(diagnostic(`Assignment to "${node.target.name}" expects ${typeName(entry.type)}, received ${typeName(actual)}.`, node, 'PLN-TYPE-ASSIGN'));
376
715
  }
377
- 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
+ }
378
730
  }
379
731
  } else if (node.type === 'GiveStatement' || node.type === 'ReturnStatement') {
380
732
  checkExpression(node.value, env, node);
381
733
  if (returnType && node.value) {
382
734
  const start = diagnostics.length;
383
- expectedMatchesNode(node.value, returnType, env, node, `Function "${functionName}" return`);
735
+ const resolvedReturnType = isPromiseSpec(returnType) ? returnType.value : returnType;
736
+ const missingAwait = reportMissingAwait(node.value, env, resolvedReturnType, `Function "${functionName}" return`);
737
+ if (!missingAwait) expectedMatchesNode(node.value, resolvedReturnType, env, node, `Function "${functionName}" return`);
384
738
  for (let index = start; index < diagnostics.length; index += 1) {
385
739
  const item = diagnostics[index];
386
740
  if (item.code === 'PLN-TYPE-ARG' || item.code === 'PLN-TYPE-ELEMENT' || item.code === 'PLN-TYPE-COLLECTION') item.code = 'PLN-TYPE-RETURN';
387
741
  }
388
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);
389
747
  } else {
390
748
  for (const value of Object.values(node)) {
391
749
  if (value && typeof value === 'object') {
@@ -434,7 +792,12 @@ function checkTypes(ast, options = {}) {
434
792
  }
435
793
 
436
794
  checkStatements(ast.body, new Map());
437
- 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 };
438
801
  }
439
802
 
440
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.0';
4
+ const VERSION = '1.1.5';
5
5
 
6
6
  module.exports = { VERSION };