plainscript-lang 1.0.363 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,27 @@
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
- function diagnostic(message, node, code = 'PLN-TYPE') {
9
+ const PRIMITIVES = new Set(['any', 'number', 'text', 'boolean', 'null', 'object', 'list', 'dictionary']);
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
+ ]);
16
+ const AUTO_AWAIT_CALLS = new Set(['fetchJson', 'fetchBytes']);
17
+ const STANDARD_LIBRARY_ALIASES = new Map([
18
+ ['lower', 'lowercase'],
19
+ ['upper', 'uppercase'],
20
+ ['to_lower', 'lowercase'],
21
+ ['to_upper', 'uppercase'],
22
+ ]);
23
+
24
+ function diagnostic(message, node, code = 'PLN-TYPE', details = {}) {
10
25
  const line = node && node.line ? node.line : 1;
11
26
  const column = node && node.col ? node.col : 1;
12
27
  return {
@@ -14,6 +29,8 @@ function diagnostic(message, node, code = 'PLN-TYPE') {
14
29
  source: 'plainscript',
15
30
  code,
16
31
  message,
32
+ ...details,
33
+ ...(node && node.sourceFile ? { file: node.sourceFile } : {}),
17
34
  range: {
18
35
  start: { line: line - 1, character: column - 1 },
19
36
  end: { line: line - 1, character: column },
@@ -23,35 +40,70 @@ function diagnostic(message, node, code = 'PLN-TYPE') {
23
40
 
24
41
  function typeName(spec) {
25
42
  if (!spec) return 'any';
43
+ if (typeof spec === 'string') return spec;
26
44
  if (spec.kind === 'name') return spec.name;
27
45
  if (spec.kind === 'optional') return `optional ${typeName(spec.value)}`;
28
46
  if (spec.kind === 'list') return `list of ${typeName(spec.value)}`;
29
47
  if (spec.kind === 'dictionary') return `dictionary of ${typeName(spec.value)}`;
48
+ if (spec.kind === 'promise') return `Promise of ${typeName(spec.value)}`;
30
49
  if (spec.kind === 'union') return spec.values.map(typeName).join(' or ');
31
50
  return 'any';
32
51
  }
33
52
 
53
+ function nameSpec(name) { return { kind: 'name', name }; }
54
+ function listSpec(value = 'any') { return { kind: 'list', value }; }
55
+ function dictionarySpec(value = 'any') { return { kind: 'dictionary', value }; }
56
+ function promiseSpec(value = 'any') { return { kind: 'promise', value }; }
57
+
34
58
  function isNullSpec(spec) {
35
- return spec && spec.kind === 'name' && spec.name === 'null';
59
+ return spec && ((spec.kind === 'name' && spec.name === 'null') || spec === 'null');
36
60
  }
37
61
 
38
62
  function isOptionalSpec(spec) {
39
63
  return spec && (spec.kind === 'optional' || (spec.kind === 'union' && spec.values.some(isNullSpec)));
40
64
  }
41
65
 
66
+ function isPromiseSpec(spec) {
67
+ return Boolean(spec && spec.kind === 'promise');
68
+ }
69
+
70
+ function withoutNull(spec) {
71
+ if (!spec) return spec;
72
+ if (spec.kind === 'optional') return spec.value;
73
+ if (spec.kind === 'union') {
74
+ const values = spec.values.filter(value => !isNullSpec(value));
75
+ return values.length === 1 ? values[0] : { kind: 'union', values };
76
+ }
77
+ return spec;
78
+ }
79
+
42
80
  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);
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);
45
84
  if (expected.kind === 'union') return expected.values.some(item => specMatches(actual, item, schemas));
46
85
  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';
86
+ if (expected.name === 'any') return true;
87
+ if (expected.name === 'null') return isNullSpec(actual);
88
+ if (expected.name === 'object') return typeName(actual) === 'object' || typeName(actual) === 'dictionary';
89
+ if (expected.name === 'list' || expected.name === 'dictionary') return typeName(actual) === expected.name || actual.kind === expected.name;
90
+ if (typeof actual === 'string') return expected.name === actual;
91
+ if (actual.kind === 'name') return expected.name === actual.name;
92
+ return schemas.has(expected.name) && (typeName(actual) === 'object' || actual.kind === 'name');
93
+ }
94
+ if (expected.kind === 'list') {
95
+ if (actual === 'list') return true;
96
+ if (!actual || actual.kind !== 'list') return false;
97
+ return specMatches(actual.value, expected.value, schemas);
98
+ }
99
+ if (expected.kind === 'dictionary') {
100
+ if (actual === 'dictionary' || actual === 'object') return true;
101
+ if (!actual || actual.kind !== 'dictionary') return false;
102
+ return specMatches(actual.value, expected.value, schemas);
103
+ }
104
+ if (expected.kind === 'promise') {
105
+ return isPromiseSpec(actual) && specMatches(actual.value, expected.value, schemas);
106
+ }
55
107
  return true;
56
108
  }
57
109
 
@@ -80,11 +132,10 @@ function checkTypes(ast, options = {}) {
80
132
  function addTypeSpecErrors(spec, node) {
81
133
  if (!spec) return;
82
134
  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)) {
135
+ if (!PRIMITIVES.has(spec.name) && !schemas.has(spec.name)) {
85
136
  diagnostics.push(diagnostic(`Unknown type "${spec.name}". Declare it with type ${spec.name} ... done.`, node, 'PLN-TYPE-UNKNOWN'));
86
137
  }
87
- } else if (spec.kind === 'optional' || spec.kind === 'list' || spec.kind === 'dictionary') {
138
+ } else if (spec.kind === 'optional' || spec.kind === 'list' || spec.kind === 'dictionary' || spec.kind === 'promise') {
88
139
  addTypeSpecErrors(spec.value, node);
89
140
  } else if (spec.kind === 'union') {
90
141
  spec.values.forEach(value => addTypeSpecErrors(value, node));
@@ -95,12 +146,13 @@ function checkTypes(ast, options = {}) {
95
146
  if (node.type === 'TypeDeclaration') {
96
147
  if (schemas.has(node.name)) diagnostics.push(diagnostic(`Type "${node.name}" is declared more than once.`, node, 'PLN-TYPE-DUPLICATE'));
97
148
  schemas.set(node.name, node);
149
+ symbols.set(node.name, { kind: 'type', node, type: nameSpec(node.name) });
98
150
  }
99
151
  if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
100
152
  functions.set(node.name, node);
101
- symbols.set(node.name, { kind: node.type === 'IntentDeclaration' ? 'intent' : 'function', node });
153
+ symbols.set(node.name, { kind: node.type === 'IntentDeclaration' ? 'intent' : 'function', node, type: node.returnType || 'any' });
102
154
  }
103
- if (node.type === 'RememberStatement' && typeof node.name === 'string') symbols.set(node.name, { kind: 'variable', node });
155
+ if (node.type === 'RememberStatement' && typeof node.name === 'string') symbols.set(node.name, { kind: 'variable', node, type: node.typeAnnotation || 'any' });
104
156
  }
105
157
 
106
158
  for (const node of ast.body || []) {
@@ -108,10 +160,10 @@ function checkTypes(ast, options = {}) {
108
160
  for (const field of node.fields || []) addTypeSpecErrors(field.type, field);
109
161
  }
110
162
  if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
111
- for (const param of node.params || []) {
112
- if (param.typeAnnotation) addTypeSpecErrors(param.typeAnnotation, node);
113
- }
163
+ for (const param of node.params || []) if (param.typeAnnotation) addTypeSpecErrors(param.typeAnnotation, param);
164
+ if (node.returnType) addTypeSpecErrors(node.returnType, node);
114
165
  }
166
+ if (node.type === 'RememberStatement' && node.typeAnnotation) addTypeSpecErrors(node.typeAnnotation, node);
115
167
  }
