plainscript-lang 1.0.362 → 1.1.0

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.
Files changed (99) hide show
  1. package/README.md +394 -54
  2. package/compiler/bundler.js +78 -3
  3. package/compiler/cli.js +239 -30
  4. package/compiler/formatter.js +21 -1
  5. package/compiler/generator.js +453 -107
  6. package/compiler/ir.js +62 -0
  7. package/compiler/lexer.js +42 -7
  8. package/compiler/lsp.js +290 -0
  9. package/compiler/parser.js +820 -113
  10. package/compiler/type-checker.js +440 -0
  11. package/compiler/version.js +1 -1
  12. package/docs/CAPABILITY_GAP_AUDIT.md +19 -3
  13. package/docs/GAME-PROMPT.md +3 -3
  14. package/docs/PLAINSCRIPT-GRAMMAR.md +317 -0
  15. package/docs/PLAINSCRIPT-SPEC.md +264 -5
  16. package/docs/V1.1-TYPED-COLLECTIONS-DESIGN.md +220 -0
  17. package/docs/index.html +5 -5
  18. package/docs/website/script.js +1 -1
  19. package/examples/ai-memory-cli.pln +221 -0
  20. package/examples/ai-memory.json +1 -0
  21. package/examples/ai-providers.pln +1 -1
  22. package/examples/arrays.pln +1 -1
  23. package/examples/async-errors.pln +1 -1
  24. package/examples/auth-api.pln +1 -1
  25. package/examples/auth-sessions.pln +1 -1
  26. package/examples/basics.pln +1 -1
  27. package/examples/bots.pln +1 -1
  28. package/examples/browser-interactive/README.md +1 -1
  29. package/examples/browser-interactive/src/interactive.pln +1 -1
  30. package/examples/cache-and-jobs.pln +1 -1
  31. package/examples/cache-schedule.pln +1 -1
  32. package/examples/canvas-game/README.md +1 -1
  33. package/examples/canvas-game/src/game.pln +1 -1
  34. package/examples/collections.pln +1 -1
  35. package/examples/compound-assignments.pln +24 -0
  36. package/examples/concurrency.pln +2 -2
  37. package/examples/conditions.pln +1 -1
  38. package/examples/database.pln +1 -1
  39. package/examples/day2.pln +1 -1
  40. package/examples/day3.pln +1 -1
  41. package/examples/deployment.pln +1 -1
  42. package/examples/email-send.pln +1 -1
  43. package/examples/error-handling.pln +1 -1
  44. package/examples/expressions.pln +1 -1
  45. package/examples/file-manager-cli.pln +51 -0
  46. package/examples/file-uploads.pln +1 -1
  47. package/examples/files-and-config.pln +1 -1
  48. package/examples/files.pln +1 -1
  49. package/examples/football-backend/app.pln +1 -1
  50. package/examples/functions.pln +1 -1
  51. package/examples/hello.pln +1 -1
  52. package/examples/http-client.pln +1 -1
  53. package/examples/http.pln +1 -1
  54. package/examples/id-verification/app.pln +1 -1
  55. package/examples/interactive-cli.pln +34 -0
  56. package/examples/javascript-library/README.md +1 -1
  57. package/examples/javascript-library/src/interop.pln +1 -1
  58. package/examples/json.pln +1 -1
  59. package/examples/loops.pln +1 -1
  60. package/examples/memoize-demo.pln +31 -0
  61. package/examples/modules/app.pln +1 -1
  62. package/examples/modules/main.pln +1 -1
  63. package/examples/modules/math.pln +1 -1
  64. package/examples/mongo.pln +1 -1
  65. package/examples/normalization-forms.pln +22 -0
  66. package/examples/objects.pln +1 -1
  67. package/examples/ocr.pln +1 -1
  68. package/examples/packages.pln +1 -1
  69. package/examples/random-cli.pln +32 -0
  70. package/examples/record-kinds.pln +1 -1
  71. package/examples/records.pln +1 -1
  72. package/examples/rest-api-fetch.pln +1 -1
  73. package/examples/rest-api.pln +1 -1
  74. package/examples/run-in-parallel.pln +25 -0
  75. package/examples/scheduled-tasks.pln +1 -1
  76. package/examples/search-and-filter.pln +1 -1
  77. package/examples/server.pln +1 -1
  78. package/examples/sessions-and-cookies.pln +1 -1
  79. package/examples/sqlite.pln +1 -1
  80. package/examples/start.pln +1 -1
  81. package/examples/stats-cli.pln +29 -0
  82. package/examples/stdlib.pln +1 -1
  83. package/examples/string-helpers.pln +23 -0
  84. package/examples/string-verbs.pln +1 -1
  85. package/examples/telegram-ai-bot.pln +1 -1
  86. package/examples/telegram-bot.pln +1 -1
  87. package/examples/terminal-cli.pln +11 -0
  88. package/examples/testing.pln +1 -1
  89. package/examples/three-dimensional/README.md +1 -1
  90. package/examples/three-dimensional/src/scene.pln +1 -1
  91. package/examples/todo-cli.pln +98 -0
  92. package/examples/typed-collections.pln +21 -0
  93. package/examples/web-api.pln +1 -1
  94. package/examples/web-app.pln +1 -1
  95. package/examples/websocket-server.pln +1 -1
  96. package/examples/websocket.pln +1 -1
  97. package/examples/whatsapp-bot/pairing.pln +1 -1
  98. package/examples/whatsapp-bot/qr.pln +1 -1
  99. package/package.json +13 -4
@@ -1,13 +1,13 @@
1
1
  // Parser: converts a token stream into an AST (Abstract Syntax Tree).
2
2
 
3
- const { TOKEN } = require('./lexer');
3
+ const { tokenize, TOKEN, KEYWORDS } = require('./lexer');
4
4
 
5
5
  // Statement-starting PlainScript keywords, used for "did you mean?" suggestions.
