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.
@@ -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 {
@@ -1403,10 +1453,35 @@ function parse(tokens) {
1403
1453
  nameLine = nameToken.line;
1404
1454
  }
1405
1455
 
1456
+ let typeAnnotation = null;
1457
+ // Typed mutable binding: `let users as list of User is [...]`. The
1458
+ // lookahead keeps legacy `let value as 42` default/initializer syntax
1459
+ // unchanged because only a recognized type expression followed by `is` or
1460
+ // `be` enters this path.
1461
+ if (isLet && peek().type === TOKEN.AS && isTypeNameStart(peekAt(1))) {
1462
+ const saved = pos;
1463
+ advance();
1464
+ try {
1465
+ const candidate = parseTypeSpec();
1466
+ if (peek().type === TOKEN.IS || peek().type === TOKEN.BE) {
1467
+ typeAnnotation = candidate;
1468
+ advance();
1469
+ } else {
1470
+ pos = saved;
1471
+ }
1472
+ } catch (_) {
1473
+ pos = saved;
1474
+ }
1475
+ }
1476
+
1406
1477
  // Object literal: next token is IDENTIFIER (except dictionary/map) followed by IS or BE
1407
1478
  if (peek().type === TOKEN.IDENTIFIER && peek().value !== 'dictionary' && peek().value !== 'map' && (peekAt(1).type === TOKEN.IS || peekAt(1).type === TOKEN.BE) && !isObjectShorthandAmbiguousWithComparison()) {
1408
1479
  const init = parseInlineObjectLiteral(false);
1409
- return { type: 'RememberStatement', name: target, value: init, isLet, isConstant: !isLet };
1480
+ return { type: 'RememberStatement', name: target, value: init, typeAnnotation, isLet, isConstant: !isLet };
1481
+ }
1482
+
1483
+ if (typeAnnotation) {
1484
+ return { type: 'RememberStatement', name: target, value: parseExpression(), typeAnnotation, isLet, isConstant: !isLet };
1410
1485
  }
1411
1486
 
1412
1487
  // "let" uses "is" or "be" for simple vars, but also accepts "as" for both simple and destructuring
@@ -1417,7 +1492,7 @@ function parse(tokens) {
1417
1492
  // The statement's name token is on the declaration line; a next token on a
1418
1493
  // LATER line means no initializer follows on that line.
1419
1494
  if (!isDestructuring && typeof target === 'string' && peek().line > nameLine) {
1420
- return { type: 'RememberStatement', name: target, value: null, isLet, isConstant: !isLet };
1495
+ return { type: 'RememberStatement', name: target, value: null, typeAnnotation, isLet, isConstant: !isLet };
1421
1496
  }
1422
1497
  const assignToken = isLet ? ((peek().type === TOKEN.IS || peek().type === TOKEN.BE) ? peek().type : TOKEN.AS) : TOKEN.AS;
1423
1498
  const expectedKeyword = (isLet && (peek().type === TOKEN.IS || peek().type === TOKEN.BE)) ? (peek().type === TOKEN.BE ? 'be' : 'is') : 'as';
@@ -1428,7 +1503,7 @@ function parse(tokens) {
1428
1503
 
1429
1504
  // Object literal: next token is IDENTIFIER followed by IS or BE
1430
1505
  if (peek().type === TOKEN.IDENTIFIER && (peekAt(1).type === TOKEN.IS || peekAt(1).type === TOKEN.BE) && !isObjectShorthandAmbiguousWithComparison()) {
1431
- return { type: 'RememberStatement', name: target, value: parseObjectLiteral() };
1506
+ return { type: 'RememberStatement', name: target, value: parseObjectLiteral(), typeAnnotation };
1432
1507
  }
1433
1508
 
1434
1509
  // v2.1.0 - remember <name> as query|insert|update|delete … done
@@ -1447,7 +1522,7 @@ function parse(tokens) {
1447
1522
  }
1448
1523
 
1449
1524
  const value = parseExpression();
1450
- return { type: 'RememberStatement', name: target, value };
1525
+ return { type: 'RememberStatement', name: target, value, typeAnnotation };
1451
1526
  }
1452
1527
 
1453
1528
  // ask <variable>
@@ -1568,7 +1643,7 @@ function parseAsk() {
1568
1643
  const keyword = isDefine ? 'define' : isFunction ? 'function' : 'make';
1569
1644
  // Allow "load" as a function name (it's also a keyword for "load env file")
1570
1645
  const nameToken = peek();
1571
- if (nameToken.type !== TOKEN.IDENTIFIER && nameToken.type !== TOKEN.LOAD) {
1646
+ if (!isIdentifierToken(nameToken) && nameToken.type !== TOKEN.LOAD) {
1572
1647
  throw new Error(makeError(
1573
1648
  `Expected a function name after "${keyword}".${reservedWordHint(nameToken)}\n\nExample:\n ${keyword} greet()\n show "Hello"\n done`,
1574
1649
  nameToken
@@ -1578,22 +1653,35 @@ function parseAsk() {
1578
1653
  consume(TOKEN.LPAREN, `Expected "(" after function name "${name}".`);
1579
1654
  const params = parseParamList();
1580
1655
  consume(TOKEN.RPAREN, 'Expected ")" to close the parameter list.');
1656
+ let returnType = null;
1657
+ if (peek().type === TOKEN.IDENTIFIER && (peek().value === 'returns' || peek().value === 'returning')) {
1658
+ advance();
1659
+ returnType = parseTypeSpec();
1660
+ }
1581
1661
  const body = parseBody(`function "${name}"`);
1582
- return { type: 'FunctionDeclaration', name, params, body };
1662
+ return { type: 'FunctionDeclaration', name, params, returnType, body };
1583
1663
  }
1584
1664
 
1585
1665
  function parseIntentDeclaration() {
1586
1666
  advance(); // intend
1587
- 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();
1588
1670
  const name = nameToken.value;
1589
1671
  consume(TOKEN.LPAREN, `Expected "(" after intent name "${name}".`);
1590
1672
  const params = parseParamList();
1591
1673
  consume(TOKEN.RPAREN, 'Expected ")" to close the intent parameter list.');
1674
+ let returnType = null;
1675
+ if (peek().type === TOKEN.IDENTIFIER && (peek().value === 'returns' || peek().value === 'returning')) {
1676
+ advance();
1677
+ returnType = parseTypeSpec();
1678
+ }
1592
1679
  const body = parseBody(`intent "${name}"`);
1593
1680
  return {
1594
1681
  type: 'IntentDeclaration',
1595
1682
  name,
1596
1683
  params,
1684
+ returnType,
1597
1685
  body,
1598
1686
  intent: { kind: 'declaration', name, parameterCount: params.length },
1599
1687
  };
@@ -1602,18 +1690,24 @@ function parseAsk() {
1602
1690
  const primitiveTypeNames = new Set(['any', 'number', 'text', 'boolean', 'null', 'object']);
1603
1691
  function isTypeNameStart(token) {
1604
1692
  return token && token.type === TOKEN.IDENTIFIER &&
1605
- (declaredTypeNames.has(token.value) || primitiveTypeNames.has(token.value) || /^[A-Z]/.test(token.value));
1693
+ (declaredTypeNames.has(token.value) || primitiveTypeNames.has(token.value) ||
1694
+ ['optional', 'list', 'dictionary'].includes(token.value) || /^[A-Z]/.test(token.value));
1606
1695
  }
1607
1696
  function parseTypeAtom() {
1608
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
+ }
1609
1703
  if (token.type === TOKEN.IDENTIFIER && token.value === 'optional') {
1610
1704
  advance();
1611
- return { kind: 'optional', value: parseTypeAtom() };
1705
+ return { kind: 'optional', value: parseTypeSpec() };
1612
1706
  }
1613
1707
  if (token.type === TOKEN.IDENTIFIER && (token.value === 'list' || token.value === 'dictionary')) {
1614
1708
  const kind = advance().value;
1615
1709
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') advance();
1616
- return { kind, value: parseTypeAtom() };
1710
+ return { kind, value: parseTypeSpec() };
1617
1711
  }
1618
1712
  if (!isTypeNameStart(token) && token.type !== TOKEN.NULL_KW) {
1619
1713
  throw new Error(makeError('Expected a type name (number, text, boolean, object, or a declared type).', token));
@@ -2100,7 +2194,9 @@ function parseAsk() {
2100
2194
  // Rest parameter: ...args
2101
2195
  if (peek().type === TOKEN.SPREAD) {
2102
2196
  advance();
2103
- 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;
2104
2200
  return { type: 'RestElement', name };
2105
2201
  }
2106
2202
  // Destructuring: [a, b] or {x, y}
@@ -2129,7 +2225,7 @@ function parseAsk() {
2129
2225
  // identifier names when used as a parameter, mirroring `remember`.
2130
2226
  const PARAM_KEYWORDS = new Set([TOKEN.BACK, TOKEN.REPLY, TOKEN.RESPOND, TOKEN.SEND_BACK, TOKEN.FILE_KW]);
2131
2227
  let name;
2132
- if (PARAM_KEYWORDS.has(peek().type)) {
2228
+ if (isIdentifierToken(peek()) || PARAM_KEYWORDS.has(peek().type)) {
2133
2229
  name = advance().value;
2134
2230
  } else {
2135
2231
  name = consume(TOKEN.IDENTIFIER, 'Expected a parameter name.').value;
@@ -2298,6 +2394,14 @@ function parseAsk() {
2298
2394
  // fold `a contains b` into a comparison here.
2299
2395
  const a = parseNullish();
2300
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
+ }
2301
2405
  if (!['equals', 'is', 'contains', 'raises'].includes(opToken.value)) {
2302
2406
  throw new Error(makeError(
2303
2407
  'Expected "equals", "is", "contains" or "raises" after the value in a "check".\n\nExample:\n check score equals 42',
@@ -2439,11 +2543,19 @@ function parseAsk() {
2439
2543
  if (peek().type === TOKEN.LBRACE) {
2440
2544
  advance(); // {
2441
2545
  const names = [];
2546
+ const namedImports = [];
2442
2547
  while (true) {
2443
- names.push(consume(
2548
+ const imported = consume(
2444
2549
  TOKEN.IDENTIFIER,
2445
2550
  'Expected an exported name inside the import braces.\n\nExample:\n import { helper } from "./util.pln"'
2446
- ).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 });
2447
2559
  if (peek().type === TOKEN.COMMA) { advance(); continue; }
2448
2560
  break;
2449
2561
  }
@@ -2455,7 +2567,7 @@ function parseAsk() {
2455
2567
  TOKEN.STRING,
2456
2568
  'Expected a file path string after the import.\n\nExample:\n import { helper } from "./util.pln"'
2457
2569
  ).value;
2458
- return { type: 'ImportStatement', path: filePath, names };
2570
+ return { type: 'ImportStatement', path: filePath, names, namedImports };
2459
2571
  }
2460
2572
 
2461
2573
  // Form 2: bring all from "path" as math / import all as math from "path" / import * as math from "path"
@@ -4205,7 +4317,7 @@ function parseAsk() {
4205
4317
  advance();
4206
4318
  return { type: 'Identifier', name: token.value };
4207
4319
  }
4208
- if (token.type === TOKEN.IDENTIFIER || IDENTIFIER_KEYWORDS.has(token.type) || isSqlWordIdentifier(token)) {
4320
+ if (isIdentifierToken(token) || IDENTIFIER_KEYWORDS.has(token.type) || isSqlWordIdentifier(token)) {
4209
4321
  if (peekAt(1).type === TOKEN.USES || peekAt(1).type === TOKEN.FILLS) {
4210
4322
  const callee = { type: 'Identifier', name: token.value };
4211
4323
  advance();
@@ -4267,7 +4379,7 @@ function parseAsk() {
4267
4379
  function tokenStartsValue(token) {
4268
4380
  return [
4269
4381
  TOKEN.STRING, TOKEN.TEMPLATE_STRING, TOKEN.NUMBER,
4270
- TOKEN.IDENTIFIER, TOKEN.LBRACKET, TOKEN.LBRACE,
4382
+ TOKEN.IDENTIFIER, TOKEN.ESCAPED_IDENTIFIER, TOKEN.LBRACKET, TOKEN.LBRACE,
4271
4383
  TOKEN.TRUE_KW, TOKEN.FALSE_KW, TOKEN.NULL_KW,
4272
4384
  ].includes(token.type);
4273
4385
  }
@@ -4358,7 +4470,7 @@ function parseAsk() {
4358
4470
  // "done" from the block terminator), plus strings ("with space": 1) and numbers
4359
4471
  // ({ 3: "three" }) for data-shaped objects. A keyword is only accepted as a key when an
4360
4472
  // explicit colon follows, so block-terminator usage of "done" can never be misread here.
4361
- 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 ||
4362
4474
  keyToken.type === TOKEN.NUMBER || keyToken.type === TOKEN.BACK;
4363
4475
  const keyIsColonKeyword = keyToken.type !== TOKEN.IDENTIFIER &&
4364
4476
  typeof keyToken.value === 'string' && /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(keyToken.value) &&