116
168
 
117
169
  function fieldSpec(schemaName, fieldName) {
@@ -120,36 +172,197 @@ function checkTypes(ast, options = {}) {
120
172
  return field ? field.type : null;
121
173
  }
122
174
 
175
+ function containsAsync(node, seen = new Set()) {
176
+ if (!node || typeof node !== 'object' || seen.has(node)) return false;
177
+ seen.add(node);
178
+ if (node.type === 'AwaitExpression') return true;
179
+ if (node.type === 'CallExpression' && (ASYNC_CALLS.has(node.name) ||
180
+ (node.callee && node.callee.type === 'MemberExpression' &&
181
+ ASYNC_CALLS.has(`${node.callee.object.name}.${node.callee.property}`)))) return true;
182
+ return Object.values(node).some(value => Array.isArray(value)
183
+ ? value.some(item => containsAsync(item, seen))
184
+ : value && typeof value === 'object' && containsAsync(value, seen));
185
+ }
186
+
187
+ function functionReturnType(fn) {
188
+ const declared = fn && fn.returnType ? fn.returnType : 'any';
189
+ if (isPromiseSpec(declared)) return declared;
190
+ return containsAsync(fn && fn.body) ? promiseSpec(declared) : declared;
191
+ }
192
+
193
+ function isPromiseProducing(node, env) {
194
+ return isPromiseSpec(infer(node, env, node));
195
+ }
196
+
197
+ function isAutoAwaitedCall(node) {
198
+ return node && node.type === 'CallExpression' && AUTO_AWAIT_CALLS.has(node.name);
199
+ }
200
+
201
+ function reportMissingAwait(node, env, expected, label) {
202
+ if (!node || node.type === 'AwaitExpression' || !isPromiseProducing(node, env) || isAutoAwaitedCall(node)) return false;
203
+ if (expected && (isPromiseSpec(expected) || typeName(expected) === 'any')) return false;
204
+ const producer = node.type === 'CallExpression' ? node.name : 'async expression';
205
+ diagnostics.push(diagnostic(
206
+ `${label} receives a Promise from "${producer}". Use "wait for" to resolve it.\nExample: remember result as wait for ${producer}(...).`,
207
+ node,
208
+ 'PLN-ASYNC-MISSING-AWAIT'
209
+ ));
210
+ return true;
211
+ }
212
+
123
213
  function infer(node, env, origin = node) {
124
214
  if (!node) return 'any';
125
- const literal = literalType(node);
126
- if (literal) return literal;
127
215
  if (node.type === 'Identifier') {
128
216
  const entry = env.get(node.name) || symbols.get(node.name);
129
217
  return entry && entry.type ? entry.type : 'any';
130
218
  }
219
+ const literal = literalType(node);
220
+ if (literal === 'list') {
221
+ const elements = (node.elements || []).filter(item => item && item.type !== 'SpreadElement').map(item => infer(item, env, origin));
222
+ const first = elements[0] || 'any';
223
+ return listSpec(elements.every(item => specMatches(item, first, schemas)) ? first : 'any');
224
+ }
225
+ if (literal === 'object') return node.type === 'ObjectLiteral' ? dictionarySpec('any') : 'object';
226
+ if (literal) return literal;
131
227
  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';
228
+ let objectType = infer(node.object, env, origin);
229
+ if (isOptionalSpec(objectType)) {
230
+ diagnostics.push(diagnostic(`Value may be null before accessing field "${node.property}". Check it first.`, origin, 'PLN-TYPE-OPTIONAL'));
231
+ objectType = withoutNull(objectType);
232
+ }
233
+ const schemaName = objectType && objectType.kind === 'name' ? objectType.name : objectType;
234
+ if (schemaName && schemas.has(schemaName)) {
235
+ const field = fieldSpec(schemaName, node.property);
236
+ if (!field) diagnostics.push(diagnostic(`Type "${schemaName}" has no field named "${node.property}".`, origin, 'PLN-TYPE-FIELD'));
237
+ return field || 'any';
137
238
  }
239
+ if (objectType && objectType.kind === 'dictionary') return objectType.value;
240
+ return 'any';
241
+ }
242
+ if (node.type === 'IndexExpression') {
243
+ const objectType = infer(node.object, env, origin);
244
+ if (objectType && (objectType.kind === 'list' || objectType.kind === 'dictionary')) return objectType.value;
138
245
  return 'any';
139
246
  }
140
247
  if (node.type === 'CallExpression') {
141
248
  const fn = functions.get(node.name);
142
- if (fn) return 'any';
249
+ if (fn) return functionReturnType(fn);
250
+ if (ASYNC_CALLS.has(node.name)) return promiseSpec('any');
251
+ if (node.callee && node.callee.type === 'MemberExpression' &&
252
+ ASYNC_CALLS.has(`${node.callee.object.name}.${node.callee.property}`)) return promiseSpec('any');
253
+ return 'any';
254
+ }
255
+ if (node.type === 'AwaitExpression') {
256
+ const awaited = infer(node.value, env, origin);
257
+ return isPromiseSpec(awaited) ? awaited.value : awaited;
258
+ }
259
+ if (node.type === 'BinaryExpression') {
260
+ if (['===', '!==', '>', '<', '>=', '<=', 'in'].includes(node.operator)) return 'boolean';
261
+ const left = infer(node.left, env, origin);
262
+ const right = infer(node.right, env, origin);
263
+ if (node.operator === '+' && (typeName(left) === 'text' || typeName(right) === 'text')) return 'text';
264
+ if (['+', '-', '*', '/', '%'].includes(node.operator) && typeName(left) === 'number' && typeName(right) === 'number') return 'number';
143
265
  return 'any';
144
266
  }
267
+ if (node.type === 'ConditionalExpression') {
268
+ const left = infer(node.consequent, env, origin);
269
+ const right = infer(node.alternate, env, origin);
270
+ return typeName(left) === typeName(right) ? left : { kind: 'union', values: [left, right] };
271
+ }
272
+ if (node.type === 'ConditionExpression' || node.type === 'BinaryCondition' || node.type === 'UnaryCondition' ||
273
+ node.type === 'BetweenCondition' || node.type === 'StringCondition' || node.type === 'InCondition' ||
274
+ node.type === 'NotInCondition' || node.type === 'LogicalCondition') return 'boolean';
145
275
  return 'any';
146
276
  }