6
6
  const STATEMENT_KEYWORDS = [
7
- 'remember', 'show', 'display', 'log', 'if', 'make', 'give',
7
+ 'remember', 'show', 'display', 'log', 'if', 'make', 'intend', 'give',
8
8
  'for', 'while', 'repeat', 'until', 'use', 'import', 'when', 'listen', 'reply', 'serve',
9
9
  'web', 'route', 'start', 'database', 'query', 'insert', 'update', 'delete', 'execute',
10
- 'ask', 'javascript', 'bot', 'ocr', 'try', 'recover', 'retry',
10
+ 'ask', 'bot', 'ocr', 'try', 'recover', 'retry',
11
11
  'gather', 'filter', 'total', 'match', 'emit', 'stream', 'run',
12
12
  'switch', 'case', 'default', 'break', 'continue', 'return',
13
13
  'throw', 'catch', 'finally', 'new', 'class', 'extends', 'super',
@@ -98,6 +98,29 @@ function closestKeyword(word) {
98
98
  }
99
99
 
100
100
  // Format an error message with position info from a token when available.
101
+ // Words that can never be used as declaration names (variable, function,
102
+ // parameter). Documentation copy for docs/PLAINSCRIPT-GRAMMAR.md lives here so
103
+ // the error hints and the docs cannot drift apart.
104
+ const RESERVED_DECLARATION_WORDS = {
105
+ remember: true, let: true, show: true, print: true, display: true,
106
+ as: true, is: true, if: true, otherwise: true, else: true, done: true,
107
+ end: true, do: true, greater: true, less: true, than: true, make: true,
108
+ define: true, function: true, give: true, return: true, becomes: true,
109
+ for: true, each: true, every: true, in: true, while: true, use: true,
110
+ import: true, include: true, load: true, when: true, listens: true,
111
+ listen: true, on: true, json: true, file: true, serve: true, folder: true,
112
+ above: true, below: true, at: true, least: true, most: true, not: true,
113
+ empty: true, contains: true, starts: true, ends: true, with: true,
114
+ between: true, and: true, or: true, instanceof: true, now: true,
115
+ web: true, route: true, start: true, database: true, ask: true,
116
+ prompt: true, ocr: true, gather: true, filter: true, match: true,
117
+ against: true, pattern: true, parallel: true, stream: true, emit: true,
118
+ happens: true, catches: true, yield: true, symbol: true, debugger: true,
119
+ to: true, together: true, be: true, then: true, plus: true, minus: true,
120
+ times: true, raise: true, raises: true, choosing: true, uses: true,
121
+ fills: true, repeat: true, until: true, log: true,
122
+ };
123
+
101
124
  function makeError(message, token) {
102
125
  if (token && token.line) {
103
126
  return `Line ${token.line}, Column ${token.col}: ${message}`;
@@ -105,13 +128,91 @@ function makeError(message, token) {
105
128
  return message;
106
129
  }
107
130
 
131
+ // When a declaration name is a reserved word, say so explicitly instead of a
132
+ // generic "Expected a variable/function name" (torture-test discoverability fix).
133
+ // Note: `back`, `total`, `reply`, `respond`, `send` and SQL words are
134
+ // deliberately usable as declaration names, so they are not listed here.
135
+ // (`file` is accepted as a variable name by `remember` but not as a
136
+ // function name, so it stays listed.)
137
+ function reservedWordHint(token) {
138
+ if (token && token.value && Object.prototype.hasOwnProperty.call(RESERVED_DECLARATION_WORDS, token.value)) {
139
+ return `\n\n"${token.value}" is a reserved PlainScript word and cannot be used as a name here. Pick a different name (see docs/PLAINSCRIPT-GRAMMAR.md).`;
140
+ }
141
+ return '';
142
+ }
143
+
108
144
  function parse(tokens) {
109
145
  let pos = 0;
110
146
  let _inRepeatCount = false;
111
-
147
+ const declaredTypeNames = new Set(['any', 'number', 'text', 'boolean', 'null', 'object']);
112
148
  function peek() { return tokens[pos]; }
113
149
  function peekAt(offset) { return tokens[pos + offset] || { type: TOKEN.EOF }; }
114
150
  function advance() { return tokens[pos++]; }
151
+ // v1.0.363 - at a block terminator? A done/together followed by "of" is a
152
+ // FIELD read ("done of item" - the README todo example), so it never closes a
153
+ // block. Every statement-bearing body loop must ask this instead of comparing
154
+ // the token type directly, or "done of t becomes true" inside an if/loop gets
155
+ // swallowed as the block's terminator.
156
+ function atBlockEnd() {
157
+ const t = peek();
158
+ if (t.type !== TOKEN.DONE && t.type !== TOKEN.TOGETHER) return false;
159
+ return !(peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'of');
160
+ }
161
+
162
+ // v1.0.364 - recursion depth guards. Nesting beyond ~700 levels recurses
163
+ // past V8's stack and crashes with a raw "Maximum call stack size exceeded"
164
+ // RangeError — no position, no PlainScript message. Both recursive funnels
165
+ // (expressions via parsePrimary, statements via parseBody) count depth and
166
+ // fail with a clean positional error long before the stack runs out. The
167
+ // limits are deliberately far below the measured crash threshold (~700
168
+ // expression levels / ~850 block levels) because the guards themselves
169
+ // consume stack; real code never nests anywhere near these numbers.
170
+ // ParseDepthError is a sentinel: speculative-parse probe sites (which catch
171
+ // and replay) must rethrow it, or deep inputs get re-parsed exponentially.
172
+ class ParseDepthError extends Error {}
173
+ const MAX_EXPR_DEPTH = 300;
174
+ const MAX_STMT_DEPTH = 200;
175
+ let exprDepth = 0;
176
+ let stmtDepth = 0;
177
+ // The typo-probe below speculatively parses a full statement to produce a
178
+ // helpful "Expected a comparison" error. Nested conditions make that probe
179
+ // re-parse the whole remainder at every level — exponential behaviour that
180
+ // hangs on legitimately deep (but valid) nesting. Two bounds keep it cheap:
181
+ // 1. block-structured statement starters are never probed (a typo'd
182
+ // comparison cannot look like "if ..."; probing would re-parse their
183
+ // entire bodies), and
184
+ // 2. probes may only nest a bounded number of levels; deeper levels take the
185
+ // plain bare-value condition path, which is what the probe concludes.
186
+ const MAX_CONDITION_PROBE_DEPTH = 3;
187
+ let conditionProbeDepth = 0;
188
+ const PROBE_BLOCKER_SET = new Set(
189
+ ['IF', 'WHILE', 'FOR', 'REPEAT', 'EACH', 'EVERY', 'MAKE', 'DEFINE', 'FUNCTION',
190
+ 'TO', 'TRY', 'WHEN', 'USE', 'IMPORT', 'INCLUDE', 'LOAD', 'GATHER', 'FILTER_KW',
191
+ 'TOTAL', 'MATCH', 'EMIT', 'STREAM', 'LISTEN', 'START_KW', 'START_ON', 'SERVE',
192
+ 'SERVE_ON', 'SERVE_STATIC', 'SERVE_PUBLIC', 'DATABASE_KW', 'CONNECT_DB',
193
+ 'USE_DATABASE', 'ROUTE_KW', 'WEB', 'ASK', 'PROMPT', 'OCR_KW', 'REPLY',
194
+ 'RESPOND', 'SEND_BACK', 'DEBUGGER_KW', 'TEST']
195
+ .filter(k => TOKEN[k] !== undefined)
196
+ .map(k => TOKEN[k])
197
+ );
198
+ const PROBE_BLOCKER_WORDS = new Set(
199
+ ['bring', 'repeat', 'define', 'when', 'start', 'serve', 'database', 'every',
200
+ 'try', 'catch', 'class', 'test', 'respond', 'listen']
201
+ );
202
+
203
+ function parsePrimary() {
204
+ if (++exprDepth > MAX_EXPR_DEPTH) {
205
+ throw new ParseDepthError(makeError(
206
+ `Expression is nested more than ${MAX_EXPR_DEPTH} levels deep. Split it into intermediate variables.`,
207
+ peek()
208
+ ));
209
+ }
210
+ try {
211
+ return parsePrimaryInner();
212
+ } finally {
213
+ exprDepth--;
214
+ }
215
+ }
115
216
 
116
217
  function consume(expectedType, hint) {
117
218
  const token = tokens[pos];
@@ -210,7 +311,41 @@ function parse(tokens) {
210
311
  // Comparisons are expressions too, so parseExpression may already have
211
312
  // folded this into a comparison node - that IS the comparison level.
212
313
  if (isComparisonNode(left)) return left;
213
- return tryParseComparisonOperator(left, true);
314
+ const result = tryParseComparisonOperator(left, false);
315
+ if (result !== left) return result;
316
+ // No comparison operator: the value itself is the condition (`if ok`,
317
+ // `if not fileExists("x")`, `while connected`) - a truthy check, like
318
+ // JavaScript's `if (value)`. But a bare identifier followed by a word that
319
+ // cannot start a statement is almost certainly a typo'd comparison
320
+ // ("if x bigger 1" for "if x is greater than 1"), so probe the parser to
321
+ // keep the helpful comparison error in that case and only treat clear
322
+ // statement/block boundaries as a bare-value condition.
323
+ const next = peek();
324
+ const isBoundary = next.type === TOKEN.DONE || next.type === TOKEN.OTHERWISE ||
325
+ next.type === TOKEN.ELSE ||
326
+ next.type === TOKEN.TOGETHER || next.type === TOKEN.THEN || next.type === TOKEN.EOF;
327
+ const probeBlockedByToken = PROBE_BLOCKER_SET.has(next.type) ||
328
+ (next.type === TOKEN.IDENTIFIER && PROBE_BLOCKER_WORDS.has(next.value));
329
+ if (!isBoundary && !probeBlockedByToken && conditionProbeDepth < MAX_CONDITION_PROBE_DEPTH) {
330
+ const savedPos = pos;
331
+ conditionProbeDepth++;
332
+ try {
333
+ const stmt = parseStatement();
334
+ pos = savedPos;
335
+ if (!stmt) return { type: 'ConditionExpression', value: left };
336
+ } catch (e) {
337
+ // Depth-limit sentinels must never be swallowed by speculative probes:
338
+ // the alternative is exponential re-parsing of deep inputs.
339
+ if (e instanceof ParseDepthError) throw e;
340
+ throw new Error(makeError(
341
+ 'Expected a comparison after the value. Use "is", "is above", "is below", "contains", "starts with", etc.',
342
+ peek()
343
+ ));
344
+ } finally {
345
+ conditionProbeDepth--;
346
+ }
347
+ }
348
+ return { type: 'ConditionExpression', value: left };
214
349
  }
215
350
 
216
351
  // Shared comparison-operator continuation. Given an already-parsed left
@@ -489,6 +624,31 @@ function parse(tokens) {
489
624
  function parseStatementCore() {
490
625
  const token = peek();
491
626
 
627
+ // Intent declarations share function semantics but remain distinct in the
628
+ // AST so future tooling can retain the author's stated intent.
629
+ if (token.type === TOKEN.IDENTIFIER && token.value === 'intend') {
630
+ return parseIntentDeclaration();
631
+ }
632
+
633
+ // `type User ... done` is contextual so existing identifier expressions
634
+ // remain compatible outside statement position.
635
+ if (token.type === TOKEN.IDENTIFIER && token.value === 'type' &&
636
+ peekAt(1).type === TOKEN.IDENTIFIER) {
637
+ return parseTypeDeclaration();
638
+ }
639
+
640
+ // v1.0.363 - `done` can name a record field ("record with text "milk" and
641
+ // done true"), so the statement-position target "done of t becomes ..."
642
+ // must parse; anything else starting with the done keyword keeps its
643
+ // terminator meaning.
644
+ if ((token.type === TOKEN.DONE || token.type === TOKEN.TOGETHER) &&
645
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'of') {
646
+ const expr = parsePrimary();
647
+ consume(TOKEN.BECOMES, 'Expected "becomes" after "done of <record>".\n\nExample:\n done of item becomes true');
648
+ const value = parseExpression();
649
+ return { type: 'BecomeStatement', target: expr, value, op: '=' };
650
+ }
651
+
492
652
  // "define a kind called ..." - must check before DEFINE token dispatch
493
653
  if ((token.type === TOKEN.DEFINE || (token.type === TOKEN.IDENTIFIER && token.value === 'define')) &&
494
654
  peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'a') {
@@ -545,7 +705,7 @@ function parse(tokens) {
545
705
  peekAt(2).type === TOKEN.IDENTIFIER && TIME_UNITS[peekAt(2).value]) {
546
706
  return parseEvery();
547
707
  }
548
- // v1.0.362 - every frame … done: requestAnimationFrame loop. "every" lexes
708
+ // v1.0.363 - every frame … done: requestAnimationFrame loop. "every" lexes
549
709
  // as TOKEN.EACH; guard on the following "frame" identifier ("for every
550
710
  // item in list" is intercepted by TOKEN.FOR above).
551
711
  if (token.type === TOKEN.EACH && peekAt(1).type === TOKEN.IDENTIFIER &&
@@ -599,16 +759,20 @@ function parse(tokens) {
599
759
  if (token.type === TOKEN.QUERY_KW && peekAt(1).type === TOKEN.LPAREN) {
600
760
  return { type: 'ExpressionStatement', expression: parseCallExpression() };
601
761
  }
602
- if (token.type === TOKEN.QUERY_KW) return parseSqlBlock('query', 'QueryStatement');
603
- if (token.type === TOKEN.INSERT_KW) return parseSqlBlock('insert', 'InsertStatement');
604
- if (token.type === TOKEN.UPDATE_KW) return parseSqlBlock('update', 'UpdateStatement');
762
+ // v1.0.363 - when the lexer did NOT capture a raw SQL body (the word is
763
+ // not alone on its line), query/insert/update/execute are ordinary names
764
+ // and flow through the identifier branch below.
765
+ if (token.type === TOKEN.QUERY_KW && peekAt(1).type === TOKEN.SQL_BODY) return parseSqlBlock('query', 'QueryStatement');
766
+ if (token.type === TOKEN.INSERT_KW && peekAt(1).type === TOKEN.SQL_BODY) return parseSqlBlock('insert', 'InsertStatement');
767
+ if (token.type === TOKEN.UPDATE_KW && peekAt(1).type === TOKEN.SQL_BODY) return parseSqlBlock('update', 'UpdateStatement');
605
768
  // v2.1.1 - delete "<url>" is an HTTP DELETE request; a bare "delete"
606
769
  // starting a raw block keeps its SQL meaning.
607
770
  if (token.type === TOKEN.DELETE_KW && tokenStartsValue(peekAt(1))) {
608
771
  return { type: 'ExpressionStatement', expression: parseHttpCall('delete') };
609
772
  }
610
773
  if (token.type === TOKEN.DELETE_KW) return parseSqlBlock('delete', 'DeleteStatement');
611
- if (token.type === TOKEN.EXECUTE_KW) return parseSqlBlock('execute', 'ExecuteStatement');
774
+ if (token.type === TOKEN.EXECUTE_KW && peekAt(1).type === TOKEN.SQL_BODY) return parseSqlBlock('execute', 'ExecuteStatement');
775
+
612
776
 
613
777
  // IOPL-native features
614
778
  if (token.type === TOKEN.GATHER) return parseGatherStatement();
@@ -627,7 +791,7 @@ function parse(tokens) {
627
791
  }
628
792
 
629
793
  // Statements starting with an identifier: call, becomes, index/member becomes
630
- if (token.type === TOKEN.IDENTIFIER) {
794
+ if (token.type === TOKEN.IDENTIFIER || isSqlWordIdentifier(token)) {
631
795
  // v2.5 - natural string and collection verbs that transform a variable
632
796
  // in place: "lowercase title", "uppercase first letter of each word in title",
633
797
  // "split title by \" \"", "join title by \" \"", "trim title".
@@ -689,7 +853,7 @@ function parse(tokens) {
689
853
  // return statement
690
854
  if (token.value === 'return' && peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
691
855
  advance();
692
- const value = peek().type !== TOKEN.DONE && peek().type !== TOKEN.EOF && peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.RBRACE
856
+ const value = peek().type !== TOKEN.DONE && peek().type !== TOKEN.EOF && peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.ELSE && peek().type !== TOKEN.RBRACE
693
857
  ? parseExpression()
694
858
  : null;
695
859
  return { type: 'ReturnStatement', value };
@@ -797,14 +961,14 @@ function parse(tokens) {
797
961
  return parseEvery();
798
962
  }
799
963
 
800
- // v1.0.362 - every frame … done: requestAnimationFrame loop. Identifier
964
+ // v1.0.363 - every frame … done: requestAnimationFrame loop. Identifier
801
965
  // mirror of the EACH dispatch above.
802
966
  if (token.value === 'every' && peekAt(1).type === TOKEN.IDENTIFIER &&
803
967
  peekAt(1).value === 'frame') {
804
968
  return parseEveryFrame();
805
969
  }
806
970
 
807
- // v1.0.362 - after <n> <unit>s … done: one-shot delayed execution.
971
+ // v1.0.363 - after <n> <unit>s … done: one-shot delayed execution.
808
972
  // Contextual like "retry": "after becomes 5" and after(...) keep their
809
973
  // ordinary meanings.
810
974
  if (token.value === 'after' &&
@@ -827,7 +991,8 @@ function parse(tokens) {
827
991
  advance(); // run
828
992
  advance(); // background
829
993
  const call = parsePrimary();
830
- if (call.type !== 'CallExpression') {
994
+ if (call.type !== 'CallExpression' && call.type !== 'AddCall' &&
995
+ call.type !== 'RemoveCall' && call.type !== 'WriteCall') {
831
996
  throw new Error(makeError(
832
997
  'Expected a function call after "run background".\n\nExample:\n run background resizeImage("photo.png")',
833
998
  peek()
@@ -993,6 +1158,28 @@ function parse(tokens) {
993
1158
  peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'cookie') {
994
1159
  return parseSetCookie();
995
1160
  }
1161
+
1162
+ // v1.0.363 - prefix assignment forms: "set <target> to <value>" and
1163
+ // "change <target> to <value>" are aliases for "<target> becomes <value>".
1164
+ // Contextual: a variable named "set" or "change" keeps its usual meaning
1165
+ // unless a value and "to" follow. "set cookie" and "set with" keep their
1166
+ // own meanings and are intercepted before this point/expression level.
1167
+ if ((token.value === 'set' || token.value === 'change') &&
1168
+ !(peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'with')) {
1169
+ const verb = token.value;
1170
+ advance(); // set / change
1171
+ const target = parseExpression();
1172
+ if (peek().type !== TOKEN.TO &&
1173
+ !(peek().type === TOKEN.IDENTIFIER && peek().value === 'to')) {
1174
+ throw new Error(makeError(
1175
+ `Expected "to" after the target of "${verb}".\n\nExample:\n ${verb} age to 17`,
1176
+ peek()
1177
+ ));
1178
+ }
1179
+ advance(); // to
1180
+ const value = parseExpression();
1181
+ return { type: 'BecomeStatement', target, value, op: '=' };
1182
+ }
996
1183
  if (token.value === 'clear' &&
997
1184
  peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'cookie') {
998
1185
  advance(); // clear
@@ -1088,8 +1275,20 @@ function parse(tokens) {
1088
1275
  // Assignment operators: becomes, is now, set to, change to, or becomes (||=), and becomes (&&=), nullish becomes (??=)
1089
1276
  let becomeOp = null;
1090
1277
  if (peek().type === TOKEN.PLUS_ASSIGN) {
1091
- advance(); // ++=
1278
+ advance(); // += (or the legacy ++=)
1092
1279
  becomeOp = '+=';
1280
+ } else if (peek().type === TOKEN.MINUS_ASSIGN) {
1281
+ advance(); // -=
1282
+ becomeOp = '-=';
1283
+ } else if (peek().type === TOKEN.STAR_ASSIGN) {
1284
+ advance(); // *=
1285
+ becomeOp = '*=';
1286
+ } else if (peek().type === TOKEN.SLASH_ASSIGN) {
1287
+ advance(); // /=
1288
+ becomeOp = '/=';
1289
+ } else if (peek().type === TOKEN.PERCENT_ASSIGN) {
1290
+ advance(); // %=
1291
+ becomeOp = '%=';
1093
1292
  } else if (peek().type === TOKEN.LOGICAL_OR_ASSIGN) {
1094
1293
  advance(); // ||=
1095
1294
  becomeOp = '||=';
@@ -1124,6 +1323,16 @@ function parse(tokens) {
1124
1323
  } else if (peek().type === TOKEN.CHANGE_TO) {
1125
1324
  advance(); // change to
1126
1325
  becomeOp = '=';
1326
+ } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'set' &&
1327
+ peekAt(1).type === TOKEN.TO) {
1328
+ advance(); // set
1329
+ advance(); // to
1330
+ becomeOp = '=';
1331
+ } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'change' &&
1332
+ peekAt(1).type === TOKEN.TO) {
1333
+ advance(); // change
1334
+ advance(); // to
1335
+ becomeOp = '=';
1127
1336
  }
1128
1337
 
1129
1338
  if (becomeOp !== null) {
@@ -1171,6 +1380,7 @@ function parse(tokens) {
1171
1380
 
1172
1381
  // Check for destructuring patterns: [ ... ] or { ... }
1173
1382
  let target;
1383
+ let nameLine = peek().line;
1174
1384
  if (peek().type === TOKEN.LBRACKET) {
1175
1385
  target = parseArrayLiteral(); // returns ArrayLiteral with elements
1176
1386
  target.type = 'ArrayPattern';
@@ -1181,26 +1391,59 @@ function parse(tokens) {
1181
1391
  // Allow contextual keywords as variable names in remember declarations
1182
1392
  let nameToken = peek();
1183
1393
  const REMEMBER_KEYWORDS = new Set([TOKEN.BACK, TOKEN.TOTAL, TOKEN.REPLY, TOKEN.RESPOND, TOKEN.SEND_BACK, TOKEN.FILE_KW]);
1184
- if (REMEMBER_KEYWORDS.has(nameToken.type)) {
1394
+ if (REMEMBER_KEYWORDS.has(nameToken.type) || isSqlWordIdentifier(nameToken)) {
1185
1395
  advance();
1186
1396
  target = nameToken.value;
1187
1397
  } else {
1188
1398
  target = consume(
1189
1399
  TOKEN.IDENTIFIER,
1190
- `Expected a variable name after "${isLet ? 'let' : 'remember'}".\n\nExample:\n ${isLet ? 'let age is 16' : 'remember age as 16'}`
1400
+ `Expected a variable name after "${isLet ? 'let' : 'remember'}".${reservedWordHint(nameToken)}\n\nExample:\n ${isLet ? 'let age is 16' : 'remember age as 16'}`
1191
1401
  ).value;
1192
1402
  }
1403
+ nameLine = nameToken.line;
1404
+ }
1405
+
1406
+ let typeAnnotation = null;
1407
+ // Typed mutable binding: `let users as list of User is [...]`. The
1408
+ // lookahead keeps legacy `let value as 42` default/initializer syntax
1409
+ // unchanged because only a recognized type expression followed by `is` or
1410
+ // `be` enters this path.
1411
+ if (isLet && peek().type === TOKEN.AS && isTypeNameStart(peekAt(1))) {
1412
+ const saved = pos;
1413
+ advance();
1414
+ try {
1415
+ const candidate = parseTypeSpec();
1416
+ if (peek().type === TOKEN.IS || peek().type === TOKEN.BE) {
1417
+ typeAnnotation = candidate;
1418
+ advance();
1419
+ } else {
1420
+ pos = saved;
1421
+ }
1422
+ } catch (_) {
1423
+ pos = saved;
1424
+ }
1193
1425
  }
1194
1426
 
1195
1427
  // Object literal: next token is IDENTIFIER (except dictionary/map) followed by IS or BE
1196
1428
  if (peek().type === TOKEN.IDENTIFIER && peek().value !== 'dictionary' && peek().value !== 'map' && (peekAt(1).type === TOKEN.IS || peekAt(1).type === TOKEN.BE) && !isObjectShorthandAmbiguousWithComparison()) {
1197
1429
  const init = parseInlineObjectLiteral(false);
1198
- return { type: 'VariableDeclaration', name: target, initializer: init, isLet, isConstant: !isLet };
1430
+ return { type: 'RememberStatement', name: target, value: init, typeAnnotation, isLet, isConstant: !isLet };
1431
+ }
1432
+
1433
+ if (typeAnnotation) {
1434
+ return { type: 'RememberStatement', name: target, value: parseExpression(), typeAnnotation, isLet, isConstant: !isLet };
1199
1435
  }
1200
1436
 
1201
1437
  // "let" uses "is" or "be" for simple vars, but also accepts "as" for both simple and destructuring
1202
1438
  // "remember" always uses "as"
1439
+ // v1.0.363 - an uninitialized declaration ("let undef") is accepted and
1440
+ // binds undefined; typical before "undef nullish becomes "default"".
1203
1441
  const isDestructuring = target && typeof target === 'object' && (target.type === 'ArrayPattern' || target.type === 'ObjectPattern');
1442
+ // The statement's name token is on the declaration line; a next token on a
1443
+ // LATER line means no initializer follows on that line.
1444
+ if (!isDestructuring && typeof target === 'string' && peek().line > nameLine) {
1445
+ return { type: 'RememberStatement', name: target, value: null, typeAnnotation, isLet, isConstant: !isLet };
1446
+ }
1204
1447
  const assignToken = isLet ? ((peek().type === TOKEN.IS || peek().type === TOKEN.BE) ? peek().type : TOKEN.AS) : TOKEN.AS;
1205
1448
  const expectedKeyword = (isLet && (peek().type === TOKEN.IS || peek().type === TOKEN.BE)) ? (peek().type === TOKEN.BE ? 'be' : 'is') : 'as';
1206
1449
  consume(
@@ -1210,7 +1453,7 @@ function parse(tokens) {
1210
1453
 
1211
1454
  // Object literal: next token is IDENTIFIER followed by IS or BE
1212
1455
  if (peek().type === TOKEN.IDENTIFIER && (peekAt(1).type === TOKEN.IS || peekAt(1).type === TOKEN.BE) && !isObjectShorthandAmbiguousWithComparison()) {
1213
- return { type: 'RememberStatement', name: target, value: parseObjectLiteral() };
1456
+ return { type: 'RememberStatement', name: target, value: parseObjectLiteral(), typeAnnotation };
1214
1457
  }
1215
1458
 
1216
1459
  // v2.1.0 - remember <name> as query|insert|update|delete … done
@@ -1229,7 +1472,7 @@ function parse(tokens) {
1229
1472
  }
1230
1473
 
1231
1474
  const value = parseExpression();
1232
- return { type: 'RememberStatement', name: target, value };
1475
+ return { type: 'RememberStatement', name: target, value, typeAnnotation };
1233
1476
  }
1234
1477
 
1235
1478
  // ask <variable>
@@ -1352,7 +1595,7 @@ function parseAsk() {
1352
1595
  const nameToken = peek();
1353
1596
  if (nameToken.type !== TOKEN.IDENTIFIER && nameToken.type !== TOKEN.LOAD) {
1354
1597
  throw new Error(makeError(
1355
- `Expected a function name after "${keyword}".\n\nExample:\n ${keyword} greet()\n show "Hello"\n done`,
1598
+ `Expected a function name after "${keyword}".${reservedWordHint(nameToken)}\n\nExample:\n ${keyword} greet()\n show "Hello"\n done`,
1356
1599
  nameToken
1357
1600
  ));
1358
1601
  }
@@ -1360,8 +1603,89 @@ function parseAsk() {
1360
1603
  consume(TOKEN.LPAREN, `Expected "(" after function name "${name}".`);
1361
1604
  const params = parseParamList();
1362
1605
  consume(TOKEN.RPAREN, 'Expected ")" to close the parameter list.');
1606
+ let returnType = null;
1607
+ if (peek().type === TOKEN.IDENTIFIER && (peek().value === 'returns' || peek().value === 'returning')) {
1608
+ advance();
1609
+ returnType = parseTypeSpec();
1610
+ }
1363
1611
  const body = parseBody(`function "${name}"`);
1364
- return { type: 'FunctionDeclaration', name, params, body };
1612
+ return { type: 'FunctionDeclaration', name, params, returnType, body };
1613
+ }
1614
+
1615
+ function parseIntentDeclaration() {
1616
+ advance(); // intend
1617
+ const nameToken = consume(TOKEN.IDENTIFIER, 'Expected an intent name after "intend".');
1618
+ const name = nameToken.value;
1619
+ consume(TOKEN.LPAREN, `Expected "(" after intent name "${name}".`);
1620
+ const params = parseParamList();
1621
+ consume(TOKEN.RPAREN, 'Expected ")" to close the intent parameter list.');
1622
+ let returnType = null;
1623
+ if (peek().type === TOKEN.IDENTIFIER && (peek().value === 'returns' || peek().value === 'returning')) {
1624
+ advance();
1625
+ returnType = parseTypeSpec();
1626
+ }
1627
+ const body = parseBody(`intent "${name}"`);
1628
+ return {
1629
+ type: 'IntentDeclaration',
1630
+ name,
1631
+ params,
1632
+ returnType,
1633
+ body,
1634
+ intent: { kind: 'declaration', name, parameterCount: params.length },
1635
+ };
1636
+ }
1637
+
1638
+ const primitiveTypeNames = new Set(['any', 'number', 'text', 'boolean', 'null', 'object']);
1639
+ function isTypeNameStart(token) {
1640
+ return token && token.type === TOKEN.IDENTIFIER &&
1641
+ (declaredTypeNames.has(token.value) || primitiveTypeNames.has(token.value) ||
1642
+ ['optional', 'list', 'dictionary'].includes(token.value) || /^[A-Z]/.test(token.value));
1643
+ }
1644
+ function parseTypeAtom() {
1645
+ const token = peek();
1646
+ if (token.type === TOKEN.IDENTIFIER && token.value === 'optional') {
1647
+ advance();
1648
+ return { kind: 'optional', value: parseTypeSpec() };
1649
+ }
1650
+ if (token.type === TOKEN.IDENTIFIER && (token.value === 'list' || token.value === 'dictionary')) {
1651
+ const kind = advance().value;
1652
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') advance();
1653
+ return { kind, value: parseTypeSpec() };
1654
+ }
1655
+ if (!isTypeNameStart(token) && token.type !== TOKEN.NULL_KW) {
1656
+ throw new Error(makeError('Expected a type name (number, text, boolean, object, or a declared type).', token));
1657
+ }
1658
+ advance();
1659
+ return { kind: 'name', name: token.value };
1660
+ }
1661
+ function parseTypeSpec() {
1662
+ const types = [parseTypeAtom()];
1663
+ while ((peek().type === TOKEN.OR || (peek().type === TOKEN.IDENTIFIER && peek().value === 'or')) &&
1664
+ peekAt(1).line === peek().line) {
1665
+ advance();
1666
+ types.push(parseTypeAtom());
1667
+ }
1668
+ return types.length === 1 ? types[0] : { kind: 'union', values: types };
1669
+ }
1670
+ function parseTypeDeclaration() {
1671
+ advance(); // type
1672
+ const nameToken = consume(TOKEN.IDENTIFIER, 'Expected a type name after "type".');
1673
+ const name = nameToken.value;
1674
+ if (declaredTypeNames.has(name)) {
1675
+ throw new Error(makeError(`Type "${name}" is already declared.`, nameToken));
1676
+ }
1677
+ declaredTypeNames.add(name);
1678
+ const fields = [];
1679
+ while (!atBlockEnd()) {
1680
+ if (peek().type === TOKEN.EOF) {
1681
+ throw new Error(makeError(`Expected keyword "done" to close type "${name}".`, peek()));
1682
+ }
1683
+ const field = consume(TOKEN.IDENTIFIER, `Expected a field name in type "${name}".`);
1684
+ consume(TOKEN.IS, `Expected "is" after field name "${field.value}".`);
1685
+ fields.push({ key: field.value, type: parseTypeSpec(), optional: false });
1686
+ }
1687
+ advance();
1688
+ return { type: 'TypeDeclaration', name, fields };
1365
1689
  }
1366
1690
 
1367
1691
  // v2.3 - English-like function declaration: "to <name> <a> and <b> together ... done"
@@ -1376,21 +1700,34 @@ function parseAsk() {
1376
1700
  ));
1377
1701
  }
1378
1702
  const name = advance().value;
1703
+ const nameLine = nameToken.line;
1379
1704
  const params = [];
1380
- // Parameters are identifiers joined by "and"
1381
- while (peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.DONE) {
1382
- if (peek().type === TOKEN.AND) {
1383
- advance(); // skip "and" between parameters
1384
- continue;
1385
- }
1705
+ // Parameters are identifiers joined by "and". The header ends at
1706
+ // "together"/"done" on the SAME line, or when the body begins on a later
1707
+ // line. The line rule is what makes the zero-parameter form work:
1708
+ // to loadTodos
1709
+ // show "reading"
1710
+ // done
1711
+ // Previously the header loop read the first body token as an attempted
1712
+ // parameter and failed with "Expected a parameter name".
1713
+ while (true) {
1386
1714
  if (peek().type === TOKEN.EOF) {
1387
1715
  throw new Error(makeError(
1388
1716
  `Expected "together" or "done" to close function "${name}" before end of file.`,
1389
1717
  peek()
1390
1718
  ));
1391
1719
  }
1720
+ if (peek().line > nameLine) break; // body starts on a later line
1721
+ if (peek().type === TOKEN.TOGETHER || peek().type === TOKEN.DONE) {
1722
+ advance(); // header terminator on the header line
1723
+ break;
1724
+ }
1725
+ if (peek().type === TOKEN.AND) {
1726
+ advance(); // skip "and" between parameters
1727
+ continue;
1728
+ }
1392
1729
  const paramToken = peek();
1393
- if (paramToken.type !== TOKEN.IDENTIFIER) {
1730
+ if (paramToken.type !== TOKEN.IDENTIFIER && !isSqlWordIdentifier(paramToken)) {
1394
1731
  throw new Error(makeError(
1395
1732
  `Expected a parameter name or "together"/"done" in function "${name}".`,
1396
1733
  paramToken
@@ -1398,9 +1735,6 @@ function parseAsk() {
1398
1735
  }
1399
1736
  params.push({ name: advance().value });
1400
1737
  }
1401
- // The params loop stops at "together"/"done" - consume the terminator here
1402
- // so parseBody parses the real body instead of treating this as an empty one.
1403
- advance(); // consume "together" or "done"
1404
1738
  const body = parseBody(`function "${name}"`);
1405
1739
  return { type: 'FunctionDeclaration', name, params, body };
1406
1740
  }
@@ -1423,13 +1757,31 @@ function parseAsk() {
1423
1757
 
1424
1758
  function parseListWith() {
1425
1759
  // Accept both "list_with" keyword and contextual "list" + "with"
1760
+ const openerLine = peek().line;
1426
1761
  if (peek().type === TOKEN.LIST_WITH) {
1427
1762
  consume(TOKEN.LIST_WITH);
1428
1763
  } else {
1429
1764
  advance(); // "list"
1430
1765
  consume(TOKEN.WITH, 'Expected "with" after "list".');
1431
1766
  }
1432
- const elements = parseListWithElements();
1767
+ // v1.0.363 - block form: first element on a later line, one element per
1768
+ // line, closed by its own "done"/"end". Previously the terminator was
1769
+ // never consumed here, so "list with\n record ...\nend" leaked "end".
1770
+ const blockForm = peek().line > openerLine;
1771
+ const elements = [];
1772
+ if (blockForm) {
1773
+ while (canContinueElement(peek())) {
1774
+ elements.push(parseBooleanAtom());
1775
+ while (peek().type === TOKEN.COMMA ||
1776
+ peek().type === TOKEN.AND ||
1777
+ (peek().type === TOKEN.IDENTIFIER && peek().value === 'and')) {
1778
+ advance();
1779
+ }
1780
+ }
1781
+ } else {
1782
+ elements.push(...parseListWithElements());
1783
+ }
1784
+ consumeCollectionTerminator(openerLine, blockForm, elements.length > 0);
1433
1785
  return { type: 'ArrayLiteral', elements };
1434
1786
  }
1435
1787
 
@@ -1437,6 +1789,7 @@ function parseAsk() {
1437
1789
  // consumeTerminator: true when used as expression (done closes record), false when standalone statement
1438
1790
  function parseRecordWith(consumeTerminator) {
1439
1791
  // Accept both "record_with" keyword and contextual "record" + "with"
1792
+ const openerLine = peek().line;
1440
1793
  if (peek().type === TOKEN.RECORD_WITH) {
1441
1794
  consume(TOKEN.RECORD_WITH);
1442
1795
  } else {
@@ -1444,15 +1797,50 @@ function parseAsk() {
1444
1797
  consume(TOKEN.WITH, 'Expected "with" after "record".');
1445
1798
  }
1446
1799
  const properties = [];
1447
- while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.EOF) {
1800
+ const recordStartLine = peek().line;
1801
+ // v1.0.363 - block form: first field on a later line. In that shape a
1802
+ // trailing done/together is the record's own terminator; in inline shape a
1803
+ // done on a LATER line belongs to the enclosing block and must be left
1804
+ // alone (it used to be swallowed, breaking "if ... record with ... done").
1805
+ const blockForm = recordStartLine > openerLine;
1806
+ while (true) {
1448
1807
  const keyToken = peek();
1449
- if (keyToken.type !== TOKEN.IDENTIFIER) {
1808
+ // `done`/`together` may name a FREQUENT boolean field, as in a todo item:
1809
+ // record with text "milk" and done true (a value follows on the same line).
1810
+ // A following "of" is the field-READ shape ("done of item") instead, so
1811
+ // the record must end there rather than eat "done of t ..." as fields.
1812
+ if ((keyToken.type === TOKEN.DONE || keyToken.type === TOKEN.TOGETHER) &&
1813
+ isRecordFieldValueStart(peekAt(1)) && peekAt(1).line === keyToken.line &&
1814
+ peekAt(1).value !== 'of') {
1815
+ advance(); // consume `done` (or `together`) as a field name
1816
+ } else if (keyToken.type === TOKEN.DONE || keyToken.type === TOKEN.TOGETHER ||
1817
+ keyToken.type === TOKEN.EOF ||
1818
+ keyToken.type === TOKEN.TO || keyToken.type === TOKEN.FROM ||
1819
+ (keyToken.type === TOKEN.IDENTIFIER && keyToken.value === 'from') ||
1820
+ keyToken.type === TOKEN.RPAREN || keyToken.type === TOKEN.COMMA ||
1821
+ keyToken.type === TOKEN.RBRACKET) {
1822
+ break; // block terminator, add/remove special forms, or value boundaries
1823
+ } else if (keyToken.type === TOKEN.IDENTIFIER || keyToken.type === TOKEN.STRING ||
1824
+ keyToken.type === TOKEN.NUMBER) {
1825
+ advance(); // consume key
1826
+ } else if (isRecordFieldKeyword(keyToken)) {
1827
+ // Keyword words (`total`, `back`) work as fields when a value follows
1828
+ // on the same line; on a later line a keyword starts a new statement.
1829
+ if (isRecordFieldValueStart(peekAt(1)) &&
1830
+ peekAt(1).line === keyToken.line &&
1831
+ (keyToken.line === recordStartLine || !isRecordStatementOpener(keyToken))) {
1832
+ advance(); // consume keyword as a field name
1833
+ } else {
1834
+ break;
1835
+ }
1836
+ } else if (isRecordStatementOpener(keyToken)) {
1837
+ break; // next statement begins: the record is finished
1838
+ } else {
1450
1839
  throw new Error(makeError(
1451
1840
  'Expected a property name after "record with".\n\nExample:\n record with name "Alice" and age 30',
1452
1841
  keyToken
1453
1842
  ));
1454
1843
  }
1455
- advance(); // consume key
1456
1844
  const key = keyToken.value;
1457
1845
  if (peek().type === TOKEN.DONE || peek().type === TOKEN.TOGETHER || peek().type === TOKEN.EOF || peek().type === TOKEN.AND) {
1458
1846
  properties.push({ key, value: { type: 'UndefinedLiteral' } });
@@ -1464,19 +1852,142 @@ function parseAsk() {
1464
1852
  advance(); // consume "and"
1465
1853
  }
1466
1854
  }
1467
- if (consumeTerminator && (peek().type === TOKEN.DONE || peek().type === TOKEN.TOGETHER)) {
1468
- advance(); // consume done/together when used as expression
1855
+ if (consumeTerminator) {
1856
+ consumeCollectionTerminator(openerLine, blockForm, properties.length > 0);
1469
1857
  }
1470
1858
  return { type: 'InlineObjectLiteral', properties };
1471
1859
  }
1472
1860
 
1861
+ // True for keyword tokens that can serve as record field names and never
1862
+ // begin a PlainScript statement alone (`total`, `back`). Also covers both
1863
+ // structural words (now, folder, pattern, ...) and words that double as
1864
+ // statement openers (status, reply, send, ...) - those only act as fields
1865
+ // when parsed on the record's own line (see the loop above). Exotic keys
1866
+ // (fields named `show`, `give`, ...) stay expressible via { ... } literals.
1867
+ const RECORD_FIELD_KEYWORDS = new Set([
1868
+ 'total', 'back', 'yield', 'match', 'retry', 'cache', 'route', 'group',
1869
+ 'status', 'reply', 'send', 'log', 'bot', 'mail', 'catch', 'recover',
1870
+ 'folder', 'now', 'gather', 'stream', 'parallel', 'against', 'pattern',
1871
+ 'start', 'serve', 'listen', 'run', 'wait', 'exit', 'put', 'unpack',
1872
+ 'set', 'change', 'add', 'remove', 'write', 'read', 'load', 'schedule',
1873
+ 'every', 'accept', 'limit', 'require', 'enable', 'disable', 'allow',
1874
+ 'google', 'websocket', 'postgres', 'database', 'query', 'insert',
1875
+ 'update', 'delete', 'execute', 'transaction', 'destroy', 'redirect',
1876
+ ]);
1877
+ function isRecordFieldKeyword(tok) {
1878
+ if (!tok || typeof tok.value !== 'string') return false;
1879
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(tok.value)) return false;
1880
+ return RECORD_FIELD_KEYWORDS.has(tok.value);
1881
+ }
1882
+
1883
+ // True for keyword tokens that always begin a PlainScript statement. When
1884
+ // one follows a record's fields, the record is finished (the keyword starts
1885
+ // the next statement); without this, `record with a 1` followed by `show
1886
+ // x` would try to read `show` as a field name.
1887
+ function isRecordStatementOpener(tok) {
1888
+ if (!tok || typeof tok.value !== 'string') return false;
1889
+ return [
1890
+ 'show', 'print', 'display', 'log', 'let', 'remember', 'give', 'return',
1891
+ 'make', 'intend', 'define', 'function', 'use', 'import', 'bring', 'export', 'ask',
1892
+ 'prompt', 'if', 'when', 'while', 'for', 'each', 'repeat', 'test', 'check',
1893
+ 'try', 'raise', 'yield', 'listen', 'start', 'serve', 'run', 'reply',
1894
+ 'status', 'send', 'wait', 'exit', 'put', 'unpack', 'set', 'change',
1895
+ 'add', 'remove', 'write', 'read', 'load', 'schedule', 'every', 'cache',
1896
+ 'route', 'group', 'redirect', 'destroy', 'accept', 'limit', 'require',
1897
+ 'enable', 'disable', 'allow', 'google', 'websocket', 'mail', 'whatsapp',
1898
+ 'telegram', 'bot', 'postgres', 'database', 'query', 'insert', 'update',
1899
+ 'delete', 'execute', 'transaction', 'retry', 'match', 'recover',
1900
+ 'finally', 'not', 'in', 'and', 'or', 'is', 'to', 'with', 'than', 'as',
1901
+ 'be', 'then', 'otherwise', 'else', 'above', 'below', 'at', 'least',
1902
+ 'most', 'between', 'contains', 'starts', 'ends', 'empty', 'now', 'back',
1903
+ 'folder', 'catch',
1904
+ ].includes(tok.value);
1905
+ }
1906
+
1907
+ // Tokens that can begin a value in "record with <name> <value>". Only these
1908
+ // make `done` look like a field name instead of the block terminator.
1909
+ function isRecordFieldValueStart(tok) {
1910
+ return !!tok && [
1911
+ TOKEN.NUMBER, TOKEN.STRING, TOKEN.IDENTIFIER, TOKEN.TRUE_KW, TOKEN.FALSE_KW,
1912
+ TOKEN.NULL_KW, TOKEN.LPAREN, TOKEN.LBRACKET, TOKEN.LBRACE, TOKEN.MINUS,
1913
+ ].includes(tok.type);
1914
+ }
1915
+
1916
+ // v1.0.363 - can this token begin a collection element on a LATER line?
1917
+ // Used to give "list with" / "dictionary with" / "set with" / "tuple with"
1918
+ // newline-separated element forms. Deliberately conservative: only literal
1919
+ // and literal-introducing starters qualify, so a following statement that
1920
+ // begins with a plain identifier ("score becomes 10") or a statement keyword
1921
+ // is never swallowed as an element.
1922
+ function canContinueElement(tok) {
1923
+ if (!tok || tok.type === TOKEN.EOF) return false;
1924
+ if (tok.type === TOKEN.NUMBER || tok.type === TOKEN.STRING ||
1925
+ tok.type === TOKEN.TRUE_KW || tok.type === TOKEN.FALSE_KW ||
1926
+ tok.type === TOKEN.NULL_KW || tok.type === TOKEN.LPAREN ||
1927
+ tok.type === TOKEN.LBRACKET || tok.type === TOKEN.LBRACE ||
1928
+ tok.type === TOKEN.MINUS) return true;
1929
+ if (tok.type === TOKEN.IDENTIFIER) {
1930
+ return [
1931
+ 'list', 'record', 'dictionary', 'map', 'set', 'tuple', 'create',
1932
+ 'count', 'all', 'any', 'settled', 'spread', 'keys', 'values',
1933
+ 'entries', 'size', 'union', 'intersection', 'intersect', 'difference',
1934
+ 'new', 'not',
1935
+ ].includes(tok.value);
1936
+ }
1937
+ return false;
1938
+ }
1939
+
1940
+ // Terminator handling shared by the "X with ..." collection literals.
1941
+ // `openerLine` is the line the "list/record/dictionary/set/tuple" token sits
1942
+ // on; `firstContentLine` the line of the first element token. A trailing
1943
+ // done/together is the collection's OWN terminator only when it is written
1944
+ // on the opener line ("record with a 1 done") or the collection is in block
1945
+ // form (first element on a later line, closed by its own done). Otherwise it
1946
+ // belongs to the enclosing block and must be left alone, so constructs like
1947
+ // if ok
1948
+ // let r be record with name "Ada"
1949
+ // done
1950
+ // stop eating the if-block's terminator.
1951
+ function consumeCollectionTerminator(openerLine, blockForm, hasContent) {
1952
+ if (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) return;
1953
+ if (!hasContent) {
1954
+ if (peek().line === openerLine) advance(); // "list with done" on one line
1955
+ return;
1956
+ }
1957
+ if (blockForm || peek().line === openerLine) advance();
1958
+ }
1959
+
1960
+ // Acceptable record field names beyond plain identifiers: quoted and
1961
+ // numeric keys ({ "first name": ... } style) plus the non-structural
1962
+ // keyword words in RECORD_FIELD_KEYWORDS handled in the loop above.
1963
+ function isRecordFieldName(tok) {
1964
+ return !!tok && (tok.type === TOKEN.IDENTIFIER || tok.type === TOKEN.STRING ||
1965
+ tok.type === TOKEN.NUMBER);
1966
+ }
1967
+
1968
+ // v1.0.363 - SQL words as ordinary identifiers. "query", "insert",
1969
+ // "update" and "execute" keep their SQL-statement meaning only when the
1970
+ // lexer produced a raw SQL body for them (word alone on its line); anywhere
1971
+ // else they are ordinary names, so common spellings like "let query be ..."
1972
+ // or "to search query ... done" work. ("delete" is a JavaScript reserved
1973
+ // word and stays reserved.)
1974
+ function isSqlWordIdentifier(tok) {
1975
+ return !!tok && [
1976
+ [TOKEN.QUERY_KW, 'query'], [TOKEN.INSERT_KW, 'insert'],
1977
+ [TOKEN.UPDATE_KW, 'update'], [TOKEN.EXECUTE_KW, 'execute'],
1978
+ ].some(([type, word]) => tok.type === type && tok.value === word);
1979
+ }
1980
+
1473
1981
  function parseDictionaryWith() {
1982
+ const openerLine = peek().line;
1474
1983
  advance(); // dictionary or map
1475
1984
  consume(TOKEN.WITH, 'Expected "with" after dictionary/map.');
1985
+ // v1.0.363 - newline-separated pairs in block form (one "key is value"
1986
+ // per line, closed by its own done/end); see consumeCollectionTerminator.
1987
+ const blockForm = peek().line > openerLine;
1476
1988
  const pairs = [];
1477
- if (peek().type !== TOKEN.DONE && peek().value !== 'done') {
1478
- while (true) {
1479
- if (peek().type === TOKEN.DONE || peek().value === 'done') break;
1989
+ if (blockForm) {
1990
+ while (canContinueElement(peek())) {
1480
1991
  // Key parsed below the comparison level so `"a" is 1 and "b" is 2`
1481
1992
  // keeps the `is` as the dictionary separator (parseExpression would
1482
1993
  // fold `"a" is 1` into a comparison).
@@ -1486,6 +1997,17 @@ function parseAsk() {
1486
1997
  // keeps `and` as the pair separator. Comparisons still fold.
1487
1998
  const value = parseBooleanAtom();
1488
1999
  pairs.push({ key, value });
2000
+ while (peek().type === TOKEN.AND || (peek().type === TOKEN.IDENTIFIER && peek().value === 'and') || peek().type === TOKEN.COMMA) {
2001
+ advance();
2002
+ }
2003
+ }
2004
+ } else if (peek().type !== TOKEN.DONE && peek().value !== 'done') {
2005
+ while (true) {
2006
+ if (peek().type === TOKEN.DONE || peek().value === 'done') break;
2007
+ const key = parseNullish();
2008
+ consume(TOKEN.IS, 'Expected "is" between key and value in dictionary/map.');
2009
+ const value = parseBooleanAtom();
2010
+ pairs.push({ key, value });
1489
2011
  if (peek().type === TOKEN.AND || (peek().type === TOKEN.IDENTIFIER && peek().value === 'and') || peek().type === TOKEN.COMMA) {
1490
2012
  advance();
1491
2013
  continue;
@@ -1493,17 +2015,26 @@ function parseAsk() {
1493
2015
  break;
1494
2016
  }
1495
2017
  }
1496
- if (peek().type === TOKEN.DONE || (peek().type === TOKEN.IDENTIFIER && peek().value === 'done')) {
1497
- advance(); // done
1498
- }
2018
+ consumeCollectionTerminator(openerLine, blockForm, pairs.length > 0);
1499
2019
  return { type: 'DictionaryLiteral', pairs };
1500
2020
  }
1501
2021
 
1502
2022
  function parseSetWith() {
2023
+ const openerLine = peek().line;
1503
2024
  advance(); // set
1504
2025
  consume(TOKEN.WITH, 'Expected "with" after "set".');
2026
+ // v1.0.363 - newline-separated elements in block form; see
2027
+ // consumeCollectionTerminator for the terminator rule.
2028
+ const blockForm = peek().line > openerLine;
1505
2029
  const elements = [];
1506
- if (peek().type !== TOKEN.DONE && peek().value !== 'done') {
2030
+ if (blockForm) {
2031
+ while (canContinueElement(peek())) {
2032
+ elements.push(parseBooleanAtom());
2033
+ while (peek().type === TOKEN.COMMA || peek().type === TOKEN.AND || (peek().type === TOKEN.IDENTIFIER && peek().value === 'and')) {
2034
+ advance();
2035
+ }
2036
+ }
2037
+ } else if (peek().type !== TOKEN.DONE && peek().value !== 'done') {
1507
2038
  while (true) {
1508
2039
  if (peek().type === TOKEN.DONE || peek().value === 'done') break;
1509
2040
  elements.push(parseBooleanAtom());
@@ -1514,17 +2045,26 @@ function parseAsk() {
1514
2045
  break;
1515
2046
  }
1516
2047
  }
1517
- if (peek().type === TOKEN.DONE || (peek().type === TOKEN.IDENTIFIER && peek().value === 'done')) {
1518
- advance(); // done
1519
- }
2048
+ consumeCollectionTerminator(openerLine, blockForm, elements.length > 0);
1520
2049
  return { type: 'SetLiteral', elements };
1521
2050
  }
1522
2051
 
1523
2052
  function parseTupleWith() {
2053
+ const openerLine = peek().line;
1524
2054
  advance(); // tuple
1525
2055
  consume(TOKEN.WITH, 'Expected "with" after "tuple".');
2056
+ // v1.0.363 - newline-separated elements in block form; see
2057
+ // consumeCollectionTerminator for the terminator rule.
2058
+ const blockForm = peek().line > openerLine;
1526
2059
  const elements = [];
1527
- if (peek().type !== TOKEN.DONE && peek().value !== 'done') {
2060
+ if (blockForm) {
2061
+ while (canContinueElement(peek())) {
2062
+ elements.push(parseBooleanAtom());
2063
+ while (peek().type === TOKEN.COMMA || peek().type === TOKEN.AND || (peek().type === TOKEN.IDENTIFIER && peek().value === 'and')) {
2064
+ advance();
2065
+ }
2066
+ }
2067
+ } else if (peek().type !== TOKEN.DONE && peek().value !== 'done') {
1528
2068
  while (true) {
1529
2069
  if (peek().type === TOKEN.DONE || peek().value === 'done') break;
1530
2070
  elements.push(parseBooleanAtom());
@@ -1535,9 +2075,7 @@ function parseAsk() {
1535
2075
  break;
1536
2076
  }
1537
2077
  }
1538
- if (peek().type === TOKEN.DONE || (peek().type === TOKEN.IDENTIFIER && peek().value === 'done')) {
1539
- advance(); // done
1540
- }
2078
+ consumeCollectionTerminator(openerLine, blockForm, elements.length > 0);
1541
2079
  return { type: 'TupleLiteral', elements };
1542
2080
  }
1543
2081
 
@@ -1636,8 +2174,12 @@ function parseAsk() {
1636
2174
  const param = { name };
1637
2175
  if (peek().type === TOKEN.AS) {
1638
2176
  advance(); // as
1639
- const dv = parseDefaultValue();
1640
- if (dv) param.defaultValue = dv;
2177
+ if (isTypeNameStart(peek())) {
2178
+ param.typeAnnotation = parseTypeSpec();
2179
+ } else {
2180
+ const dv = parseDefaultValue();
2181
+ if (dv) param.defaultValue = dv;
2182
+ }
1641
2183
  }
1642
2184
  return param;
1643
2185
  }
@@ -2106,7 +2648,7 @@ function parseAsk() {
2106
2648
  (nextToken.type === TOKEN.IDENTIFIER && (nextToken.value === 'nothing' || nextToken.value === 'socket'));
2107
2649
 
2108
2650
  if (!isEventWhen) {
2109
- // v1.0.362 - when <target> "<event>" happens [as <name>] … done binds a
2651
+ // v1.0.363 - when <target> "<event>" happens [as <name>] … done binds a
2110
2652
  // DOM event listener: when button "click" happens => addEventListener.
2111
2653
  // Detection probes the target expression and commits only when a string
2112
2654
  // followed by "happens" is next; otherwise the tokens are replayed and
@@ -2126,8 +2668,10 @@ function parseAsk() {
2126
2668
  const body = parseBody('"when happens" block');
2127
2669
  return { type: 'WhenTargetedStatement', target, event: eventStr, paramName, body };
2128
2670
  }
2129
- } catch (_e) {
2671
+ } catch (e) {
2130
2672
  // Not a targeted "when" - replay and fall through to the condition form.
2673
+ // (Depth-limit sentinels propagate — see parseComparisonCondition.)
2674
+ if (e instanceof ParseDepthError) throw e;
2131
2675
  }
2132
2676
  pos = savedPos;
2133
2677
 
@@ -2136,19 +2680,19 @@ function parseAsk() {
2136
2680
  if (peek().type === TOKEN.THEN) {
2137
2681
  advance(); // consume "then"
2138
2682
  }
2139
- const consequent = [];
2140
- while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
2141
- if (peek().type === TOKEN.EOF) {
2142
- throw new Error(makeError(
2143
- 'Expected keyword "done" to close the "when" block before end of file.',
2144
- peek()
2145
- ));
2146
- }
2147
- const stmt = parseStatement();
2148
- if (stmt) consequent.push(stmt);
2683
+ const consequent = [];
2684
+ while (!atBlockEnd()) {
2685
+ if (peek().type === TOKEN.EOF) {
2686
+ throw new Error(makeError(
2687
+ 'Expected keyword "done" to close the "when" block before end of file.',
2688
+ peek()
2689
+ ));
2149
2690
  }
2150
- advance(); // consume DONE or TOGETHER
2151
- return { type: 'IfStatement', condition, consequent, alternate: null };
2691
+ const stmt = parseStatement();
2692
+ if (stmt) consequent.push(stmt);
2693
+ }
2694
+ advance(); // consume DONE or TOGETHER
2695
+ return { type: 'IfStatement', condition, consequent, alternate: null };
2152
2696
  }
2153
2697
 
2154
2698
  // v2.1.1 - "when nothing matches … done" registers the 404 catch-all.
@@ -2586,7 +3130,7 @@ function parseAsk() {
2586
3130
  advance(); // try
2587
3131
  const tryBody = [];
2588
3132
  // Parse try body - stop at "done", "recover", "finally", or "handled by"
2589
- while (!(peek().type === TOKEN.DONE ||
3133
+ while (!(atBlockEnd() ||
2590
3134
  (peek().type === TOKEN.IDENTIFIER && (peek().value === 'recover' || peek().value === 'finally')) ||
2591
3135
  isHandledBy())) {
2592
3136
  if (peek().type === TOKEN.EOF) {
@@ -2629,7 +3173,7 @@ function parseAsk() {
2629
3173
  }
2630
3174
  }
2631
3175
  const recoverBody = [];
2632
- while (peek().type !== TOKEN.DONE &&
3176
+ while (!atBlockEnd() &&
2633
3177
  !(peek().type === TOKEN.IDENTIFIER && (peek().value === 'recover' || peek().value === 'finally')) &&
2634
3178
  !isHandledBy()) {
2635
3179
  if (peek().type === TOKEN.EOF) {
@@ -2651,7 +3195,7 @@ function parseAsk() {
2651
3195
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'finally') {
2652
3196
  advance(); // finally
2653
3197
  finallyBody = [];
2654
- while (peek().type !== TOKEN.DONE) {
3198
+ while (!atBlockEnd()) {
2655
3199
  if (peek().type === TOKEN.EOF) {
2656
3200
  throw new Error(makeError(
2657
3201
  'Expected keyword "done" to close the "finally" block before end of file.',
@@ -2885,11 +3429,18 @@ function parseAsk() {
2885
3429
  // ── Conditions ─────────────────────────────────────────────────────────────
2886
3430
 
2887
3431
  function parseIf() {
3432
+ if (++stmtDepth > MAX_STMT_DEPTH) {
3433
+ throw new ParseDepthError(makeError(
3434
+ `Blocks are nested more than ${MAX_STMT_DEPTH} levels deep. Split the program into functions or reduce nesting.`,
3435
+ peek()
3436
+ ));
3437
+ }
3438
+ try {
2888
3439
  consume(TOKEN.IF);
2889
3440
  const condition = parseCondition();
2890
3441
 
2891
3442
  const consequent = [];
2892
- while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
3443
+ while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.ELSE && !atBlockEnd()) {
2893
3444
  if (peek().type === TOKEN.EOF) {
2894
3445
  throw new Error(makeError(
2895
3446
  'Expected keyword "done" before end of file to close the "if" block.',
@@ -2901,9 +3452,9 @@ function parseAsk() {
2901
3452
  }
2902
3453
 
2903
3454
  let alternate = null;
2904
- if (peek().type === TOKEN.OTHERWISE) {
2905
- // `otherwise if` is an else-if chain (sharing one `done`) ONLY when `if`
2906
- // sits on the same line as `otherwise`; a newline-separated `if` is a
3455
+ if (peek().type === TOKEN.OTHERWISE || peek().type === TOKEN.ELSE) {
3456
+ // `otherwise if` / `else if` is an else-if chain (sharing one `done`)
3457
+ // ONLY when `if` sits on the same line; a newline-separated `if` is a
2907
3458
  // nested if statement with its own `done`.
2908
3459
  const otherwiseLine = peek().line;
2909
3460
  advance();
@@ -2911,7 +3462,7 @@ function parseAsk() {
2911
3462
  alternate = [parseElseIfChain()];
2912
3463
  } else {
2913
3464
  alternate = [];
2914
- while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
3465
+ while (!atBlockEnd()) {
2915
3466
  if (peek().type === TOKEN.EOF) {
2916
3467
  throw new Error(makeError(
2917
3468
  'Expected keyword "done" before end of file to close the "otherwise" block.',
@@ -2926,6 +3477,9 @@ function parseAsk() {
2926
3477
 
2927
3478
  advance(); // consume DONE or TOGETHER
2928
3479
  return { type: 'IfStatement', condition, consequent, alternate };
3480
+ } finally {
3481
+ stmtDepth--;
3482
+ }
2929
3483
  }
2930
3484
 
2931
3485
  // `otherwise if <condition> ... [otherwise if ...] [otherwise ...] done`
@@ -2933,11 +3487,18 @@ function parseAsk() {
2933
3487
  // trailing `otherwise` supplies the final else. The trailing `done` belongs to
2934
3488
  // the outermost `if` and is consumed there, not here.
2935
3489
  function parseElseIfChain() {
3490
+ if (++stmtDepth > MAX_STMT_DEPTH) {
3491
+ throw new ParseDepthError(makeError(
3492
+ `Blocks are nested more than ${MAX_STMT_DEPTH} levels deep. Split the program into functions or reduce nesting.`,
3493
+ peek()
3494
+ ));
3495
+ }
3496
+ try {
2936
3497
  advance(); // consume IF
2937
3498
  const condition = parseCondition();
2938
3499
 
2939
3500
  const consequent = [];
2940
- while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
3501
+ while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.ELSE && !atBlockEnd()) {
2941
3502
  if (peek().type === TOKEN.EOF) {
2942
3503
  throw new Error(makeError(
2943
3504
  'Expected keyword "done" before end of file to close the "otherwise if" block.',
@@ -2949,14 +3510,14 @@ function parseAsk() {
2949
3510
  }
2950
3511
 
2951
3512
  let alternate = null;
2952
- if (peek().type === TOKEN.OTHERWISE) {
3513
+ if (peek().type === TOKEN.OTHERWISE || peek().type === TOKEN.ELSE) {
2953
3514
  const otherwiseLine = peek().line;
2954
3515
  advance();
2955
3516
  if (peek().type === TOKEN.IF && peek().line === otherwiseLine) {
2956
3517
  alternate = [parseElseIfChain()];
2957
3518
  } else {
2958
3519
  alternate = [];
2959
- while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
3520
+ while (!atBlockEnd()) {
2960
3521
  if (peek().type === TOKEN.EOF) {
2961
3522
  throw new Error(makeError(
2962
3523
  'Expected keyword "done" before end of file to close the "otherwise" block.',
@@ -2970,13 +3531,33 @@ function parseAsk() {
2970
3531
  }
2971
3532
 
2972
3533
  return { type: 'IfStatement', condition, consequent, alternate };
3534
+ } finally {
3535
+ stmtDepth--;
3536
+ }
2973
3537
  }
2974
3538
 
2975
3539
  // ── Shared helpers ──────────────────────────────────────────────────────────
2976
3540
 
2977
3541
  function parseBody(context) {
3542
+ if (++stmtDepth > MAX_STMT_DEPTH) {
3543
+ throw new ParseDepthError(makeError(
3544
+ `Blocks are nested more than ${MAX_STMT_DEPTH} levels deep. Split the program into functions or reduce nesting.`,
3545
+ peek()
3546
+ ));
3547
+ }
3548
+ try {
3549
+ return parseBodyInner(context);
3550
+ } finally {
3551
+ stmtDepth--;
3552
+ }
3553
+ }
3554
+
3555
+ function parseBodyInner(context) {
2978
3556
  const body = [];
2979
- while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
3557
+ // v1.0.363 - "done of <record>" reads the `done` FIELD (the README todo
3558
+ // example), so a done/together followed by "of" is never a block
3559
+ // terminator; it starts the next statement instead.
3560
+ while (!atBlockEnd()) {
2980
3561
  if (peek().type === TOKEN.EOF) {
2981
3562
  throw new Error(makeError(
2982
3563
  `Expected keyword "done" to close the ${context} before end of file.`,
@@ -3005,13 +3586,88 @@ function parseAsk() {
3005
3586
  const condition = parseCondition();
3006
3587
  if (peek().type === TOKEN.THEN) advance();
3007
3588
  const consequent = parseExpression();
3008
- if (peek().type === TOKEN.OTHERWISE) advance();
3589
+ if (peek().type === TOKEN.OTHERWISE || peek().type === TOKEN.ELSE) advance();
3009
3590
  const alternate = parseExpression();
3010
3591
  return { type: 'ConditionalExpression', condition, consequent, alternate };
3011
3592
  }
3012
3593
  return parseBooleanOrExpression();
3013
3594
  }
3014
3595
 
3596
+ // v1.0.364 - template interpolation is compiled, not spliced. The lexer
3597
+ // delivers backtick content verbatim; the ${...} parts used to be emitted as
3598
+ // raw source text, so PlainScript-only expressions inside them ("message of
3599
+ // e", "x is at least 80", "a contains b") generated invalid or wrong
3600
+ // JavaScript. Split the content here, tokenize each expression with the same
3601
+ // lexer, and parse it with the ordinary expression grammar. A part that fails
3602
+ // to parse falls back to raw text so legacy output is unchanged.
3603
+ function parseTemplateLiteral(token) {
3604
+ const content = token.value;
3605
+ if (!content.includes('${')) return { type: 'TemplateLiteral', value: content };
3606
+ const parts = [];
3607
+ let plain = '';
3608
+ let i = 0;
3609
+ while (i < content.length) {
3610
+ if (content[i] === '\\' && content[i + 1] === '$' && content[i + 2] === '{') {
3611
+ plain += '\\${'; // keep the backslash: JS renders \${ as literal "${"
3612
+ i += 3;
3613
+ continue;
3614
+ }
3615
+ if (content[i] === '$' && content[i + 1] === '{') {
3616
+ // Find the matching close brace, honouring nested braces and strings.
3617
+ let depth = 1;
3618
+ let j = i + 2;
3619
+ let exprText = '';
3620
+ while (j < content.length && depth > 0) {
3621
+ const ch = content[j];
3622
+ if (ch === '{') depth++;
3623
+ else if (ch === '}') {
3624
+ depth--;
3625
+ if (depth === 0) break;
3626
+ } else if (ch === '"' || ch === "'" || ch === '`') {
3627
+ const quote = ch;
3628
+ exprText += ch;
3629
+ j++;
3630
+ while (j < content.length) {
3631
+ if (content[j] === '\\') { exprText += content[j] + (content[j + 1] || ''); j += 2; continue; }
3632
+ exprText += content[j];
3633
+ if (content[j] === quote) { j++; break; }
3634
+ j++;
3635
+ }
3636
+ continue;
3637
+ }
3638
+ exprText += ch;
3639
+ j++;
3640
+ }
3641
+ if (depth !== 0) {
3642
+ throw new Error(makeError('Unterminated "${" in template string: the closing "}" is missing.', token));
3643
+ }
3644
+ if (plain) { parts.push({ kind: 'text', text: plain }); plain = ''; }
3645
+ let parsed = null;
3646
+ try {
3647
+ const inner = tokenize('show ' + exprText);
3648
+ const sub = parse(inner);
3649
+ if (sub.body.length === 1 && sub.body[0].type === 'ShowStatement') {
3650
+ parsed = sub.body[0].value;
3651
+ }
3652
+ } catch (e) {
3653
+ if (/must contain one expression/.test(e.message) || e instanceof ParseDepthError) throw e;
3654
+ parsed = null; // not valid PlainScript: keep legacy raw-text behaviour
3655
+ }
3656
+ if (parsed) parts.push({ kind: 'expr', expr: parsed, raw: exprText });
3657
+ else parts.push({ kind: 'raw', text: '${' + exprText + '}' });
3658
+ i = j + 1;
3659
+ continue;
3660
+ }
3661
+ plain += content[i];
3662
+ i++;
3663
+ }
3664
+ if (plain) parts.push({ kind: 'text', text: plain });
3665
+ if (parts.every(p => p.kind === 'text')) {
3666
+ return { type: 'TemplateLiteral', value: parts.map(p => p.text).join('') };
3667
+ }
3668
+ return { type: 'TemplateLiteral', value: content, parts };
3669
+ }
3670
+
3015
3671
  // Expression-level boolean algebra: boolean operators usable in ordinary
3016
3672
  // value positions (e.g. `(x is above 3) and (x is below 10)` as a value).
3017
3673
  // Produces the SAME LogicalCondition nodes the condition level builds, so no
@@ -3219,7 +3875,7 @@ function parseAsk() {
3219
3875
  }
3220
3876
 
3221
3877
  // primary → itemExpr | atom (postfix)*
3222
- function parsePrimary() {
3878
+ function parsePrimaryInner() {
3223
3879
  // Arrow function: (params) -> body - detected before grouped expression
3224
3880
  if (peek().type === TOKEN.LPAREN && isArrowFunctionPattern()) {
3225
3881
  return parseArrowFunction();
@@ -3325,7 +3981,7 @@ function parseAsk() {
3325
3981
 
3326
3982
  const item = tryParseItemExpression();
3327
3983
  if (item) return item;
3328
- // v1.0.362 - `new` works anywhere an expression is parsed (assignment
3984
+ // v1.0.363 - `new` works anywhere an expression is parsed (assignment
3329
3985
  // targets, call arguments, member chains). "new" is not a keyword, so this
3330
3986
  // identifier must be intercepted here; parseAtom would read it as a plain
3331
3987
  // Identifier and turn "new THREE.Scene()" into "new.THREE.Scene()".
@@ -3409,8 +4065,14 @@ function parseAsk() {
3409
4065
  } else if (peek().type === TOKEN.AT && peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'position') {
3410
4066
  advance(); // at
3411
4067
  advance(); // position
3412
- const idx = consume(TOKEN.NUMBER, 'Expected a number after "at position".').value;
3413
- node = { type: 'IndexExpression', object: node, index: { type: 'NumberLiteral', value: idx } };
4068
+ // Accept a literal number (the common form) or any expression, so
4069
+ // loop indices and computed indexes work: xs at position i, y at
4070
+ // position (count of xs - 1). parseExpression stops at "to"/")"/","
4071
+ // so "set data at position 0 to 99" keeps its meaning.
4072
+ const index = peek().type === TOKEN.NUMBER
4073
+ ? { type: 'NumberLiteral', value: advance().value }
4074
+ : parseExpression();
4075
+ node = { type: 'IndexExpression', object: node, index };
3414
4076
  } else if (peek().type === TOKEN.LPAREN) {
3415
4077
  // Postfix call: invoke any expression - f()(), arr[0](1), mul(6)(7),
3416
4078
  // obj.method()(x), or an immediately-invoked lambda ((x) -> x + 1)(2).
@@ -3492,10 +4154,18 @@ function parseAsk() {
3492
4154
  return { type: 'NumberedItem', index, collection };
3493
4155
  }
3494
4156
 
3495
- throw new Error(makeError(
3496
- `Expected a number word after "${first.value}" before "from".\n\nUse number words like "one", "two", "three".\n\nExample:\n ${first.value} one from players`,
3497
- second
3498
- ));
4157
+ // v1.0.363 - never throw here for the "X Y of ..." shape: that is the
4158
+ // ordinary property form ("completed of todo"), so the fall-through parses
4159
+ // it normally. Only a plain "X Y from ..." keeps the number-word hint,
4160
+ // since "from" cannot start a property access.
4161
+ if (third.value === 'from') {
4162
+ throw new Error(makeError(
4163
+ `Expected a number word after "${first.value}" before "from".\n\nUse number words like "one", "two", "three".\n\nExample:\n ${first.value} one from players`,
4164
+ second
4165
+ ));
4166
+ }
4167
+
4168
+ return null;
3499
4169
  }
3500
4170
 
3501
4171
  // atom → STRING | NUMBER | true | false | null | undefined | BigInt | '(' expr ')' |
@@ -3504,7 +4174,10 @@ function parseAsk() {
3504
4174
  const token = peek();
3505
4175
 
3506
4176
  if (token.type === TOKEN.STRING) { advance(); return { type: 'StringLiteral', value: token.value }; }
3507
- if (token.type === TOKEN.TEMPLATE_STRING) { advance(); return { type: 'TemplateLiteral', value: token.value }; }
4177
+ if (token.type === TOKEN.TEMPLATE_STRING) {
4178
+ advance();
4179
+ return parseTemplateLiteral(token);
4180
+ }
3508
4181
  if (token.type === TOKEN.NUMBER) { advance(); return { type: 'NumberLiteral', value: token.value }; }
3509
4182
  if (token.type === TOKEN.BIGINT) { advance(); return { type: 'BigIntLiteral', value: token.value }; }
3510
4183
  // v2.1.1 - boolean and null literals
@@ -3559,7 +4232,17 @@ function parseAsk() {
3559
4232
 
3560
4233
  // Keywords that can also be used as identifiers in expression context
3561
4234
  const IDENTIFIER_KEYWORDS = new Set([TOKEN.BACK, TOKEN.REPLY, TOKEN.RESPOND, TOKEN.SEND_BACK, TOKEN.FILE_KW]);
3562
- if (token.type === TOKEN.IDENTIFIER || IDENTIFIER_KEYWORDS.has(token.type)) {
4235
+ // v1.0.363 - `done` can be a record field NAME ("record with text "milk"
4236
+ // and done true", the README todo example), so it must also be readable:
4237
+ // `done of item`, `done of item becomes true`. Accept it as a word only in
4238
+ // the `done of <expr>` shape; a bare `done` elsewhere stays the block
4239
+ // terminator so empty bodies and missing values still fail clearly.
4240
+ if ((token.type === TOKEN.DONE || token.type === TOKEN.TOGETHER) &&
4241
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'of') {
4242
+ advance();
4243
+ return { type: 'Identifier', name: token.value };
4244
+ }
4245
+ if (token.type === TOKEN.IDENTIFIER || IDENTIFIER_KEYWORDS.has(token.type) || isSqlWordIdentifier(token)) {
3563
4246
  if (peekAt(1).type === TOKEN.USES || peekAt(1).type === TOKEN.FILLS) {
3564
4247
  const callee = { type: 'Identifier', name: token.value };
3565
4248
  advance();
@@ -3642,7 +4325,7 @@ function parseAsk() {
3642
4325
  urlToken
3643
4326
  ));
3644
4327
  }
3645
- const url = parsePrimary();
4328
+ const url = parseExpression();
3646
4329
  let body = null;
3647
4330
  let headers = null;
3648
4331
  let timeout = null;
@@ -3708,8 +4391,16 @@ function parseAsk() {
3708
4391
  continue;
3709
4392
  }
3710
4393
  const keyToken = peek();
3711
- // Allow keywords that are valid JS identifiers as property names (e.g., "back" from "give back")
3712
- if (keyToken.type !== TOKEN.IDENTIFIER && keyToken.type !== TOKEN.STRING && keyToken.type !== TOKEN.BACK) {
4394
+ // Allow keywords that are valid JS identifiers as property names (e.g., "back" from "give back",
4395
+ // "done" from the block terminator), plus strings ("with space": 1) and numbers
4396
+ // ({ 3: "three" }) for data-shaped objects. A keyword is only accepted as a key when an
4397
+ // 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 ||
4399
+ keyToken.type === TOKEN.NUMBER || keyToken.type === TOKEN.BACK;
4400
+ const keyIsColonKeyword = keyToken.type !== TOKEN.IDENTIFIER &&
4401
+ typeof keyToken.value === 'string' && /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(keyToken.value) &&
4402
+ peekAt(1).type === TOKEN.COLON;
4403
+ if (!keyIsWord && !keyIsColonKeyword) {
3713
4404
  throw new Error(makeError(
3714
4405
  'Expected a property name inside the inline object.\n\nExample:\n { text: "hi" }',
3715
4406
  keyToken
@@ -3781,7 +4472,7 @@ function parseAsk() {
3781
4472
  keyToken.type === TOKEN.OR || keyToken.type === TOKEN.NOT ||
3782
4473
  keyToken.type === TOKEN.IN || keyToken.type === TOKEN.WITH ||
3783
4474
  keyToken.type === TOKEN.AS || keyToken.type === TOKEN.IF ||
3784
- keyToken.type === TOKEN.OTHERWISE) {
4475
+ keyToken.type === TOKEN.OTHERWISE || keyToken.type === TOKEN.ELSE) {
3785
4476
  advance();
3786
4477
  } else {
3787
4478
  throw new Error(makeError('Expected a property name.', keyToken));
@@ -3816,7 +4507,7 @@ function parseAsk() {
3816
4507
  return { type: 'EveryStatement', count, unit, body };
3817
4508
  }
3818
4509
 
3819
- // v1.0.362 - every frame … done: a requestAnimationFrame loop whose body runs
4510
+ // v1.0.363 - every frame … done: a requestAnimationFrame loop whose body runs
3820
4511
  // once per animation frame. The next frame is scheduled after the body so it
3821
4512
  // always runs (t is the frame timestamp, like the DOM's rAF callback).
3822
4513
  function parseEveryFrame() {
@@ -3826,7 +4517,7 @@ function parseAsk() {
3826
4517
  return { type: 'EveryFrameStatement', body };
3827
4518
  }
3828
4519
 
3829
- // v1.0.362 - after <n> <unit>s … done: run work once after a delay.
4520
+ // v1.0.363 - after <n> <unit>s … done: run work once after a delay.
3830
4521
  // after 5 seconds
3831
4522
  // show "butter!" ... done
3832
4523
  // The delay is a number expression ("after count seconds"); the unit is
@@ -3873,7 +4564,7 @@ function parseAsk() {
3873
4564
  let messageBody = null;
3874
4565
  let disconnectBody = null;
3875
4566
 
3876
- while (peek().type !== TOKEN.DONE) {
4567
+ while (!atBlockEnd()) {
3877
4568
  if (peek().type === TOKEN.EOF) {
3878
4569
  throw new Error(makeError(
3879
4570
  'Expected keyword "done" to close the websocket block before end of file.',
@@ -3925,7 +4616,7 @@ function parseAsk() {
3925
4616
  let baileysModule = null;
3926
4617
  const handlers = [];
3927
4618
 
3928
- while (peek().type !== TOKEN.DONE) {
4619
+ while (!atBlockEnd()) {
3929
4620
  if (peek().type === TOKEN.EOF) {
3930
4621
  throw new Error(makeError(
3931
4622
  'Expected keyword "done" to close the "whatsapp bot" block before end of file.',
@@ -4151,12 +4842,12 @@ function parseAsk() {
4151
4842
  ));
4152
4843
  }
4153
4844
  // otherwise → body
4154
- if (peek().type === TOKEN.OTHERWISE) {
4155
- advance(); // otherwise
4845
+ if (peek().type === TOKEN.OTHERWISE || peek().type === TOKEN.ELSE) {
4846
+ advance(); // otherwise/else
4156
4847
  consume(TOKEN.ARROW,
4157
4848
  'Expected "->" after "otherwise".\n\nExample:\n otherwise → show "other"');
4158
4849
  defaultCase = [];
4159
- while (peek().type !== TOKEN.DONE) {
4850
+ while (!atBlockEnd()) {
4160
4851
  if (peek().type === TOKEN.EOF) {
4161
4852
  throw new Error(makeError(
4162
4853
  'Expected keyword "done" to close the "match" block before end of file.',
@@ -4172,7 +4863,8 @@ function parseAsk() {
4172
4863
  consume(TOKEN.ARROW,
4173
4864
  'Expected "->" after the case expression.\n\nExample:\n "red" → show "stop"');
4174
4865
  const caseBody = [];
4175
- while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.OTHERWISE &&
4866
+ while (!atBlockEnd() && peek().type !== TOKEN.OTHERWISE &&
4867
+ peek().type !== TOKEN.ELSE &&
4176
4868
  !(peek().type === TOKEN.STRING || peek().type === TOKEN.NUMBER ||
4177
4869
  peek().type === TOKEN.TRUE_KW || peek().type === TOKEN.FALSE_KW ||
4178
4870
  peek().type === TOKEN.NULL_KW)) {
@@ -4322,11 +5014,11 @@ function parseAsk() {
4322
5014
  ));
4323
5015
  }
4324
5016
  // otherwise → body
4325
- if (peek().type === TOKEN.OTHERWISE) {
4326
- advance(); // otherwise
5017
+ if (peek().type === TOKEN.OTHERWISE || peek().type === TOKEN.ELSE) {
5018
+ advance(); // otherwise/else
4327
5019
  consume(TOKEN.ARROW, 'Expected "->" after "otherwise".\n\nExample:\n otherwise → show "other"');
4328
5020
  defaultCase = [];
4329
- while (peek().type !== TOKEN.DONE) {
5021
+ while (!atBlockEnd()) {
4330
5022
  if (peek().type === TOKEN.EOF) {
4331
5023
  throw new Error(makeError(
4332
5024
  'Expected keyword "done" to close the "switch" block before end of file.',
@@ -4341,7 +5033,8 @@ function parseAsk() {
4341
5033
  const test = parseExpression();
4342
5034
  consume(TOKEN.ARROW, 'Expected "->" after the case expression.\n\nExample:\n "red" → show "stop"');
4343
5035
  const caseBody = [];
4344
- while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.OTHERWISE &&
5036
+ while (!atBlockEnd() && peek().type !== TOKEN.OTHERWISE &&
5037
+ peek().type !== TOKEN.ELSE &&
4345
5038
  !(peek().type === TOKEN.STRING || peek().type === TOKEN.NUMBER ||
4346
5039
  peek().type === TOKEN.TRUE_KW || peek().type === TOKEN.FALSE_KW ||
4347
5040
  peek().type === TOKEN.NULL_KW)) {
@@ -4435,12 +5128,26 @@ function parseAsk() {
4435
5128
 
4436
5129
  // ── Program ────────────────────────────────────────────────────────────────
4437
5130
 
4438
- const body = [];
4439
- while (peek().type !== TOKEN.EOF) {
4440
- const stmt = parseStatement();
4441
- if (stmt) body.push(stmt);
5131
+ // v1.0.364 - last-resort backstop: any stack overflow that escapes the
5132
+ // recursive descent (the depth guards fire first, but unguarded paths like
5133
+ // class-in-class nesting must never leak a raw RangeError either) becomes
5134
+ // a clean PlainScript error. By the time this catch runs the stack has
5135
+ // unwound, so building the replacement error is safe.
5136
+ try {
5137
+ const body = [];
5138
+ while (peek().type !== TOKEN.EOF) {
5139
+ const stmt = parseStatement();
5140
+ if (stmt) body.push(stmt);
5141
+ }
5142
+ return { type: 'Program', body };
5143
+ } catch (e) {
5144
+ if (e instanceof RangeError) {
5145
+ throw new Error(
5146
+ 'Program is too deeply nested to compile. Split it into functions or intermediate variables.'
5147
+ );
5148
+ }
5149
+ throw e;
4442
5150
  }
4443
- return { type: 'Program', body };
4444
5151
  }
4445
5152
 
4446
5153
  module.exports = { parse };