plainscript-lang 1.0.0 → 1.0.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 +6 -6
- package/compiler/cli.js +125 -18
- package/compiler/generator.js +155 -120
- package/compiler/lexer.js +1 -1
- package/compiler/parser.js +130 -12
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +9 -9
- package/docs/PLINJS_SPEC.md +4 -4
- package/docs/index.html +25 -20
- package/docs/website/script.js +1 -1
- package/examples/auth-api.ps +2 -2
- package/examples/concurrency.ps +1 -1
- package/examples/error-handling.ps +1 -1
- package/examples/file-uploads.ps +1 -1
- package/examples/files-and-config.ps +1 -1
- package/examples/http-client.ps +1 -1
- package/examples/modules/app.ps +1 -1
- package/examples/modules/math.ps +1 -1
- package/examples/record-kinds.ps +1 -1
- package/examples/search-and-filter.ps +1 -1
- package/examples/sessions-and-cookies.ps +1 -1
- package/package.json +2 -2
package/compiler/generator.js
CHANGED
|
@@ -40,7 +40,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
40
40
|
fs: `const fs = require('fs');`,
|
|
41
41
|
path: `const path = require('path');`,
|
|
42
42
|
crypto: `const crypto = require('crypto');`,
|
|
43
|
-
// v1.0.
|
|
43
|
+
// v1.0.1 — env-file runtime. Applies KEY=VALUE pairs from a .env file to
|
|
44
44
|
// process.env. Blank lines and `#` comment lines are skipped.
|
|
45
45
|
dotenv: [
|
|
46
46
|
`function __loadEnvFile(path) {`,
|
|
@@ -86,7 +86,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
86
86
|
` }`,
|
|
87
87
|
`}`,
|
|
88
88
|
].join('\n'),
|
|
89
|
-
// v1.0.
|
|
89
|
+
// v1.0.1 — shared runtime helpers for reflection, binary-size, YAML subset
|
|
90
90
|
// parsing/emitting, spread of timeouts, and set/map helpers. Injected lazily
|
|
91
91
|
// when any feature that needs them is used.
|
|
92
92
|
core: [
|
|
@@ -219,7 +219,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
219
219
|
` });`,
|
|
220
220
|
`}`,
|
|
221
221
|
].join('\n'),
|
|
222
|
-
// v1.0.
|
|
222
|
+
// v1.0.1 — process execution (child processes).
|
|
223
223
|
process: [
|
|
224
224
|
`const { execFile } = require('child_process');`,
|
|
225
225
|
`function __runCommand(command, args) {`,
|
|
@@ -230,7 +230,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
230
230
|
` });`,
|
|
231
231
|
`}`,
|
|
232
232
|
].join('\n'),
|
|
233
|
-
// v1.0.
|
|
233
|
+
// v1.0.1 — Map helpers.
|
|
234
234
|
mapset: [
|
|
235
235
|
`function __mapSet(map, key, value) { map.set(key, value); return map; }`,
|
|
236
236
|
].join('\n'),
|
|
@@ -277,7 +277,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
277
277
|
` return { items: slice, count: total, page, pages, perPage, hasNext: page < pages, hasPrev: page > 1 };`,
|
|
278
278
|
`}`,
|
|
279
279
|
].join('\n'),
|
|
280
|
-
// v1.0.
|
|
280
|
+
// v1.0.1 — dynamic module loader.
|
|
281
281
|
loadmodule: [
|
|
282
282
|
`function __loadModule(spec) {`,
|
|
283
283
|
` const path = require('path');`,
|
|
@@ -286,7 +286,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
286
286
|
` catch (e) { if (spec[0] !== '.') return require(spec); throw e; }`,
|
|
287
287
|
`}`,
|
|
288
288
|
].join('\n'),
|
|
289
|
-
// v1.0.
|
|
289
|
+
// v1.0.1 — recursive directory walker (returns full paths, files first).
|
|
290
290
|
walk: [
|
|
291
291
|
`function __walkFolder(dir) {`,
|
|
292
292
|
` const fs = require('fs');`,
|
|
@@ -1121,7 +1121,7 @@ const STDLIB = {
|
|
|
1121
1121
|
// v1.2 — Telegram runtime helpers
|
|
1122
1122
|
bot: (args, context) => {
|
|
1123
1123
|
ensureBuiltin(context, 'telegram');
|
|
1124
|
-
|
|
1124
|
+
markAsync(context);
|
|
1125
1125
|
return `BOT = await Telegram.createTelegramBot(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
1126
1126
|
},
|
|
1127
1127
|
sendMessage: (args, context) => {
|
|
@@ -1261,7 +1261,7 @@ const STDLIB = {
|
|
|
1261
1261
|
padStart: (args, context) => `String(${generateExpr(args[0], context)}).padStart(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
|
|
1262
1262
|
padEnd: (args, context) => `String(${generateExpr(args[0], context)}).padEnd(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
|
|
1263
1263
|
|
|
1264
|
-
// ── v1.0.
|
|
1264
|
+
// ── v1.0.1 — nullable / regex / date helpers (IOPL-native).
|
|
1265
1265
|
// first non-null, non-undefined argument — IOPL null-coalescing.
|
|
1266
1266
|
coalesce: (args, context) =>
|
|
1267
1267
|
`(() => { const __vals = [${args.map(a => generateExpr(a, context)).join(', ')}]; for (const __v of __vals) if (__v !== null && __v !== undefined) return __v; return undefined; })()`,
|
|
@@ -1351,7 +1351,7 @@ const STDLIB = {
|
|
|
1351
1351
|
return `readToken(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
1352
1352
|
},
|
|
1353
1353
|
|
|
1354
|
-
// ── v1.0.
|
|
1354
|
+
// ── v1.0.1 — capability-gap stdlib (reflection, binary, concurrency, ...) ──
|
|
1355
1355
|
|
|
1356
1356
|
// Reflection
|
|
1357
1357
|
typeOf: (args, context) => { ensureBuiltin(context, 'core'); return `__typeOf(${generateExpr(args[0], context)})`; },
|
|
@@ -1412,7 +1412,7 @@ const STDLIB = {
|
|
|
1412
1412
|
// Generators / iterables
|
|
1413
1413
|
spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
|
|
1414
1414
|
|
|
1415
|
-
// v1.0.
|
|
1415
|
+
// v1.0.1 — dynamic module loading (the runtime companion to `import "./x.ps"`).
|
|
1416
1416
|
// Resolves relative to the bundler's CWD so `loadModule("./m")` behaves like
|
|
1417
1417
|
// `require.resolve` from the program root.
|
|
1418
1418
|
loadModule: (args, context) => {
|
|
@@ -1500,9 +1500,41 @@ const STDLIB = {
|
|
|
1500
1500
|
},
|
|
1501
1501
|
};
|
|
1502
1502
|
|
|
1503
|
-
// Mark the enclosing program async when a call awaits at the top level
|
|
1503
|
+
// Mark the enclosing program async when a call awaits at the top level, and
|
|
1504
|
+
// record that this scope emitted an `await` so handler and function bodies can
|
|
1505
|
+
// decide their own async-ness at generation time (see generateBlock). Routing
|
|
1506
|
+
// every await-emitting construct through this single function removes the need
|
|
1507
|
+
// for a separate hand-maintained registry of async statement types — so a new
|
|
1508
|
+
// async keyword can never silently break when used inside a route, listener, or
|
|
1509
|
+
// function.
|
|
1504
1510
|
function markAsync(context) {
|
|
1505
|
-
|
|
1511
|
+
context.emittedAwait = true;
|
|
1512
|
+
// Only a construct that awaits at the true top level needs the program
|
|
1513
|
+
// wrapped in an async IIFE. Awaits emitted inside a user function (inFunction)
|
|
1514
|
+
// or inside a route/listener/404 handler (inHandler) are handled by marking
|
|
1515
|
+
// that function/handler async instead — they must not drag the whole program
|
|
1516
|
+
// into an async wrapper, or "top-level use wraps the whole program" would be
|
|
1517
|
+
// the only safe nesting level for a new async keyword.
|
|
1518
|
+
if (!context.inFunction && !context.inHandler) context.needsAsync = true;
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
// Generate a body of statements and report whether it emitted an `await`.
|
|
1522
|
+
//
|
|
1523
|
+
// This is the single source of truth for whether a route handler, listener,
|
|
1524
|
+
// 404 handler, or user function must be declared `async`. Previously this was
|
|
1525
|
+
// decided by a separate AST walker (containsAsyncBlock) that had to be kept in
|
|
1526
|
+
// sync by hand with every construct that compiles down to `await` — the exact
|
|
1527
|
+
// fragility that made "top-level use wraps the whole program" the only place
|
|
1528
|
+
// certain keywords (like ocr) were guaranteed to work. By observing the output
|
|
1529
|
+
// of generation instead, whatever a body contains is handled correctly, even if
|
|
1530
|
+
// it uses a brand-new async keyword.
|
|
1531
|
+
function generateBlock(statements, indent, context) {
|
|
1532
|
+
const prev = context.emittedAwait;
|
|
1533
|
+
context.emittedAwait = false;
|
|
1534
|
+
const out = statements.map(s => generateStatement(s, indent, context)).join('\n');
|
|
1535
|
+
const emitted = context.emittedAwait;
|
|
1536
|
+
context.emittedAwait = prev;
|
|
1537
|
+
return { out, emitted };
|
|
1506
1538
|
}
|
|
1507
1539
|
|
|
1508
1540
|
// v2.1.0 — generate a request accessor (param/query/header). These compile to
|
|
@@ -1574,6 +1606,7 @@ function emitSqlCall(kind, sql, params, indent, context) {
|
|
|
1574
1606
|
let n = 0;
|
|
1575
1607
|
const pgSql = String(sql).replace(/\?/g, () => (++n <= params.length ? `$${n}` : '?'));
|
|
1576
1608
|
const call = `${_sqlClientVar}.query(\`${pgSql}\`, [${args}])`;
|
|
1609
|
+
markAsync(context);
|
|
1577
1610
|
return kind === 'query' ? `(await ${call}).rows` : `await ${call}`;
|
|
1578
1611
|
}
|
|
1579
1612
|
switch (kind) {
|
|
@@ -1589,7 +1622,10 @@ function createGenerationContext() {
|
|
|
1589
1622
|
requires: new Set(),
|
|
1590
1623
|
pendingPrelude: [],
|
|
1591
1624
|
needsAsync: false, // true when top-level code emits await (js blocks / ask)
|
|
1625
|
+
emittedAwait: false, // true when the current generateBlock emitted an await
|
|
1592
1626
|
inFunction: false, // true while generating inside a function-like scope
|
|
1627
|
+
inHandler: false, // true while generating a route/listener/404 response body
|
|
1628
|
+
loopDepth: 0, // >0 while generating inside a for-each / for-index / while loop
|
|
1593
1629
|
};
|
|
1594
1630
|
}
|
|
1595
1631
|
|
|
@@ -1653,72 +1689,6 @@ function ensureBuiltin(context, moduleName) {
|
|
|
1653
1689
|
}
|
|
1654
1690
|
}
|
|
1655
1691
|
|
|
1656
|
-
// Builtins whose calls await. A statement containing one of these anywhere in
|
|
1657
|
-
// its expressions must compile into an async context.
|
|
1658
|
-
const ASYNC_CALL_NAMES = new Set([
|
|
1659
|
-
// v2.1.0 — cache and email
|
|
1660
|
-
'cacheGet', 'cacheSet', 'cacheDelete', 'sendMail',
|
|
1661
|
-
// v2.2.0 — AI/ML calls await their model endpoint
|
|
1662
|
-
'chat', 'embedText',
|
|
1663
|
-
// v1.2 — Telegram helpers (await their API transport)
|
|
1664
|
-
'bot', 'sendMessage', 'sendPhoto', 'editMessage', 'getChat', 'getMyChats',
|
|
1665
|
-
]);
|
|
1666
|
-
|
|
1667
|
-
// Collect async builtin call names reachable from an AST fragment.
|
|
1668
|
-
function findAsyncCalls(node, found) {
|
|
1669
|
-
if (!node || typeof node !== 'object') return found;
|
|
1670
|
-
if (Array.isArray(node)) {
|
|
1671
|
-
for (const item of node) findAsyncCalls(item, found);
|
|
1672
|
-
return found;
|
|
1673
|
-
}
|
|
1674
|
-
if (node.type === 'CallExpression' && ASYNC_CALL_NAMES.has(node.name)) {
|
|
1675
|
-
found.add(node.name);
|
|
1676
|
-
}
|
|
1677
|
-
// v2.1.1 — HTTP client calls await; "wait for <expr>" awaits explicitly.
|
|
1678
|
-
if (node.type === 'HttpCall' || node.type === 'AwaitExpression') {
|
|
1679
|
-
found.add(node.type);
|
|
1680
|
-
}
|
|
1681
|
-
for (const value of Object.values(node)) {
|
|
1682
|
-
if (value && typeof value === 'object') findAsyncCalls(value, found);
|
|
1683
|
-
}
|
|
1684
|
-
return found;
|
|
1685
|
-
}
|
|
1686
|
-
|
|
1687
|
-
// True when any statement in the block emits `await` (a JavaScript block,
|
|
1688
|
-
// `ask`, or `ocr`), including inside nested if / loop bodies. Nested PlainScript
|
|
1689
|
-
// function declarations are handled independently, so they are not descended
|
|
1690
|
-
// into.
|
|
1691
|
-
function containsAsyncBlock(statements) {
|
|
1692
|
-
for (const stmt of statements || []) {
|
|
1693
|
-
if (stmt.type === 'AskStatement' || stmt.type === 'JavaScriptBlock' || stmt.type === 'OcrStatement') return true;
|
|
1694
|
-
// v2.1.0 — transactions always await; PostgreSQL SQL statements await;
|
|
1695
|
-
// mail sends, cache setup and websocket handlers await.
|
|
1696
|
-
if (stmt.type === 'TransactionStatement') return true;
|
|
1697
|
-
if (stmt.type === 'SendMailStatement' || stmt.type === 'CacheStatement') return true;
|
|
1698
|
-
// v2.1.1 — opening the database awaits (native/wasm engine probe);
|
|
1699
|
-
// retry loops pause between attempts; try/recover recurse.
|
|
1700
|
-
if (stmt.type === 'DatabaseStatement' || stmt.type === 'RetryStatement') return true;
|
|
1701
|
-
if (stmt.type === 'TryStatement') {
|
|
1702
|
-
if (containsAsyncBlock(stmt.tryBody)) return true;
|
|
1703
|
-
if (stmt.recoverBody && containsAsyncBlock(stmt.recoverBody)) return true;
|
|
1704
|
-
continue;
|
|
1705
|
-
}
|
|
1706
|
-
if (_sqlDriver === 'pg' && (
|
|
1707
|
-
stmt.type === 'QueryStatement' || stmt.type === 'InsertStatement' ||
|
|
1708
|
-
stmt.type === 'UpdateStatement' || stmt.type === 'DeleteStatement' ||
|
|
1709
|
-
stmt.type === 'ExecuteStatement' || stmt.type === 'RememberSqlStatement'
|
|
1710
|
-
)) return true;
|
|
1711
|
-
if (findAsyncCalls(stmt, new Set()).size > 0) return true;
|
|
1712
|
-
if (stmt.type === 'IfStatement') {
|
|
1713
|
-
if (containsAsyncBlock(stmt.consequent)) return true;
|
|
1714
|
-
if (stmt.alternate && containsAsyncBlock(stmt.alternate)) return true;
|
|
1715
|
-
} else if (stmt.type !== 'FunctionDeclaration' && stmt.body) {
|
|
1716
|
-
if (containsAsyncBlock(stmt.body)) return true;
|
|
1717
|
-
}
|
|
1718
|
-
}
|
|
1719
|
-
return false;
|
|
1720
|
-
}
|
|
1721
|
-
|
|
1722
1692
|
// True when any statement in a block (recursively, skipping nested function
|
|
1723
1693
|
// declarations) contains a `yield`, which marks the enclosing function as a
|
|
1724
1694
|
// generator (function*).
|
|
@@ -1738,7 +1708,7 @@ function containsYield(statements) {
|
|
|
1738
1708
|
function generate(ast, context = createGenerationContext()) { if (ast.type !== 'Program') {
|
|
1739
1709
|
throw new Error(`Expected a Program node but got "${ast.type}".`);
|
|
1740
1710
|
}
|
|
1741
|
-
// v1.0.
|
|
1711
|
+
// v1.0.1 — reset per-program test bookkeeping so repeated generate() calls
|
|
1742
1712
|
// (build pipeline) start clean.
|
|
1743
1713
|
__testCount = 0;
|
|
1744
1714
|
__testCatchers = [];
|
|
@@ -1760,7 +1730,7 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
1760
1730
|
lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
|
|
1761
1731
|
}
|
|
1762
1732
|
|
|
1763
|
-
// v1.0.
|
|
1733
|
+
// v1.0.1 — native test runner. When any "test ... done" block exists, emit
|
|
1764
1734
|
// the runner helper, register each test after its function declaration, and
|
|
1765
1735
|
// execute them. Each failure prints a message and sets process.exitCode = 1.
|
|
1766
1736
|
if (__testCatchers.length > 0) {
|
|
@@ -1795,7 +1765,7 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
1795
1765
|
return lines.join('\n');
|
|
1796
1766
|
}
|
|
1797
1767
|
|
|
1798
|
-
// ── v1.0.
|
|
1768
|
+
// ── v1.0.1 — test DSL bookkeeping ───────────────────────────────────────────
|
|
1799
1769
|
let __testCount = 0;
|
|
1800
1770
|
let __testCatchers = [];
|
|
1801
1771
|
let __inTest = false;
|
|
@@ -1848,7 +1818,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1848
1818
|
case 'BecomeStatement':
|
|
1849
1819
|
return `${indent}${generateLValue(node.target, context)} = ${generateExpr(node.value, context)};`;
|
|
1850
1820
|
|
|
1851
|
-
// v1.0.
|
|
1821
|
+
// v1.0.1 — record kinds: `define a kind called "Person" with ... done`.
|
|
1852
1822
|
// Names are emitted as a JS factory that returns a fresh plain object with
|
|
1853
1823
|
// declared defaults. Constructors prompt for required fields at compile
|
|
1854
1824
|
// time via `create a Person with ...` (see GenerateExpr CreateKind).
|
|
@@ -1872,14 +1842,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1872
1842
|
].join('\n');
|
|
1873
1843
|
}
|
|
1874
1844
|
|
|
1875
|
-
// v1.0.
|
|
1845
|
+
// v1.0.1 — load env file "<path>": apply KEY=VALUE pairs to process.env.
|
|
1876
1846
|
// Blank lines and `#` comments are skipped; values keep their text.
|
|
1877
1847
|
case 'LoadEnvFileStatement': {
|
|
1878
1848
|
ensureBuiltin(context, 'dotenv');
|
|
1879
1849
|
return `${indent}__loadEnvFile(${JSON.stringify(node.path)});`;
|
|
1880
1850
|
}
|
|
1881
1851
|
|
|
1882
|
-
// v1.0.
|
|
1852
|
+
// v1.0.1 — native test DSL. `test "<name>" ... done` registers a runnable
|
|
1883
1853
|
// unit; all tests are executed after the program body with a tiny runner.
|
|
1884
1854
|
case 'TestStatement': {
|
|
1885
1855
|
__testCount++;
|
|
@@ -1892,7 +1862,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1892
1862
|
return `${indent}function ${fnName}() {\n${body}\n${indent}}`;
|
|
1893
1863
|
}
|
|
1894
1864
|
|
|
1895
|
-
// v1.0.
|
|
1865
|
+
// v1.0.1 — assertion `check <a> (equals|is|contains|raises) <b>`.
|
|
1896
1866
|
// For `raises`, `a` is wrapped in a thunk so the expression is evaluated
|
|
1897
1867
|
// inside the runner's try/catch (its thrown error is the subject).
|
|
1898
1868
|
case 'CheckStatement': {
|
|
@@ -1906,11 +1876,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1906
1876
|
return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
|
|
1907
1877
|
}
|
|
1908
1878
|
|
|
1909
|
-
// v1.0.
|
|
1879
|
+
// v1.0.1 — export <name>: mark a top-level symbol for module.exports.
|
|
1910
1880
|
case 'ExportStatement':
|
|
1911
1881
|
return `${indent}module.exports.${node.name} = ${node.name};`;
|
|
1912
1882
|
|
|
1913
|
-
// v1.0.
|
|
1883
|
+
// v1.0.1 — generators: `yield <expr>` (or bare `yield`).
|
|
1914
1884
|
case 'YieldStatement': {
|
|
1915
1885
|
if (!context.inFunction) {
|
|
1916
1886
|
throw new Error('"yield" can only be used inside a function created with "make".\n\nExample:\n make countUp(n)\n let i = 0\n while i less than n\n i = i + 1\n yield i\n done\n done');
|
|
@@ -1959,13 +1929,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1959
1929
|
// body is emitted verbatim: JavaScript indentation, template literals,
|
|
1960
1930
|
// and line structure are preserved as written (RFC-0011 §31).
|
|
1961
1931
|
if (node.name) {
|
|
1962
|
-
|
|
1932
|
+
markAsync(context);
|
|
1963
1933
|
return `${indent}let ${node.name} = await (async () => {\n${node.body}\n${indent}})();`;
|
|
1964
1934
|
}
|
|
1965
1935
|
// Statement-level blocks inside functions/routes/loops, or that need
|
|
1966
1936
|
// top-level await, retain the async-context wrapper.
|
|
1967
1937
|
if (context.inFunction || hasTopLevelAwait) {
|
|
1968
|
-
|
|
1938
|
+
markAsync(context);
|
|
1969
1939
|
return `${indent}await (async () => {\n${node.body}\n${indent}})();`;
|
|
1970
1940
|
}
|
|
1971
1941
|
// Synchronous statement-level block: emit its body directly/verbatim.
|
|
@@ -1975,7 +1945,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1975
1945
|
// ask name / ask "<prompt>" as name
|
|
1976
1946
|
case 'AskStatement': {
|
|
1977
1947
|
ensureBuiltin(context, 'ask');
|
|
1978
|
-
|
|
1948
|
+
markAsync(context);
|
|
1979
1949
|
const prompt = node.prompt != null ? JSON.stringify(node.prompt) : '"> "';
|
|
1980
1950
|
return `${indent}let ${node.variable} = await __ask(${prompt});`;
|
|
1981
1951
|
}
|
|
@@ -1983,14 +1953,18 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1983
1953
|
// v2.0.1 — ocr "<image>" as <variable> [using "<lang>"]
|
|
1984
1954
|
case 'OcrStatement': {
|
|
1985
1955
|
ensureBuiltin(context, 'ocr');
|
|
1986
|
-
|
|
1956
|
+
markAsync(context);
|
|
1987
1957
|
const image = generateExpr(node.image, context);
|
|
1988
1958
|
const langArg = node.lang != null ? `, ${JSON.stringify(node.lang)}` : '';
|
|
1989
1959
|
return `${indent}let ${node.variable} = await __ocr(${image}${langArg});`;
|
|
1990
1960
|
}
|
|
1991
1961
|
|
|
1992
1962
|
case 'FunctionDeclaration': {
|
|
1993
|
-
const
|
|
1963
|
+
const prevInFunction = context.inFunction;
|
|
1964
|
+
context.inFunction = true;
|
|
1965
|
+
const block = generateBlock(node.body, indent + ' ', context);
|
|
1966
|
+
context.inFunction = prevInFunction;
|
|
1967
|
+
const isAsync = block.emitted ? 'async ' : '';
|
|
1994
1968
|
const isGen = containsYield(node.body) ? '*' : '';
|
|
1995
1969
|
const paramStr = node.params.map(p => {
|
|
1996
1970
|
if (typeof p === 'object') {
|
|
@@ -1999,11 +1973,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
1999
1973
|
}
|
|
2000
1974
|
return p;
|
|
2001
1975
|
}).join(', ');
|
|
2002
|
-
|
|
2003
|
-
context.inFunction = true;
|
|
2004
|
-
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2005
|
-
context.inFunction = prevInFunction;
|
|
2006
|
-
return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${body}\n${indent}}`;
|
|
1976
|
+
return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${block.out}\n${indent}}`;
|
|
2007
1977
|
}
|
|
2008
1978
|
|
|
2009
1979
|
case 'IfStatement': {
|
|
@@ -2018,37 +1988,87 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2018
1988
|
}
|
|
2019
1989
|
|
|
2020
1990
|
case 'ForEachStatement': {
|
|
1991
|
+
context.loopDepth++;
|
|
2021
1992
|
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
1993
|
+
context.loopDepth--;
|
|
2022
1994
|
return `${indent}for (const ${node.item} of ${generateExpr(node.collection, context)}) {\n${body}\n${indent}}`;
|
|
2023
1995
|
}
|
|
2024
1996
|
|
|
1997
|
+
case 'ForIndexStatement': {
|
|
1998
|
+
context.loopDepth++;
|
|
1999
|
+
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2000
|
+
context.loopDepth--;
|
|
2001
|
+
// for index <name> in <collection> — zero-based index over a list.
|
|
2002
|
+
if (node.over != null) {
|
|
2003
|
+
const coll = generateExpr(node.over, context);
|
|
2004
|
+
return `${indent}for (let ${node.name} = 0; ${node.name} < ${coll}.length; ${node.name}++) {\n${body}\n${indent}}`;
|
|
2005
|
+
}
|
|
2006
|
+
const start = generateExpr(node.start, context);
|
|
2007
|
+
const end = generateExpr(node.end, context);
|
|
2008
|
+
// Explicit step uses the user's sign; otherwise the increment follows
|
|
2009
|
+
// the direction of the bounds (from 5 to 1 counts down automatically).
|
|
2010
|
+
const inc = node.step ? generateExpr(node.step, context)
|
|
2011
|
+
: `(${start} <= ${end} ? 1 : -1)`;
|
|
2012
|
+
// Direction-aware: "from 5 to 1" counts down even without an explicit
|
|
2013
|
+
// "by", while "from 1 to 5" counts up.
|
|
2014
|
+
const test = `(${start} <= ${end} ? ${node.name} <= ${end} : ${node.name} >= ${end})`;
|
|
2015
|
+
return `${indent}for (let ${node.name} = ${start}; ${test}; ${node.name} += ${inc}) {\n${body}\n${indent}}`;
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2025
2018
|
case 'WhileStatement': {
|
|
2026
2019
|
const condition = generateCondition(node.condition, context);
|
|
2027
|
-
|
|
2020
|
+
context.loopDepth++;
|
|
2021
|
+
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2022
|
+
context.loopDepth--;
|
|
2028
2023
|
return `${indent}while (${condition}) {\n${body}\n${indent}}`;
|
|
2029
2024
|
}
|
|
2030
2025
|
|
|
2026
|
+
case 'BreakStatement': {
|
|
2027
|
+
if (context.loopDepth <= 0) {
|
|
2028
|
+
throw new Error('"break" can only be used inside a loop (for each, for index, or while).\n\nExample:\n for each item in list\n if done(item)\n break\n done\n done');
|
|
2029
|
+
}
|
|
2030
|
+
return `${indent}break;`;
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
case 'ContinueStatement': {
|
|
2034
|
+
if (context.loopDepth <= 0) {
|
|
2035
|
+
throw new Error('"continue" can only be used inside a loop (for each, for index, or while).\n\nExample:\n for each item in list\n if skip(item)\n continue\n done\n done');
|
|
2036
|
+
}
|
|
2037
|
+
return `${indent}continue;`;
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
case 'ThrowStatement':
|
|
2041
|
+
return `${indent}throw ${generateExpr(node.value, context)};`;
|
|
2042
|
+
|
|
2031
2043
|
// v0.3 — Express runtime
|
|
2032
2044
|
|
|
2033
2045
|
case 'ListenStatement': {
|
|
2034
|
-
const
|
|
2035
|
-
|
|
2036
|
-
|
|
2046
|
+
const prevInHandler = context.inHandler;
|
|
2047
|
+
context.inHandler = true;
|
|
2048
|
+
const block = generateBlock(node.body, indent + ' ', context);
|
|
2049
|
+
context.inHandler = prevInHandler;
|
|
2050
|
+
const handlerAsync = block.emitted ? 'async ' : '';
|
|
2051
|
+
return `${indent}app.listen(${generateExpr(node.port, context)}, ${handlerAsync}() => {\n${block.out}\n${indent}});`;
|
|
2037
2052
|
}
|
|
2038
2053
|
|
|
2039
2054
|
case 'RouteStatement': {
|
|
2040
2055
|
_inRoute = true;
|
|
2041
|
-
const
|
|
2042
|
-
|
|
2056
|
+
const prevInHandler = context.inHandler;
|
|
2057
|
+
context.inHandler = true;
|
|
2058
|
+
const block = generateBlock(node.body, indent + ' ', context);
|
|
2059
|
+
context.inHandler = prevInHandler;
|
|
2043
2060
|
_inRoute = false;
|
|
2044
|
-
|
|
2061
|
+
const handlerAsync = block.emitted ? 'async ' : '';
|
|
2062
|
+
return `${indent}app.get(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${block.out}\n${indent}});`;
|
|
2045
2063
|
}
|
|
2046
2064
|
|
|
2047
2065
|
case 'ReplyStatement':
|
|
2048
2066
|
if (_inTelegram) {
|
|
2067
|
+
markAsync(context);
|
|
2049
2068
|
return `${indent}await Telegram.sendMessage(ctx.chatId, ${generateExpr(node.value, context)});`;
|
|
2050
2069
|
}
|
|
2051
2070
|
if (_inWhatsApp) {
|
|
2071
|
+
markAsync(context);
|
|
2052
2072
|
ensureBuiltin(context, 'whatsapp');
|
|
2053
2073
|
return `${indent}await __whatsappReply(__waCtx.chat, ${generateExpr(node.value, context)});`;
|
|
2054
2074
|
}
|
|
@@ -2059,9 +2079,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2059
2079
|
.map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
|
|
2060
2080
|
.join(', ');
|
|
2061
2081
|
if (_inTelegram) {
|
|
2082
|
+
markAsync(context);
|
|
2062
2083
|
return `${indent}await Telegram.sendMessage(ctx.chatId, JSON.stringify({ ${props} }));`;
|
|
2063
2084
|
}
|
|
2064
2085
|
if (_inWhatsApp) {
|
|
2086
|
+
markAsync(context);
|
|
2065
2087
|
ensureBuiltin(context, 'whatsapp');
|
|
2066
2088
|
return `${indent}await __whatsappReply(__waCtx.chat, JSON.stringify({ ${props} }));`;
|
|
2067
2089
|
}
|
|
@@ -2074,6 +2096,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2074
2096
|
// button is rendered as [text, data] and rows are merged into that list.
|
|
2075
2097
|
case 'ReplyWithButtonsStatement': {
|
|
2076
2098
|
ensureBuiltin(context, 'telegram');
|
|
2099
|
+
markAsync(context);
|
|
2077
2100
|
const pairs = node.buttons.flat().map(({ text, data }) => [text, data]);
|
|
2078
2101
|
return `${indent}await Telegram.sendMessage(ctx.chatId, ${generateExpr(node.value, context)}, ${JSON.stringify(pairs)});`;
|
|
2079
2102
|
}
|
|
@@ -2095,10 +2118,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2095
2118
|
|
|
2096
2119
|
case 'SimpleRouteStatement': {
|
|
2097
2120
|
_inRoute = true;
|
|
2098
|
-
const
|
|
2099
|
-
|
|
2121
|
+
const prevInHandler = context.inHandler;
|
|
2122
|
+
context.inHandler = true;
|
|
2123
|
+
const block = generateBlock(node.body, indent + ' ', context);
|
|
2124
|
+
context.inHandler = prevInHandler;
|
|
2100
2125
|
_inRoute = false;
|
|
2101
|
-
|
|
2126
|
+
const handlerAsync = block.emitted ? 'async ' : '';
|
|
2127
|
+
return `${indent}app.${node.method}(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${block.out}\n${indent}});`;
|
|
2102
2128
|
}
|
|
2103
2129
|
|
|
2104
2130
|
// v2.1.0 — group "<prefix>" ... done: composes routes under a shared
|
|
@@ -2225,10 +2251,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2225
2251
|
// in registration order).
|
|
2226
2252
|
case 'NotFoundStatement': {
|
|
2227
2253
|
_inRoute = true;
|
|
2228
|
-
const
|
|
2229
|
-
|
|
2254
|
+
const prevInHandler = context.inHandler;
|
|
2255
|
+
context.inHandler = true;
|
|
2256
|
+
const block = generateBlock(node.body, indent + ' ', context);
|
|
2257
|
+
context.inHandler = prevInHandler;
|
|
2230
2258
|
_inRoute = false;
|
|
2231
|
-
|
|
2259
|
+
const handlerAsync = block.emitted ? 'async ' : '';
|
|
2260
|
+
return `${indent}app.use((${handlerAsync}req, res) => {\n${block.out}\n${indent}});`;
|
|
2232
2261
|
}
|
|
2233
2262
|
|
|
2234
2263
|
// ── v2.1.1 — error handling and retries
|
|
@@ -2321,7 +2350,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2321
2350
|
case 'PostgresStatement': {
|
|
2322
2351
|
_sqlDriver = 'pg';
|
|
2323
2352
|
_sqlClientVar = 'db';
|
|
2324
|
-
|
|
2353
|
+
markAsync(context);
|
|
2325
2354
|
return [
|
|
2326
2355
|
emitRequire(context, 'postgres'),
|
|
2327
2356
|
`${indent}const db = new Pool({ connectionString: ${generateExpr(node.connection, context)} });`,
|
|
@@ -2352,7 +2381,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2352
2381
|
if (_sqlDriver === 'pg') {
|
|
2353
2382
|
const prevClient = _sqlClientVar;
|
|
2354
2383
|
_sqlClientVar = '__txClient';
|
|
2355
|
-
|
|
2384
|
+
markAsync(context);
|
|
2356
2385
|
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2357
2386
|
_sqlClientVar = prevClient;
|
|
2358
2387
|
return [
|
|
@@ -2385,7 +2414,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2385
2414
|
|
|
2386
2415
|
case 'TelegramCommandStatement': {
|
|
2387
2416
|
ensureBuiltin(context, 'telegram');
|
|
2388
|
-
|
|
2417
|
+
markAsync(context);
|
|
2389
2418
|
_inTelegram = true;
|
|
2390
2419
|
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2391
2420
|
_inTelegram = false;
|
|
@@ -2397,7 +2426,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2397
2426
|
|
|
2398
2427
|
case 'TelegramCallbackStatement': {
|
|
2399
2428
|
ensureBuiltin(context, 'telegram');
|
|
2400
|
-
|
|
2429
|
+
markAsync(context);
|
|
2401
2430
|
_inTelegram = true;
|
|
2402
2431
|
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
2403
2432
|
_inTelegram = false;
|
|
@@ -2406,7 +2435,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2406
2435
|
|
|
2407
2436
|
case 'TelegramStartStatement': {
|
|
2408
2437
|
ensureBuiltin(context, 'telegram');
|
|
2409
|
-
|
|
2438
|
+
markAsync(context);
|
|
2410
2439
|
return `${indent}await BOT.start();`;
|
|
2411
2440
|
}
|
|
2412
2441
|
|
|
@@ -2445,7 +2474,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2445
2474
|
// WhatsApp message as a normalized PlainScript record on `message`.
|
|
2446
2475
|
case 'WhatsAppOnMessageStatement': {
|
|
2447
2476
|
ensureBuiltin(context, 'whatsapp');
|
|
2448
|
-
|
|
2477
|
+
markAsync(context);
|
|
2449
2478
|
const prevInWhatsApp = _inWhatsApp;
|
|
2450
2479
|
_inWhatsApp = true;
|
|
2451
2480
|
const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
|
|
@@ -2548,7 +2577,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2548
2577
|
|
|
2549
2578
|
case 'RunBackgroundStatement':
|
|
2550
2579
|
return [
|
|
2551
|
-
`${indent}setImmediate(() => {`,
|
|
2580
|
+
`${indent}setImmediate(async () => {`,
|
|
2552
2581
|
`${indent} try {`,
|
|
2553
2582
|
`${indent} Promise.resolve(${generateExpr(node.call, context)}).catch((error) => console.error(error));`,
|
|
2554
2583
|
`${indent} } catch (error) { console.error(error); }`,
|
|
@@ -2755,6 +2784,12 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
2755
2784
|
return `${generateExpr(node.object, context)}.${node.property}`;
|
|
2756
2785
|
|
|
2757
2786
|
case 'CallExpression': {
|
|
2787
|
+
// Method call: receiver.method(args). Member access invoked with parens —
|
|
2788
|
+
// e.g. path.join("a", "b"), mrz.parse(line), fs.existsSync(("x")).
|
|
2789
|
+
if (node.callee) {
|
|
2790
|
+
const args = node.args.map(arg => generateExpr(arg, context)).join(', ');
|
|
2791
|
+
return `${generateExpr(node.callee, context)}(${args})`;
|
|
2792
|
+
}
|
|
2758
2793
|
if (STDLIB[node.name]) {
|
|
2759
2794
|
if (node.name === 'readFile' || node.name === 'writeFile' ||
|
|
2760
2795
|
node.name === 'fileExists' || node.name === 'read') {
|
|
@@ -2811,7 +2846,7 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
2811
2846
|
ensureBuiltin(context, 'fs');
|
|
2812
2847
|
return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
|
|
2813
2848
|
|
|
2814
|
-
// v1.0.
|
|
2849
|
+
// v1.0.1 — record constructor: `create a Person with name "Ada" and age 17`
|
|
2815
2850
|
// calls the kind factory that `define a kind called "Person"` registered.
|
|
2816
2851
|
case 'CreateKindExpression': {
|
|
2817
2852
|
const fields = node.pairs
|
|
@@ -2820,7 +2855,7 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
2820
2855
|
return `${node.kind}({ ${fields} })`;
|
|
2821
2856
|
}
|
|
2822
2857
|
|
|
2823
|
-
// v1.0.
|
|
2858
|
+
// v1.0.1 — concurrency combinators: `all of [...]` / `any of [...]` /
|
|
2824
2859
|
// `settled of [...]`. All are awaited; `settled` returns status records.
|
|
2825
2860
|
case 'ConcurrencyExpression': {
|
|
2826
2861
|
markAsync(context);
|
|
@@ -2830,7 +2865,7 @@ function generateExpr(node, context = createGenerationContext()) {
|
|
|
2830
2865
|
return `(await Promise.all(${rhs}))`;
|
|
2831
2866
|
}
|
|
2832
2867
|
|
|
2833
|
-
// v1.0.
|
|
2868
|
+
// v1.0.1 — `spread of <collection>` → a fresh array from an iterable.
|
|
2834
2869
|
case 'SpreadExpression':
|
|
2835
2870
|
return `[...${generateExpr(node.collection, context)}]`;
|
|
2836
2871
|
|
package/compiler/lexer.js
CHANGED
|
@@ -76,7 +76,7 @@ const TOKEN = {
|
|
|
76
76
|
EMIT: 'EMIT', // emit "event.name" with data (event emitter)
|
|
77
77
|
HAPPENS: 'HAPPENS', // when "event.name" happens as data (event listener)
|
|
78
78
|
CATCHES: 'CATCHES', // recover when err catches "TypeError" (typed error recovery)
|
|
79
|
-
// v1.0.
|
|
79
|
+
// v1.0.1 — generators. "yield" is a JavaScript reserved word, so it becomes a
|
|
80
80
|
// real keyword token (a variable named `yield` is illegal in JS anyway).
|
|
81
81
|
YIELD: 'YIELD',
|
|
82
82
|
// Punctuation
|