147
277
 
278
+ function expectedMatchesNode(node, expected, env, origin, path, emit = true) {
279
+ if (!node || !expected) return true;
280
+ if (expected.kind === 'optional') {
281
+ if (node.type === 'NullLiteral') return true;
282
+ return expectedMatchesNode(node, expected.value, env, origin, path, emit);
283
+ }
284
+ if (expected.kind === 'union') {
285
+ const start = diagnostics.length;
286
+ for (const option of expected.values) {
287
+ diagnostics.length = start;
288
+ if (expectedMatchesNode(node, option, env, origin, path, false)) {
289
+ diagnostics.length = start;
290
+ return expectedMatchesNode(node, option, env, origin, path, emit);
291
+ }
292
+ }
293
+ diagnostics.length = start;
294
+ if (emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(infer(node, env, origin))}.`, origin, 'PLN-TYPE-ELEMENT'));
295
+ return false;
296
+ }
297
+ if (expected.kind === 'list') {
298
+ const actual = infer(node, env, origin);
299
+ if (node.type !== 'ArrayLiteral') {
300
+ const ok = specMatches(actual, expected, schemas);
301
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-COLLECTION'));
302
+ return ok;
303
+ }
304
+ let ok = true;
305
+ (node.elements || []).forEach((element, index) => {
306
+ if (element && element.type === 'SpreadElement') return;
307
+ if (!expectedMatchesNode(element, expected.value, env, origin, `${path || 'Collection'} element ${index + 1}`, emit)) ok = false;
308
+ });
309
+ return ok;
310
+ }
311
+ if (expected.kind === 'dictionary') {
312
+ const actual = infer(node, env, origin);
313
+ if (node.type !== 'ObjectLiteral' && node.type !== 'InlineObjectLiteral') {
314
+ const ok = specMatches(actual, expected, schemas);
315
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-COLLECTION'));
316
+ return ok;
317
+ }
318
+ let ok = true;
319
+ (node.properties || []).forEach(property => {
320
+ if (property.type === 'SpreadProperty') return;
321
+ if (!expectedMatchesNode(property.value, expected.value, env, origin, `${path || 'Dictionary'} value "${property.key}"`, emit)) ok = false;
322
+ });
323
+ return ok;
324
+ }
325
+ if (expected.kind === 'name' && schemas.has(expected.name) &&
326
+ (node.type === 'InlineObjectLiteral' || node.type === 'ObjectLiteral')) {
327
+ const schema = schemas.get(expected.name);
328
+ const properties = new Map((node.properties || []).map(property => [property.key, property]));
329
+ let ok = true;
330
+ for (const field of schema.fields || []) {
331
+ const property = properties.get(field.key);
332
+ if (!property) {
333
+ if (!isOptionalSpec(field.type)) {
334
+ if (emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}is missing required field "${field.key}" for type "${expected.name}".`, origin, 'PLN-TYPE-FIELD'));
335
+ ok = false;
336
+ }
337
+ continue;
338
+ }
339
+ const start = diagnostics.length;
340
+ if (!expectedMatchesNode(property.value, field.type, env, origin, `${path ? `${path} ` : ''}field "${field.key}"`, emit)) ok = false;
341
+ for (let index = start; index < diagnostics.length; index += 1) {
342
+ const item = diagnostics[index];
343
+ if (item.code === 'PLN-TYPE-ARG' || item.code === 'PLN-TYPE-ELEMENT' || item.code === 'PLN-TYPE-COLLECTION') item.code = 'PLN-TYPE-FIELD';
344
+ }
345
+ }
346
+ for (const property of node.properties || []) {
347
+ if (!(schema.fields || []).some(field => field.key === property.key)) {
348
+ if (emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}type "${expected.name}" has no field named "${property.key}".`, origin, 'PLN-TYPE-FIELD'));
349
+ ok = false;
350
+ }
351
+ }
352
+ return ok;
353
+ }
354
+ const actual = infer(node, env, origin);
355
+ const ok = specMatches(actual, expected, schemas);
356
+ if (!ok && emit) diagnostics.push(diagnostic(`${path ? `${path} ` : ''}expects ${typeName(expected)}, received ${typeName(actual)}.`, origin, 'PLN-TYPE-ARG'));
357
+ return ok;
358
+ }
359
+
148
360
  function checkExpression(node, env, origin = node) {
149
361
  if (!node || typeof node !== 'object') return;
150
- if (node.type === 'MemberExpression') {
362
+ if (node.type === 'MemberExpression' || node.type === 'IndexExpression') {
151
363
  infer(node, env, origin);
152
364
  checkExpression(node.object, env, origin);
365
+ if (node.index) checkExpression(node.index, env, origin);
153
366
  return;
154
367
  }
155
368
  if (node.type === 'CallExpression') {
@@ -161,15 +374,35 @@ function checkTypes(ast, options = {}) {
161
374
  }
162
375
  node.args.forEach((arg, index) => {
163
376
  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);
377
+ const missingAwait = param && param.typeAnnotation && reportMissingAwait(
378
+ arg, env, param.typeAnnotation, `Argument ${index + 1} of "${node.name}"`
379
+ );
380
+ if (param && param.typeAnnotation && !missingAwait) expectedMatchesNode(arg, param.typeAnnotation, env, origin, `Argument ${index + 1} of "${node.name}"`);
381
+ checkExpression(arg, env, origin);
170
382
  });
383
+ } else {
384
+ if (STANDARD_LIBRARY_ALIASES.has(node.name)) {
385
+ const canonical = STANDARD_LIBRARY_ALIASES.get(node.name);
386
+ diagnostics.push(diagnostic(
387
+ `Unknown PlainScript function "${node.name}". It is not a standard-library function. Use "${canonical}(...)" or, for a JavaScript member method, "value.toLowerCase()" / "value.toUpperCase()".`,
388
+ origin,
389
+ 'PLN-NAMESPACE-UNKNOWN',
390
+ { category: 'namespace', explanation: `The canonical standard-library name is ${canonical}.`, suggestion: canonical }
391
+ ));
392
+ }
393
+ node.args.forEach(arg => checkExpression(arg, env, origin));
171
394
  }
172
- node.args.forEach(arg => checkExpression(arg, env, origin));
395
+ return;
396
+ }
397
+ if (node.type === 'BinaryExpression') {
398
+ checkExpression(node.left, env, origin);
399
+ checkExpression(node.right, env, origin);
400
+ return;
401
+ }
402
+ if (node.type === 'ConditionalExpression') {
403
+ checkExpression(node.condition, env, origin);
404
+ checkExpression(node.consequent, env, origin);
405
+ checkExpression(node.alternate, env, origin);
173
406
  return;
174
407
  }
175
408
  for (const value of Object.values(node)) {
@@ -180,54 +413,64 @@ function checkTypes(ast, options = {}) {
180
413
  }
181
414
  }
182
415
 
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;
416
+ function narrowEnvironment(env, condition, truthy) {
417
+ const next = new Map(env);
418
+ function apply(left, operator, right) {
419
+ if (!left || left.type !== 'Identifier' || !right || right.type !== 'NullLiteral') return;
420
+ const entry = next.get(left.name);
421
+ if (!entry || !isOptionalSpec(entry.type)) return;
422
+ const isNonNull = operator === 'is not' || operator === '!==' || operator === 'different from';
423
+ if (truthy === isNonNull) next.set(left.name, { ...entry, type: withoutNull(entry.type) });
195
424
  }
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
- }
425
+ if (condition && condition.type === 'ConditionExpression') return narrowEnvironment(next, condition.value, truthy);
426
+ if (condition && condition.type === 'BinaryCondition') apply(condition.left, condition.op, condition.right);
427
+ if (condition && condition.type === 'LogicalCondition' && condition.op === 'and' && truthy) {
428
+ narrowEnvironment(narrowEnvironment(next, condition.left, true), condition.right, true).forEach((value, key) => next.set(key, value));
215
429
  }
430
+ return next;
216
431
  }
217
432
 
218
- function checkStatements(statements, env) {
433
+ function checkStatements(statements, env, returnType = null, functionName = null) {
219
434
  for (const node of statements || []) {
220
435
  if (!node) continue;
221
436
  if (node.type === 'RememberStatement' && typeof node.name === 'string') {
222
- const type = literalType(node.value);
223
- env.set(node.name, { type: type || 'any', node });
437
+ const missingAwait = reportMissingAwait(node.value, env, node.typeAnnotation, `Variable "${node.name}"`);
438
+ if (node.typeAnnotation && !missingAwait) expectedMatchesNode(node.value, node.typeAnnotation, env, node, `Variable "${node.name}"`);
439
+ const inferred = node.typeAnnotation || infer(node.value, env, node);
440
+ env.set(node.name, { type: inferred || 'any', node });
441
+ symbols.set(node.name, { kind: 'variable', node, type: inferred || 'any' });
224
442
  checkExpression(node.value, env, node);
225
443
  } else if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
226
444
  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 });
445
+ for (const param of node.params || []) if (param.name) nested.set(param.name, { type: param.typeAnnotation || 'any', node: param });
446
+ checkStatements(node.body, nested, node.returnType || null, node.name);
447
+ checkFunctionReturns(node, nested);
448
+ } else if (node.type === 'IfStatement') {
449
+ checkExpression(node.condition, env, node);
450
+ checkStatements(node.consequent, narrowEnvironment(env, node.condition, true), returnType, functionName);
451
+ if (node.alternate) checkStatements(node.alternate, narrowEnvironment(env, node.condition, false), returnType, functionName);
452
+ } else if (node.type === 'BecomeStatement') {
453
+ checkExpression(node.value, env, node);
454
+ const actual = infer(node.value, env, node);
455
+ if (node.target && node.target.type === 'Identifier') {
456
+ const entry = env.get(node.target.name);
457
+ if (entry && entry.type && !specMatches(actual, entry.type, schemas)) {
458
+ diagnostics.push(diagnostic(`Assignment to "${node.target.name}" expects ${typeName(entry.type)}, received ${typeName(actual)}.`, node, 'PLN-TYPE-ASSIGN'));
459
+ }
460
+ if (entry && node.op === '=') env.set(node.target.name, { ...entry, type: actual });
461
+ }
462
+ } else if (node.type === 'GiveStatement' || node.type === 'ReturnStatement') {
463
+ checkExpression(node.value, env, node);
464
+ if (returnType && node.value) {
465
+ const start = diagnostics.length;
466
+ const resolvedReturnType = isPromiseSpec(returnType) ? returnType.value : returnType;
467
+ const missingAwait = reportMissingAwait(node.value, env, resolvedReturnType, `Function "${functionName}" return`);
468
+ if (!missingAwait) expectedMatchesNode(node.value, resolvedReturnType, env, node, `Function "${functionName}" return`);
469
+ for (let index = start; index < diagnostics.length; index += 1) {
470
+ const item = diagnostics[index];
471
+ if (item.code === 'PLN-TYPE-ARG' || item.code === 'PLN-TYPE-ELEMENT' || item.code === 'PLN-TYPE-COLLECTION') item.code = 'PLN-TYPE-RETURN';
472
+ }
229
473
  }
230
- checkStatements(node.body, nested);
231
474
  } else {
232
475
  for (const value of Object.values(node)) {
233
476
  if (value && typeof value === 'object') {
@@ -239,8 +482,44 @@ function checkTypes(ast, options = {}) {
239
482
  }
240
483
  }
241
484
 
485
+ function collectReturns(statements, result = []) {
486
+ for (const node of statements || []) {
487
+ if (!node || typeof node !== 'object') continue;
488
+ if (node.type === 'GiveStatement' || node.type === 'ReturnStatement') result.push(node);
489
+ for (const key of ['body', 'consequent', 'alternate', 'handlers', 'finalizer']) {
490
+ const child = node[key];
491
+ if (Array.isArray(child)) collectReturns(child, result);
492
+ else if (child && typeof child === 'object') collectReturns([child], result);
493
+ }
494
+ }
495
+ return result;
496
+ }
497
+
498
+ function checkFunctionReturns(fn, env) {
499
+ if (!fn.returnType) return;
500
+ const returns = collectReturns(fn.body);
501
+ if (returns.length === 0) {
502
+ diagnostics.push(diagnostic(`Function "${fn.name}" declares ${typeName(fn.returnType)} but does not return a value.`, fn, 'PLN-TYPE-RETURN-MISSING'));
503
+ return;
504
+ }
505
+ if (returns.some(statement => !statement.value) && !isOptionalSpec(fn.returnType)) {
506
+ diagnostics.push(diagnostic(`Function "${fn.name}" returns ${typeName(fn.returnType)} but this return has no value.`, fn, 'PLN-TYPE-RETURN'));
507
+ }
508
+ }
509
+
510
+ // Imports are resolved by the bundler before this checker receives a graph.
511
+ // A flattened graph therefore exposes declarations from every local module;
512
+ // report only names that are genuinely absent and ignore npm imports.
513
+ for (const node of ast.body || []) {
514
+ if (node.type !== 'ImportStatement' || !node.path || !node.path.endsWith('.pln') && !node.path.startsWith('.') && !node.path.startsWith('@/') && !node.path.startsWith('/')) continue;
515
+ const imported = node.names || (node.defaultImport ? [node.defaultImport] : []);
516
+ for (const name of imported) {
517
+ if (!symbols.has(name)) diagnostics.push(diagnostic(`Imported symbol "${name}" was not found in the resolved module graph.`, node, 'PLN-MODULE-UNKNOWN'));
518
+ }
519
+ }
520
+
242
521
  checkStatements(ast.body, new Map());
243
522
  return { diagnostics, ir };
244
523
  }
245
524
 
246
- module.exports = { checkTypes, typeName };
525
+ 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.1';
5
5
 
6
6
  module.exports = { VERSION };