plainscript-lang 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -131,7 +131,7 @@ done
131
131
  </tr>
132
132
  </table>
133
133
 
134
- **Current version:** `v1.1.0` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
134
+ **Current version:** `v1.1.1` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
135
135
 
136
136
  ---
137
137
 
@@ -261,7 +261,7 @@ For projects that need custom output or source directories, add a `plainscript.c
261
261
  "build": "plainscript build",
262
262
  "prepare": "plainscript build"
263
263
  },
264
- "devDependencies": { "plainscript-lang": "^1.1.0" }
264
+ "devDependencies": { "plainscript-lang": "^1.1.1" }
265
265
  }
266
266
  ```
267
267
 
@@ -365,9 +365,11 @@ All comparison operators:
365
365
  | `is not` | `!==` |
366
366
  | `different from` | `!==` |
367
367
  | `is greater than` / `is above` | `>` |
368
- | `more than` | `>` |
368
+ | `more than` / `is more than` | `>` |
369
369
  | `is less than` / `is below` | `<` |
370
- | `fewer than` | `<` |
370
+ | `fewer than` / `is fewer than` | `<` |
371
+ | `greater than or equal to` / `is more than or equal to` | `>=` |
372
+ | `less than or equal to` | `<=` |
371
373
  | `is at least` | `>=` |
372
374
  | `is at most` | `<=` |
373
375
  | `is empty` | `.length === 0` |
@@ -770,7 +772,7 @@ PlainScript 1.0.2 closes most of the gap with TypeScript-class languages using i
770
772
  | Streams | `writeLine`, `appendLine` |
771
773
  | Collections | `keyMap/mapSet/mapGet/mapHas/mapDelete`, `newSet/addToSet` |
772
774
  | Dynamic modules | `loadModule("./m")` |
773
- | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check <expr> raises "msg"`; run files with `plainscript test` |
775
+ | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check object has field "name"`, and `check <expr> raises "msg"`; run files with `plainscript test` |
774
776
  | Exports | `export <name>` |
775
777
 
776
778
  </details>
@@ -834,6 +836,28 @@ database "app.db" using "wasm" // hard requirement: sql.js
834
836
 
835
837
  The WebAssembly engine persists the whole database to disk after every write, so data survives restarts either way.
836
838
 
839
+ SQL blocks use bound PlainScript value placeholders. `{name}` or
840
+ `{imageHash(image)}` becomes a prepared statement parameter; the resulting value
841
+ is never concatenated into SQL text:
842
+
843
+ ```plainscript
844
+ remember email as request.body.email
845
+ remember rows as query
846
+ SELECT receipt_id FROM receipts WHERE email = {email}
847
+ done
848
+ ```
849
+
850
+ Placeholders are parsed as PlainScript expressions, while raw statement text or
851
+ malformed expressions are rejected at compile time. For complex expressions,
852
+ bind the expression first:
853
+
854
+ ```plainscript
855
+ remember receiptHash as imageHash(image)
856
+ remember rows as query
857
+ SELECT receipt_id FROM receipts WHERE hash = {receiptHash}
858
+ done
859
+ ```
860
+
837
861
  ### HTTP Client
838
862
 
839
863
  ```plainscript
@@ -1359,6 +1383,21 @@ export circleArea
1359
1383
 
1360
1384
  Imports are bundled per entry: `plainscript build` gives every source file its own standalone output under `dist/`, with imported code inlined. Functions, lambdas, records, and modules together are how you build your own vocabulary on top of the core verbs - a new reader puzzle (`validate(body, fields)`) is a one-line call, not a loop.
1361
1385
 
1386
+ ### npm and JavaScript imports
1387
+
1388
+ Named package exports may be given an explicit PlainScript local name:
1389
+
1390
+ ```plainscript
1391
+ import { createHash as hash, randomUUID } from "crypto"
1392
+ show hash
1393
+ ```
1394
+
1395
+ The compiler emits a CommonJS `require` followed by destructuring, so
1396
+ `createHash as hash` becomes the JavaScript binding `{ createHash: hash }`.
1397
+ Unaliased named imports retain their exported name. The same brace syntax is
1398
+ accepted for local PlainScript modules; aliased names become local bindings in
1399
+ the bundled output.
1400
+
1362
1401
  ---
1363
1402
 
1364
1403
  ## Express Integration
@@ -3298,7 +3298,9 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3298
3298
  const runner = [
3299
3299
  `const __tests = [];`,
3300
3300
  `function __check(op, a, b) {`,
3301
- ` const ok = op === 'contains'`,
3301
+ ` const ok = op === 'has-field'`,
3302
+ ` ? a != null && Object.prototype.hasOwnProperty.call(Object(a), b)`,
3303
+ ` : op === 'contains'`,
3302
3304
  ` ? (a instanceof Set ? a.has(b) : String(a).includes(String(b)))`,
3303
3305
  ` : op === 'is'`,
3304
3306
  ` ? a === b`,
@@ -3555,6 +3557,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3555
3557
  }
3556
3558
 
3557
3559
  // v1.0.1 - assertion `check <a> (equals|is|contains|raises) <b>`.
3560
+ // v1.1.1 - `check <object> has field "name"` checks JSON/object shape.
3558
3561
  // For `raises`, `a` is wrapped in a thunk so the expression is evaluated
3559
3562
  // inside the runner's try/catch (its thrown error is the subject).
3560
3563
  case 'CheckStatement': {
@@ -3653,9 +3656,12 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3653
3656
  }
3654
3657
  if (node.names && node.names.length > 0) {
3655
3658
  const reqName = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
3656
- emitRequire(context, node.path, `__pkg_${reqName}`);
3657
- const destructuring = `const { ${node.names.join(', ')} } = __pkg_${reqName};`;
3658
- return `${indent}${destructuring}`;
3659
+ const requireLine = emitRequire(context, node.path, `__pkg_${reqName}`);
3660
+ const bindings = (node.namedImports && node.namedImports.length > 0)
3661
+ ? node.namedImports.map(({ imported, local }) => imported === local ? imported : `${imported}: ${local}`)
3662
+ : node.names;
3663
+ const destructuring = `const { ${bindings.join(', ')} } = __pkg_${reqName};`;
3664
+ return [requireLine, `${indent}${destructuring}`].filter(Boolean).join('\n');
3659
3665
  }
3660
3666
  const pkg = emitRequire(context, node.path, null);
3661
3667
  return pkg ? `${indent}${pkg}` : '';
@@ -3674,7 +3680,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3674
3680
  }
3675
3681
  const modVar = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
3676
3682
  return `${indent}const ${node.namespace} = typeof __module_${modVar} !== 'undefined' ? __module_${modVar} : require(${JSON.stringify(node.path)});`;
3677
- }
3683
+ }
3684
+ if (node.namedImports && node.namedImports.some(({ imported, local }) => imported !== local)) {
3685
+ return node.namedImports
3686
+ .filter(({ imported, local }) => imported !== local)
3687
+ .map(({ imported, local }) => `${indent}const ${local} = ${imported};`)
3688
+ .join('\n');
3689
+ }
3678
3690
  return '';
3679
3691
  }
3680
3692
 
package/compiler/lexer.js CHANGED
@@ -152,6 +152,7 @@ const TOKEN = {
152
152
  PERCENT_ASSIGN: 'PERCENT_ASSIGN', // %=
153
153
  // Literals & identifiers
154
154
  IDENTIFIER: 'IDENTIFIER',
155
+ ESCAPED_IDENTIFIER: 'ESCAPED_IDENTIFIER', // `now`, `prompt`, `list`, etc.
155
156
  STRING: 'STRING',
156
157
  NUMBER: 'NUMBER',
157
158
  TRUE_KW: 'TRUE_KW', // v2.1.1 - boolean literal true
@@ -422,7 +423,14 @@ function tokenize(source) {
422
423
  );
423
424
  }
424
425
  i++; // skip closing backtick
425
- tokens.push({ type: TOKEN.TEMPLATE_STRING, value: content, line: tokenLine, col: tokenCol });
426
+ const escapedIdentifier = /^[A-Za-z_][A-Za-z0-9_]*$/.test(content) &&
427
+ Object.prototype.hasOwnProperty.call(KEYWORDS, content);
428
+ tokens.push({
429
+ type: escapedIdentifier ? TOKEN.ESCAPED_IDENTIFIER : TOKEN.TEMPLATE_STRING,
430
+ value: content,
431
+ line: tokenLine,
432
+ col: tokenCol,
433
+ });
426
434
  continue;
427
435
  }
428
436
 
@@ -53,13 +53,44 @@ const TIME_UNITS = {
53
53
 
54
54
  // v2.1.0 - split raw SQL into placeholder-free text and ordered parameter
55
55
  // names. "{name}" marks a bound parameter; the generator renders "?" for
56
- // SQLite or "$1…" for PostgreSQL.
56
+ // SQLite or "$1…" for PostgreSQL. A value expression is also accepted after
57
+ // parsing it as PlainScript, but its result remains a bound parameter and is
58
+ // never inserted into the SQL text.
57
59
  function extractSqlParams(rawSql) {
58
60
  const params = [];
59
- const sql = String(rawSql).replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => {
61
+ const source = String(rawSql);
62
+ const sql = source.replace(/\{([^{}]*)\}/g, (_match, content) => {
63
+ const name = String(content).trim();
64
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
65
+ if (/[;{}]/.test(name)) {
66
+ throw new Error(
67
+ 'SQL placeholders must contain a PlainScript value expression, not raw statement text.\n\n' +
68
+ `Found "{${content}}". Bind the expression before the query, for example:\n` +
69
+ ' remember receiptHash as imageHash(image)\n' +
70
+ ' query\n SELECT * FROM receipts WHERE hash = {receiptHash}\n done'
71
+ );
72
+ }
73
+ try {
74
+ const expressionAst = parse(tokenize(`remember __sqlParameter as ${name}`));
75
+ if (!expressionAst || expressionAst.body.length !== 1 || expressionAst.body[0].type !== 'RememberStatement') throw new Error('invalid expression');
76
+ } catch (_) {
77
+ throw new Error(
78
+ 'SQL placeholders must contain a valid PlainScript value expression.\n\n' +
79
+ `Found "{${content}}". Bind the expression before the query, for example:\n` +
80
+ ' remember receiptHash as imageHash(image)\n' +
81
+ ' query\n SELECT * FROM receipts WHERE hash = {receiptHash}\n done'
82
+ );
83
+ }
84
+ }
60
85
  params.push(name);
61
86
  return '?';
62
87
  });
88
+ if (/[{}]/.test(sql)) {
89
+ throw new Error(
90
+ 'SQL interpolation contains an unmatched "{" or "}".\n\n' +
91
+ 'Use {name} for a bound PlainScript value; SQL text must not contain raw interpolated expressions.'
92
+ );
93
+ }
63
94
  return { sql, params };
64
95
  }
65
96
 
@@ -148,6 +179,9 @@ function parse(tokens) {
148
179
  function peek() { return tokens[pos]; }
149
180
  function peekAt(offset) { return tokens[pos + offset] || { type: TOKEN.EOF }; }
150
181
  function advance() { return tokens[pos++]; }
182
+ function isIdentifierToken(token) {
183
+ return token && (token.type === TOKEN.IDENTIFIER || token.type === TOKEN.ESCAPED_IDENTIFIER);
184
+ }
151
185
  // v1.0.363 - at a block terminator? A done/together followed by "of" is a
152
186
  // FIELD read ("done of item" - the README todo example), so it never closes a
153
187
  // block. Every statement-bearing body loop must ask this instead of comparing
@@ -529,15 +563,31 @@ function parse(tokens) {
529
563
  return { type: 'BinaryCondition', left, op: '===', right };
530
564
  }
531
565
 
532
- // is more than <expr>
566
+ // is more than [or equal to] <expr>
533
567
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'more' &&
534
568
  (peekAt(1).type === TOKEN.THAN || (peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'than'))) {
535
569
  advance(); // more
536
570
  advance(); // than
571
+ if (peek().type === TOKEN.OR && peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'equal') {
572
+ advance();
573
+ advance();
574
+ if (peek().type === TOKEN.TO || (peek().type === TOKEN.IDENTIFIER && peek().value === 'to')) advance();
575
+ const right = parseBooleanAtom();
576
+ return { type: 'BinaryCondition', left, op: '>=', right };
577
+ }
537
578
  const right = parseBooleanAtom();
538
579
  return { type: 'BinaryCondition', left, op: '>', right };
539
580
  }
540
581
 
582
+ // is fewer than <expr> (natural-language alias for less than)
583
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'fewer' &&
584
+ (peekAt(1).type === TOKEN.THAN || (peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'than'))) {
585
+ advance();
586
+ advance();
587
+ const right = parseBooleanAtom();
588
+ return { type: 'BinaryCondition', left, op: '<', right };
589
+ }
590
+
541
591
  // is above (alias: >)
542
592
  if (peek().type === TOKEN.ABOVE) {
543
593
  advance();
@@ -1391,7 +1441,7 @@ function parse(tokens) {
1391
1441
  // Allow contextual keywords as variable names in remember declarations
1392
1442
  let nameToken = peek();
1393
1443
  const REMEMBER_KEYWORDS = new Set([TOKEN.BACK, TOKEN.TOTAL, TOKEN.REPLY, TOKEN.RESPOND, TOKEN.SEND_BACK, TOKEN.FILE_KW]);
1394
- if (REMEMBER_KEYWORDS.has(nameToken.type) || isSqlWordIdentifier(nameToken)) {
1444
+ if (isIdentifierToken(nameToken) || REMEMBER_KEYWORDS.has(nameToken.type) || isSqlWordIdentifier(nameToken)) {
1395
1445
  advance();
1396
1446
  target = nameToken.value;
1397
1447
  } else {
@@ -1593,7 +1643,7 @@ function parseAsk() {
1593
1643
  const keyword = isDefine ? 'define' : isFunction ? 'function' : 'make';
1594
1644
  // Allow "load" as a function name (it's also a keyword for "load env file")
1595
1645
  const nameToken = peek();
1596
- if (nameToken.type !== TOKEN.IDENTIFIER && nameToken.type !== TOKEN.LOAD) {
1646
+ if (!isIdentifierToken(nameToken) && nameToken.type !== TOKEN.LOAD) {
1597
1647
  throw new Error(makeError(
1598
1648
  `Expected a function name after "${keyword}".${reservedWordHint(nameToken)}\n\nExample:\n ${keyword} greet()\n show "Hello"\n done`,
1599
1649
  nameToken
@@ -1614,7 +1664,9 @@ function parseAsk() {
1614
1664
 
1615
1665
  function parseIntentDeclaration() {
1616
1666
  advance(); // intend
1617
- const nameToken = consume(TOKEN.IDENTIFIER, 'Expected an intent name after "intend".');
1667
+ const nameToken = peek();
1668
+ if (!isIdentifierToken(nameToken)) throw new Error(makeError('Expected an intent name after "intend".', nameToken));
1669
+ advance();
1618
1670
  const name = nameToken.value;
1619
1671
  consume(TOKEN.LPAREN, `Expected "(" after intent name "${name}".`);
1620
1672
  const params = parseParamList();
@@ -1643,6 +1695,11 @@ function parseAsk() {
1643
1695
  }
1644
1696
  function parseTypeAtom() {
1645
1697
  const token = peek();
1698
+ if (token.type === TOKEN.IDENTIFIER && (token.value === 'Promise' || token.value === 'promise')) {
1699
+ advance();
1700
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') advance();
1701
+ return { kind: 'promise', value: parseTypeSpec() };
1702
+ }
1646
1703
  if (token.type === TOKEN.IDENTIFIER && token.value === 'optional') {
1647
1704
  advance();
1648
1705
  return { kind: 'optional', value: parseTypeSpec() };
@@ -2137,7 +2194,9 @@ function parseAsk() {
2137
2194
  // Rest parameter: ...args
2138
2195
  if (peek().type === TOKEN.SPREAD) {
2139
2196
  advance();
2140
- const name = consume(TOKEN.IDENTIFIER, 'Expected a parameter name after "...".').value;
2197
+ const restToken = peek();
2198
+ if (!isIdentifierToken(restToken)) throw new Error(makeError('Expected a parameter name after "...".', restToken));
2199
+ const name = advance().value;
2141
2200
  return { type: 'RestElement', name };
2142
2201
  }
2143
2202
  // Destructuring: [a, b] or {x, y}
@@ -2166,7 +2225,7 @@ function parseAsk() {
2166
2225
  // identifier names when used as a parameter, mirroring `remember`.
2167
2226
  const PARAM_KEYWORDS = new Set([TOKEN.BACK, TOKEN.REPLY, TOKEN.RESPOND, TOKEN.SEND_BACK, TOKEN.FILE_KW]);
2168
2227
  let name;
2169
- if (PARAM_KEYWORDS.has(peek().type)) {
2228
+ if (isIdentifierToken(peek()) || PARAM_KEYWORDS.has(peek().type)) {
2170
2229
  name = advance().value;
2171
2230
  } else {
2172
2231
  name = consume(TOKEN.IDENTIFIER, 'Expected a parameter name.').value;
@@ -2335,6 +2394,14 @@ function parseAsk() {
2335
2394
  // fold `a contains b` into a comparison here.
2336
2395
  const a = parseNullish();
2337
2396
  const opToken = peek();
2397
+ if (opToken.value === 'has' && peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'field') {
2398
+ advance(); // has
2399
+ advance(); // field
2400
+ const field = consume(TOKEN.STRING,
2401
+ 'Expected a field name string after "has field".\n\nExample:\n check data of response has field "status"'
2402
+ ).value;
2403
+ return { type: 'CheckStatement', a, op: 'has-field', b: { type: 'StringLiteral', value: field } };
2404
+ }
2338
2405
  if (!['equals', 'is', 'contains', 'raises'].includes(opToken.value)) {
2339
2406
  throw new Error(makeError(
2340
2407
  'Expected "equals", "is", "contains" or "raises" after the value in a "check".\n\nExample:\n check score equals 42',
@@ -2476,11 +2543,19 @@ function parseAsk() {
2476
2543
  if (peek().type === TOKEN.LBRACE) {
2477
2544
  advance(); // {
2478
2545
  const names = [];
2546
+ const namedImports = [];
2479
2547
  while (true) {
2480
- names.push(consume(
2548
+ const imported = consume(
2481
2549
  TOKEN.IDENTIFIER,
2482
2550
  'Expected an exported name inside the import braces.\n\nExample:\n import { helper } from "./util.pln"'
2483
- ).value);
2551
+ ).value;
2552
+ let local = imported;
2553
+ if (peek().type === TOKEN.AS) {
2554
+ advance();
2555
+ local = consume(TOKEN.IDENTIFIER, 'Expected a local name after "as" in the import braces.').value;
2556
+ }
2557
+ names.push(imported);
2558
+ namedImports.push({ imported, local });
2484
2559
  if (peek().type === TOKEN.COMMA) { advance(); continue; }
2485
2560
  break;
2486
2561
  }
@@ -2492,7 +2567,7 @@ function parseAsk() {
2492
2567
  TOKEN.STRING,
2493
2568
  'Expected a file path string after the import.\n\nExample:\n import { helper } from "./util.pln"'
2494
2569
  ).value;
2495
- return { type: 'ImportStatement', path: filePath, names };
2570
+ return { type: 'ImportStatement', path: filePath, names, namedImports };
2496
2571
  }
2497
2572
 
2498
2573
  // Form 2: bring all from "path" as math / import all as math from "path" / import * as math from "path"
@@ -4242,7 +4317,7 @@ function parseAsk() {
4242
4317
  advance();
4243
4318
  return { type: 'Identifier', name: token.value };
4244
4319
  }
4245
- if (token.type === TOKEN.IDENTIFIER || IDENTIFIER_KEYWORDS.has(token.type) || isSqlWordIdentifier(token)) {
4320
+ if (isIdentifierToken(token) || IDENTIFIER_KEYWORDS.has(token.type) || isSqlWordIdentifier(token)) {
4246
4321
  if (peekAt(1).type === TOKEN.USES || peekAt(1).type === TOKEN.FILLS) {
4247
4322
  const callee = { type: 'Identifier', name: token.value };
4248
4323
  advance();
@@ -4304,7 +4379,7 @@ function parseAsk() {
4304
4379
  function tokenStartsValue(token) {
4305
4380
  return [
4306
4381
  TOKEN.STRING, TOKEN.TEMPLATE_STRING, TOKEN.NUMBER,
4307
- TOKEN.IDENTIFIER, TOKEN.LBRACKET, TOKEN.LBRACE,
4382
+ TOKEN.IDENTIFIER, TOKEN.ESCAPED_IDENTIFIER, TOKEN.LBRACKET, TOKEN.LBRACE,
4308
4383
  TOKEN.TRUE_KW, TOKEN.FALSE_KW, TOKEN.NULL_KW,
4309
4384
  ].includes(token.type);
4310
4385
  }
@@ -4395,7 +4470,7 @@ function parseAsk() {
4395
4470
  // "done" from the block terminator), plus strings ("with space": 1) and numbers
4396
4471
  // ({ 3: "three" }) for data-shaped objects. A keyword is only accepted as a key when an
4397
4472
  // explicit colon follows, so block-terminator usage of "done" can never be misread here.
4398
- const keyIsWord = keyToken.type === TOKEN.IDENTIFIER || keyToken.type === TOKEN.STRING ||
4473
+ const keyIsWord = keyToken.type === TOKEN.IDENTIFIER || keyToken.type === TOKEN.ESCAPED_IDENTIFIER || keyToken.type === TOKEN.STRING ||
4399
4474
  keyToken.type === TOKEN.NUMBER || keyToken.type === TOKEN.BACK;
4400
4475
  const keyIsColonKeyword = keyToken.type !== TOKEN.IDENTIFIER &&
4401
4476
  typeof keyToken.value === 'string' && /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(keyToken.value) &&
@@ -7,8 +7,21 @@
7
7
  const { lowerToIR } = require('./ir');
8
8
 
9
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
+ ]);
10
23
 
11
- function diagnostic(message, node, code = 'PLN-TYPE') {
24
+ function diagnostic(message, node, code = 'PLN-TYPE', details = {}) {
12
25
  const line = node && node.line ? node.line : 1;
13
26
  const column = node && node.col ? node.col : 1;
14
27
  return {
@@ -16,6 +29,7 @@ function diagnostic(message, node, code = 'PLN-TYPE') {
16
29
  source: 'plainscript',
17
30
  code,
18
31
  message,
32
+ ...details,
19
33
  ...(node && node.sourceFile ? { file: node.sourceFile } : {}),
20
34
  range: {
21
35
  start: { line: line - 1, character: column - 1 },
@@ -31,6 +45,7 @@ function typeName(spec) {
31
45
  if (spec.kind === 'optional') return `optional ${typeName(spec.value)}`;
32
46
  if (spec.kind === 'list') return `list of ${typeName(spec.value)}`;
33
47
  if (spec.kind === 'dictionary') return `dictionary of ${typeName(spec.value)}`;
48
+ if (spec.kind === 'promise') return `Promise of ${typeName(spec.value)}`;
34
49
  if (spec.kind === 'union') return spec.values.map(typeName).join(' or ');
35
50
  return 'any';
36
51
  }
@@ -38,6 +53,7 @@ function typeName(spec) {
38
53
  function nameSpec(name) { return { kind: 'name', name }; }
39
54
  function listSpec(value = 'any') { return { kind: 'list', value }; }
40
55
  function dictionarySpec(value = 'any') { return { kind: 'dictionary', value }; }
56
+ function promiseSpec(value = 'any') { return { kind: 'promise', value }; }
41
57
 
42
58
  function isNullSpec(spec) {
43
59
  return spec && ((spec.kind === 'name' && spec.name === 'null') || spec === 'null');
@@ -47,6 +63,10 @@ function isOptionalSpec(spec) {
47
63
  return spec && (spec.kind === 'optional' || (spec.kind === 'union' && spec.values.some(isNullSpec)));
48
64
  }
49
65
 
66
+ function isPromiseSpec(spec) {
67
+ return Boolean(spec && spec.kind === 'promise');
68
+ }
69
+
50
70
  function withoutNull(spec) {
51
71
  if (!spec) return spec;
52
72
  if (spec.kind === 'optional') return spec.value;
@@ -60,6 +80,7 @@ function withoutNull(spec) {
60
80
  function specMatches(actual, expected, schemas) {
61
81
  if (!expected || expected === 'any' || (expected.kind === 'name' && expected.name === 'any') || !actual || actual === 'any') return true;
62
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);
63
84
  if (expected.kind === 'union') return expected.values.some(item => specMatches(actual, item, schemas));
64
85
  if (expected.kind === 'name') {
65
86
  if (expected.name === 'any') return true;
@@ -80,6 +101,9 @@ function specMatches(actual, expected, schemas) {
80
101
  if (!actual || actual.kind !== 'dictionary') return false;
81
102
  return specMatches(actual.value, expected.value, schemas);
82
103
  }
104
+ if (expected.kind === 'promise') {
105
+ return isPromiseSpec(actual) && specMatches(actual.value, expected.value, schemas);
106
+ }
83
107
  return true;
84
108
  }
85
109
 
@@ -111,7 +135,7 @@ function checkTypes(ast, options = {}) {
111
135
  if (!PRIMITIVES.has(spec.name) && !schemas.has(spec.name)) {
112
136
  diagnostics.push(diagnostic(`Unknown type "${spec.name}". Declare it with type ${spec.name} ... done.`, node, 'PLN-TYPE-UNKNOWN'));
113
137
  }
114
- } 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') {
115
139
  addTypeSpecErrors(spec.value, node);
116
140
  } else if (spec.kind === 'union') {
117
141
  spec.values.forEach(value => addTypeSpecErrors(value, node));
@@ -148,6 +172,44 @@ function checkTypes(ast, options = {}) {
148
172
  return field ? field.type : null;
149
173
  }
150
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
+
151
213
  function infer(node, env, origin = node) {
152
214
  if (!node) return 'any';
153
215
  if (node.type === 'Identifier') {
@@ -184,7 +246,15 @@ function checkTypes(ast, options = {}) {
184
246
  }
185
247
  if (node.type === 'CallExpression') {
186
248
  const fn = functions.get(node.name);
187
- return fn && fn.returnType ? fn.returnType : '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;
188
258
  }
189
259
  if (node.type === 'BinaryExpression') {
190
260
  if (['===', '!==', '>', '<', '>=', '<=', 'in'].includes(node.operator)) return 'boolean';
@@ -304,10 +374,22 @@ function checkTypes(ast, options = {}) {
304
374
  }
305
375
  node.args.forEach((arg, index) => {
306
376
  const param = params[index];
307
- if (param && param.typeAnnotation) expectedMatchesNode(arg, param.typeAnnotation, env, origin, `Argument ${index + 1} of "${node.name}"`);
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}"`);
308
381
  checkExpression(arg, env, origin);
309
382
  });
310
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
+ }
311
393
  node.args.forEach(arg => checkExpression(arg, env, origin));
312
394
  }
313
395
  return;
@@ -352,7 +434,8 @@ function checkTypes(ast, options = {}) {
352
434
  for (const node of statements || []) {
353
435
  if (!node) continue;
354
436
  if (node.type === 'RememberStatement' && typeof node.name === 'string') {
355
- if (node.typeAnnotation) expectedMatchesNode(node.value, node.typeAnnotation, env, node, `Variable "${node.name}"`);
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}"`);
356
439
  const inferred = node.typeAnnotation || infer(node.value, env, node);
357
440
  env.set(node.name, { type: inferred || 'any', node });
358
441
  symbols.set(node.name, { kind: 'variable', node, type: inferred || 'any' });
@@ -380,7 +463,9 @@ function checkTypes(ast, options = {}) {
380
463
  checkExpression(node.value, env, node);
381
464
  if (returnType && node.value) {
382
465
  const start = diagnostics.length;
383
- expectedMatchesNode(node.value, returnType, env, node, `Function "${functionName}" return`);
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`);
384
469
  for (let index = start; index < diagnostics.length; index += 1) {
385
470
  const item = diagnostics[index];
386
471
  if (item.code === 'PLN-TYPE-ARG' || item.code === 'PLN-TYPE-ELEMENT' || item.code === 'PLN-TYPE-COLLECTION') item.code = 'PLN-TYPE-RETURN';
@@ -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.1';
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.0.363
7
+ Version: 1.1.1
8
8
 
9
9
  ---
10
10
 
@@ -62,6 +62,14 @@ Line 1, Column 10: Expected a variable name after "remember".
62
62
  Pick a different name (see docs/PLAINSCRIPT-GRAMMAR.md).
63
63
  ```
64
64
 
65
+ Reserved words may be used deliberately by enclosing the word in backticks. The
66
+ escaped form is an identifier, not a template string:
67
+
68
+ ```plainscript
69
+ remember `now` as 1
70
+ show `now`
71
+ ```
72
+
65
73
  ### Operators
66
74
 
67
75
  | Token | Meaning |
@@ -74,6 +82,11 @@ Pick a different name (see docs/PLAINSCRIPT-GRAMMAR.md).
74
82
  | `...` | spread |
75
83
  | `(` `)` `[` `]` `{` `}` `,` `:` | grouping, literals, comma, object colon |
76
84
 
85
+ Natural-language comparisons normalize to the same binary operators. Supported
86
+ forms include `is greater than` / `is more than` (`>`), `is less than` / `is
87
+ fewer than` (`<`), `is greater than or equal to` / `is more than or equal to`
88
+ (`>=`), `is less than or equal to` (`<=`), and `is at least` / `is at most`.
89
+
77
90
  ### Assignment operators
78
91
 
79
92
  | Operator | Meaning |
@@ -219,6 +232,27 @@ checker also validates literal arguments, typed bindings, return contracts,
219
232
  collection elements, nested fields, and known member access. It remains
220
233
  conservative for expressions whose types are unknown.
221
234
 
235
+ ### Async values and Promise contracts
236
+
237
+ Calls to asynchronous functions are tracked as `Promise of T` values. A
238
+ function body containing `wait for` is therefore asynchronous even when its
239
+ resolved return contract is written as `returns text`. Use `wait for` when a
240
+ resolved value is required:
241
+
242
+ ```plainscript
243
+ make verify() returns text
244
+ wait for sleep(10)
245
+ give "verified"
246
+ done
247
+
248
+ remember result as wait for verify()
249
+ ```
250
+
251
+ The checker reports `PLN-ASYNC-MISSING-AWAIT` when a Promise is assigned,
252
+ passed to a typed synchronous parameter, or returned where a resolved value is
253
+ required. Explicit raw contracts may use `returns Promise of text`; the body
254
+ is still checked against the resolved `text` value.
255
+
222
256
  ## 5. Statements and blocks
223
257
 
224
258
  Blocks open with a keyword line and close with `done` **or** `end`. They are
@@ -237,18 +271,73 @@ equivalent; `end` maps to the same terminator as `done` in the lexer.
237
271
  | `switch <value> against` | `->` cases | `done` |
238
272
  | `try` | body with `recover as <err>` / `finally` clauses | `done` |
239
273
  | `web app` / `route <method> "<path>"` / `when someone visits "<path>"` / `listen on <port>` blocks | body | `done` |
240
- | `database "file.db"` SQL blocks (`query`, `insert`, `update`, `delete`, `execute`) | raw SQL | `done` (or `end`) |
274
+ | `database "file.db"` SQL blocks (`query`, `insert`, `update`, `delete`, `execute`) | raw SQL with `{name}` bound parameters | `done` (or `end`) |
241
275
  | `run in parallel` | concurrent statements (each statement's value is awaited and resolved with `Promise.all`, collected in body order) | `done as <name>` |
242
276
  | `when "<event>" happens` | body | `done` |
243
277
  | `every <interval>` / `schedule "<cron>"` | body | `done` |
244
278
  | `websocket server`, `bot`, `whatsapp bot`, `mail transport` | body | `done` |
245
279
  | `stream "<file>" as <line>` | body | `done` |
246
- | `test "<name>"` | `check` / `equals` / `raises` | `done` |
280
+ | `test "<name>"` | `check` / `equals` / `raises` / `has field` | `done` |
247
281
 
248
282
  A `make` body that contains `yield` compiles to a generator function
249
- (`function*`). SQL block text is passed through verbatim to SQLite.
283
+ (`function*`). SQL block text is passed through to the selected database driver,
284
+ except for safe PlainScript parameter placeholders.
285
+
286
+ Native tests can assert the shape of JSON-like records with
287
+ `check data of response has field "status"`. The assertion checks for an own
288
+ property and fails when the value is null or the field is absent.
289
+
290
+ ### SQL interpolation
291
+
292
+ SQL placeholders use a PlainScript value expression inside braces. The compiler
293
+ replaces `{name}` or `{imageHash(image)}` with a driver parameter marker and
294
+ passes the resulting value separately to the prepared statement; values are
295
+ never concatenated into SQL text.
296
+
297
+ ```plainscript
298
+ remember email as request.body.email
299
+ remember rows as query
300
+ SELECT receipt_id FROM receipts WHERE email = {email}
301
+ done
302
+ ```
303
+
304
+ Expressions are parsed as PlainScript before compilation. Malformed or raw
305
+ statement text is rejected at compile time; for example, this is invalid:
306
+
307
+ ```text
308
+ {imageHash(image); DROP TABLE receipts}
309
+ ```
310
+
311
+ For complex expressions, binding first is still recommended because it makes
312
+ the source and inferred value easier to read:
313
+
314
+ ```plainscript
315
+ remember receiptHash as imageHash(image)
316
+ remember rows as query
317
+ SELECT receipt_id FROM receipts WHERE hash = {receiptHash}
318
+ done
319
+ ```
320
+
321
+ The same binding rule applies to `query`, `insert`, `update`, `delete`, and
322
+ `execute`. SQL injection attempts supplied as values remain data because the
323
+ prepared statement receives them as parameters.
324
+
325
+ ## 6. Module and npm imports
326
+
327
+ Selective imports may rename an exported symbol with `as`:
328
+
329
+ ```plainscript
330
+ import { createHash as hash, randomUUID } from "crypto"
331
+ ```
332
+
333
+ For npm packages, the compiler emits a CommonJS `require` and destructures the
334
+ requested exports. The example creates local bindings named `hash` and
335
+ `randomUUID`, while the package exports remain `createHash` and `randomUUID`.
336
+ The same syntax works for local `.pln` modules; the bundler creates the alias
337
+ after resolving the dependency. A plain `import { name } from ...` keeps the
338
+ exported name unchanged.
250
339
 
251
- ## 6. Expressions
340
+ ## 7. Expressions
252
341
 
253
342
  Recursive-descent parsing with precedence. Member access uses `of`:
254
343
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plainscript-lang",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "PlainScript - an Intent-Oriented Programming Language. When even a simple sentence can be code.",
5
5
  "main": "compiler/cli.js",
6
6
  "bin": {