plainscript-lang 1.0.0 → 1.0.2-latest

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 (106) hide show
  1. package/README.md +194 -729
  2. package/compiler/bundler.js +2 -2
  3. package/compiler/cli.js +182 -79
  4. package/compiler/dependency-detector.js +5 -0
  5. package/compiler/formatter.js +1 -1
  6. package/compiler/generator.js +1083 -206
  7. package/compiler/lexer.js +130 -54
  8. package/compiler/parser.js +1117 -156
  9. package/compiler/version.js +1 -1
  10. package/docs/CAPABILITY_GAP_AUDIT.md +98 -435
  11. package/docs/PLAINSCRIPT-SPEC.md +335 -0
  12. package/docs/index.html +103 -605
  13. package/docs/website/script.js +59 -943
  14. package/docs/website/style.css +74 -656
  15. package/examples/ai-providers.pln +7 -0
  16. package/examples/arrays.pln +4 -0
  17. package/examples/async-errors.pln +18 -0
  18. package/examples/auth-api.pln +9 -0
  19. package/examples/auth-sessions.pln +32 -0
  20. package/examples/basics.pln +14 -0
  21. package/examples/bots.pln +13 -0
  22. package/examples/cache-and-jobs.pln +7 -0
  23. package/examples/cache-schedule.pln +22 -0
  24. package/examples/collections.pln +15 -0
  25. package/examples/concurrency.pln +18 -0
  26. package/examples/conditions.pln +22 -0
  27. package/examples/database.pln +8 -0
  28. package/examples/day2.pln +7 -0
  29. package/examples/day3.pln +5 -0
  30. package/examples/deployment.pln +6 -0
  31. package/examples/email-send.pln +3 -0
  32. package/examples/error-handling.pln +7 -0
  33. package/examples/expressions.pln +7 -0
  34. package/examples/file-uploads.pln +10 -0
  35. package/examples/files-and-config.pln +6 -0
  36. package/examples/files.pln +12 -0
  37. package/examples/football-backend/{app.ps → app.pln} +22 -21
  38. package/examples/functions.pln +17 -0
  39. package/examples/hello.pln +2 -0
  40. package/examples/http-client.pln +3 -0
  41. package/examples/http.pln +11 -0
  42. package/examples/id-verification/{app.ps → app.pln} +5 -4
  43. package/examples/id-verification/make-sample-id.js +29 -42
  44. package/examples/json.pln +11 -0
  45. package/examples/loops.pln +18 -0
  46. package/examples/modules/app.pln +3 -0
  47. package/examples/modules/main.pln +4 -0
  48. package/examples/modules/math.pln +9 -0
  49. package/examples/mongo.pln +33 -0
  50. package/examples/objects.pln +4 -0
  51. package/examples/ocr.pln +22 -0
  52. package/examples/packages.pln +6 -0
  53. package/examples/record-kinds.pln +7 -0
  54. package/examples/records.pln +15 -0
  55. package/examples/rest-api-fetch.pln +10 -0
  56. package/examples/rest-api.pln +8 -0
  57. package/examples/scheduled-tasks.pln +4 -0
  58. package/examples/search-and-filter.pln +4 -0
  59. package/examples/server.pln +6 -0
  60. package/examples/sessions-and-cookies.pln +8 -0
  61. package/examples/sqlite.pln +23 -0
  62. package/examples/start.pln +2 -0
  63. package/examples/stdlib.pln +4 -0
  64. package/examples/telegram-ai-bot.pln +19 -0
  65. package/examples/telegram-bot.pln +6 -0
  66. package/examples/testing.pln +13 -0
  67. package/examples/web-api.pln +27 -0
  68. package/examples/web-app.pln +8 -0
  69. package/examples/websocket-server.pln +6 -0
  70. package/examples/websocket.pln +13 -0
  71. package/examples/whatsapp-bot/{pairing.ps → pairing.pln} +4 -5
  72. package/examples/whatsapp-bot/qr.pln +12 -0
  73. package/package.json +3 -2
  74. package/docs/PLINJS_SPEC.md +0 -1151
  75. package/examples/arrays.ps +0 -13
  76. package/examples/auth-api.ps +0 -56
  77. package/examples/cache-and-jobs.ps +0 -29
  78. package/examples/concurrency.ps +0 -49
  79. package/examples/database.ps +0 -41
  80. package/examples/day2.ps +0 -7
  81. package/examples/day3.ps +0 -11
  82. package/examples/deployment.ps +0 -12
  83. package/examples/email-send.ps +0 -22
  84. package/examples/error-handling.ps +0 -54
  85. package/examples/expressions.ps +0 -40
  86. package/examples/file-uploads.ps +0 -39
  87. package/examples/files-and-config.ps +0 -47
  88. package/examples/hello.ps +0 -3
  89. package/examples/http-client.ps +0 -44
  90. package/examples/loops.ps +0 -17
  91. package/examples/modules/app.ps +0 -16
  92. package/examples/modules/math.ps +0 -20
  93. package/examples/objects.ps +0 -12
  94. package/examples/record-kinds.ps +0 -43
  95. package/examples/rest-api-fetch.ps +0 -94
  96. package/examples/rest-api.ps +0 -68
  97. package/examples/scheduled-tasks.ps +0 -23
  98. package/examples/search-and-filter.ps +0 -34
  99. package/examples/server.ps +0 -25
  100. package/examples/sessions-and-cookies.ps +0 -54
  101. package/examples/start.ps +0 -2
  102. package/examples/stdlib.ps +0 -41
  103. package/examples/telegram-bot.ps +0 -42
  104. package/examples/web-app.ps +0 -20
  105. package/examples/websocket-server.ps +0 -27
  106. package/examples/whatsapp-bot/qr.ps +0 -8
@@ -9,6 +9,20 @@ const STATEMENT_KEYWORDS = [
9
9
  'web', 'route', 'start', 'database', 'query', 'insert', 'update', 'delete', 'execute',
10
10
  'ask', 'javascript', 'bot', 'ocr', 'try', 'recover', 'retry',
11
11
  'gather', 'filter', 'total', 'match', 'emit', 'stream', 'run',
12
+ 'switch', 'case', 'default', 'break', 'continue', 'return',
13
+ 'throw', 'catch', 'finally', 'new', 'class', 'extends', 'super',
14
+ 'const', 'let', 'var', 'function', 'yield', 'await',
15
+ 'import', 'export', 'default', 'from', 'as',
16
+ 'in', 'of', 'instanceof', 'typeof', 'delete', 'void',
17
+ 'debugger', 'with', 'enum', 'interface', 'type',
18
+ 'async', 'await', 'static', 'get', 'set',
19
+ 'target', 'meta', 'new.target', 'import.meta',
20
+ 'url', 'urlsearchparams', 'blob', 'file', 'formdata',
21
+ 'crypto', 'subtle', 'crypto.randomuuid', 'crypto.getrandomvalues',
22
+ 'intl', 'datetimeformat', 'numberformat', 'collator',
23
+ 'weakmap', 'weakset', 'weakref', 'finalizationregistry',
24
+ 'proxy', 'reflect', 'symbol', 'bigint', 'sharedarraybuffer',
25
+ 'atomics', 'dataview', 'arraybuffer', 'typedarray',
12
26
  ];
13
27
 
14
28
  // Number words used by the numbered item expression (v1.1):
@@ -155,6 +169,76 @@ function parse(tokens) {
155
169
  function parseComparisonCondition() {
156
170
  const left = parseExpression();
157
171
 
172
+ // ── instanceof condition ───────────────────────────────────────────────────
173
+ if (peek().type === TOKEN.INSTANCEOF) {
174
+ advance();
175
+ const right = parseExpression();
176
+ return { type: 'BinaryCondition', left, op: 'instanceof', right };
177
+ }
178
+
179
+ // v2.4 — "has field" → "x" in obj (contextual: "has" followed by "field")
180
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'has' &&
181
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'field') {
182
+ advance(); // has
183
+ advance(); // field
184
+ const right = parseExpression();
185
+ return { type: 'BinaryCondition', left: right, op: 'in', right: left };
186
+ }
187
+ // v2.4 — "starts as" → startsWith (contextual: "starts" followed by "as")
188
+ if (peek().type === TOKEN.STARTS && peekAt(1).type === TOKEN.AS) {
189
+ advance(); // starts
190
+ advance(); // as
191
+ const right = parseExpression();
192
+ return { type: 'StringCondition', left, method: 'startsWith', right };
193
+ }
194
+ // v2.4 — "ends as" → endsWith (contextual: "ends" followed by "as")
195
+ if (peek().type === TOKEN.ENDS && peekAt(1).type === TOKEN.AS) {
196
+ advance(); // ends
197
+ advance(); // as
198
+ const right = parseExpression();
199
+ return { type: 'StringCondition', left, method: 'endsWith', right };
200
+ }
201
+ // v2.4 — "made of" → includes (contextual: "made" followed by "of")
202
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'made' &&
203
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'of') {
204
+ advance(); // made
205
+ advance(); // of
206
+ const right = parseExpression();
207
+ return { type: 'StringCondition', left, method: 'includes', right };
208
+ }
209
+ // v2.4 — "more than" → > (contextual: "more" followed by "than")
210
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'more' &&
211
+ peekAt(1).type === TOKEN.THAN) {
212
+ advance(); // more
213
+ advance(); // than
214
+ const right = parseExpression();
215
+ return { type: 'BinaryCondition', left, op: '>', right };
216
+ }
217
+ // v2.4 — "fewer than" → < (contextual: "fewer" followed by "than")
218
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'fewer' &&
219
+ peekAt(1).type === TOKEN.THAN) {
220
+ advance(); // fewer
221
+ advance(); // than
222
+ const right = parseExpression();
223
+ return { type: 'BinaryCondition', left, op: '<', right };
224
+ }
225
+ // v2.4 — "same as" → === (contextual: "same" followed by "as")
226
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'same' &&
227
+ peekAt(1).type === TOKEN.AS) {
228
+ advance(); // same
229
+ advance(); // as
230
+ const right = parseExpression();
231
+ return { type: 'BinaryCondition', left, op: '===', right };
232
+ }
233
+ // v2.4 — "different from" → !== (contextual: "different" followed by "from")
234
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'different' &&
235
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'from') {
236
+ advance(); // different
237
+ advance(); // from
238
+ const right = parseExpression();
239
+ return { type: 'BinaryCondition', left, op: '!==', right };
240
+ }
241
+
158
242
  // ── Non-"is" operators ──────────────────────────────────────────────────
159
243
  if (peek().type === TOKEN.CONTAINS) {
160
244
  advance();
@@ -264,12 +348,37 @@ function parse(tokens) {
264
348
  function parseStatement() {
265
349
  const token = peek();
266
350
 
351
+ // "define a kind called ..." - must check before DEFINE token dispatch
352
+ if ((token.type === TOKEN.DEFINE || (token.type === TOKEN.IDENTIFIER && token.value === 'define')) &&
353
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'a') {
354
+ return parseDefineKind();
355
+ }
356
+
357
+ // "load env file" - must check before LOAD token dispatch
358
+ if ((token.type === TOKEN.LOAD || (token.type === TOKEN.IDENTIFIER && token.value === 'load')) &&
359
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'env' &&
360
+ (peekAt(2).type === TOKEN.IDENTIFIER || peekAt(2).type === TOKEN.FILE_KW) && peekAt(2).value === 'file') {
361
+ advance(); // load
362
+ advance(); // env
363
+ advance(); // file
364
+ const path = consume(TOKEN.STRING,
365
+ 'Expected an env file path string after "load env file".\n\nExample:\n load env file ".env"');
366
+ return { type: 'LoadEnvFileStatement', path: path.value };
367
+ }
368
+
267
369
  if (token.type === TOKEN.REMEMBER) return parseRemember();
370
+ if (token.type === TOKEN.LET) return parseRemember(); // "let x is 5"
268
371
  if (token.type === TOKEN.SHOW) return parseShow();
372
+ if (token.type === TOKEN.PRINT) return parseShow(); // alias for show
373
+ if (token.type === TOKEN.DISPLAY) return parseShow(); // alias for show
269
374
  if (token.type === TOKEN.IF) return parseIf();
270
375
  if (token.type === TOKEN.MAKE) return parseMake();
376
+ if (token.type === TOKEN.DEFINE) return parseMake(); // alias for make
377
+ if (token.type === TOKEN.FUNCTION) return parseMake(); // alias for make
271
378
  if (token.type === TOKEN.GIVE) return parseGive();
272
- // v1.0.0 — generators: `yield <expr>` is only meaningful inside a function
379
+ if (token.type === TOKEN.RETURN) return parseGive(); // alias for give
380
+ if (token.type === TOKEN.GIVE_BACK) return parseGive(); // alias for give
381
+ // v1.0.1 — generators: `yield <expr>` is only meaningful inside a function
273
382
  // body; the generator marks the enclosing `make ... done` as a function*.
274
383
  if (token.type === TOKEN.YIELD) return parseYield();
275
384
  if (token.type === TOKEN.FOR) return parseForEach();
@@ -283,20 +392,41 @@ function parse(tokens) {
283
392
  if (token.type === TOKEN.WHILE) return parseWhile();
284
393
  if (token.type === TOKEN.USE) return parseUse();
285
394
  if (token.type === TOKEN.IMPORT) return parseImport();
395
+ if (token.type === TOKEN.INCLUDE) return parseImport(); // alias for import
396
+ if (token.type === TOKEN.LOAD) return parseImport(); // alias for import
286
397
  if (token.type === TOKEN.WHEN) return parseWhen();
398
+ // v2.3 — English-like function declaration: "to add a and b together ... done"
399
+ if (token.type === TOKEN.TO && peekAt(1).type === TOKEN.IDENTIFIER) return parseToFunction();
400
+ // v2.4 — "list with" and "record with" as expressions
401
+ if (token.type === TOKEN.IDENTIFIER && token.value === 'list' && peekAt(1).type === TOKEN.WITH) return parseListWith();
402
+ if (token.type === TOKEN.IDENTIFIER && token.value === 'record' && peekAt(1).type === TOKEN.WITH) return parseRecordWith(false);
403
+ if (token.type === TOKEN.LIST_WITH) return parseListWith();
404
+ if (token.type === TOKEN.RECORD_WITH) return parseRecordWith(false);
287
405
  if (token.type === TOKEN.LISTEN) return parseListen();
406
+ if (token.type === TOKEN.START_ON) return parseListen(); // "start on port 3000"
407
+ if (token.type === TOKEN.SERVE_ON) return parseListen(); // "serve on port 3000"
288
408
  if (token.type === TOKEN.REPLY) return parseReply();
409
+ if (token.type === TOKEN.RESPOND) return parseReply(); // alias for reply
410
+ if (token.type === TOKEN.SEND_BACK) return parseReply(); // alias for reply
289
411
  if (token.type === TOKEN.SERVE) return parseServeFolder();
290
- // v1.1.1 — JavaScript Gateway
412
+ if (token.type === TOKEN.SERVE_STATIC) return parseServeFolder(); // alias
413
+ if (token.type === TOKEN.SERVE_PUBLIC) return parseServeFolder(); // alias
291
414
  if (token.type === TOKEN.ASK) return parseAsk();
292
- if (token.type === TOKEN.JAVASCRIPT_KW) return parseJavaScriptBlock();
415
+ if (token.type === TOKEN.PROMPT) return parseAsk(); // alias for ask
416
+ if (token.type === TOKEN.DEBUGGER_KW) {
417
+ advance();
418
+ return { type: 'DebuggerStatement' };
419
+ }
293
420
  // v2.0.1 — OCR capability
294
421
  if (token.type === TOKEN.OCR_KW) return parseOcr();
295
422
  // v0.6
296
423
  if (token.type === TOKEN.WEB) return parseWebApp();
297
424
  if (token.type === TOKEN.ROUTE_KW) return parseSimpleRoute();
298
425
  if (token.type === TOKEN.START_KW) return parseStart();
426
+ if (token.type === TOKEN.RUN_ON) return parseStart(); // alias for start
299
427
  if (token.type === TOKEN.DATABASE_KW) return parseDatabase();
428
+ if (token.type === TOKEN.CONNECT_DB) return parseDatabase(); // alias
429
+ if (token.type === TOKEN.USE_DATABASE) return parseDatabase(); // alias
300
430
  // v2.1.0 — query("field"): the HTTP query-string accessor. The SQLite
301
431
  // block form keeps priority when "query" stands alone on a line; a
302
432
  // call form is always the accessor.
@@ -324,8 +454,38 @@ function parse(tokens) {
324
454
 
325
455
  if (token.type === TOKEN.EOF) return null;
326
456
 
457
+ if (token.type === TOKEN.RAISES) {
458
+ advance();
459
+ const value = parseExpression();
460
+ return { type: 'ThrowStatement', value };
461
+ }
462
+
327
463
  // Statements starting with an identifier: call, becomes, index/member becomes
328
464
  if (token.type === TOKEN.IDENTIFIER) {
465
+ // switch ... against ... done
466
+ if (token.value === 'switch' && (peekAt(1).type === TOKEN.IDENTIFIER || tokenStartsValue(peekAt(1)))) {
467
+ return parseSwitchStatement();
468
+ }
469
+
470
+ // class declaration: class Name { ... }
471
+ if (token.value === 'class') {
472
+ return parseClassDeclaration();
473
+ }
474
+
475
+ // return statement
476
+ if (token.value === 'return' && peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
477
+ advance();
478
+ const value = peek().type !== TOKEN.DONE && peek().type !== TOKEN.EOF && peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.RBRACE
479
+ ? parseExpression()
480
+ : null;
481
+ return { type: 'ReturnStatement', value };
482
+ }
483
+
484
+ // new expression: new ClassName(args)
485
+ if (token.value === 'new' && peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
486
+ return { type: 'ExpressionStatement', expression: parseNewExpression() };
487
+ }
488
+
329
489
  // v1.2 — bot "<token>" / bot <expr>: creates the polling Telegram bot.
330
490
  // Bound to BOT by the generator's `bot` stdlib. Only intercepts when a
331
491
  // value follows; bot(...) calls and ordinary identifiers (e.g. a
@@ -365,6 +525,15 @@ function parse(tokens) {
365
525
  return parsePostgres();
366
526
  }
367
527
 
528
+ // v2.2.0 — mongo "<connection-string>" [db "<name>"]: binds the MongoDB client.
529
+ // Contextual: a variable named "mongo" or "mongodb" keeps its meaning unless
530
+ // a connection string follows on the same line.
531
+ if ((token.value === 'mongo' || token.value === 'mongodb') && (
532
+ peekAt(1).type === TOKEN.STRING || peekAt(1).type === TOKEN.IDENTIFIER ||
533
+ peekAt(1).type === TOKEN.LPAREN || peekAt(1).type === TOKEN.TEMPLATE_STRING)) {
534
+ return parseMongo();
535
+ }
536
+
368
537
  // v2.1.0 — cache "<redis-url>" / cache env("REDIS_URL"): connects the
369
538
  // shared Redis client used by cacheGet / cacheSet / cacheDelete.
370
539
  // Contextual like "postgres": a variable named "cache" keeps its
@@ -494,7 +663,7 @@ function parse(tokens) {
494
663
 
495
664
  // v2.2.0 — redirect to "<url>": sends an HTTP redirect from a route
496
665
  // handler. "redirect(...)" calls and "redirect becomes x" stay ordinary.
497
- if (token.value === 'redirect' && peekAt(1).value === 'to') {
666
+ if (token.value === 'redirect' && (peekAt(1).value === 'to' || peekAt(1).type === TOKEN.TO)) {
498
667
  advance(); // redirect
499
668
  advance(); // to
500
669
  const url = parseExpression();
@@ -578,18 +747,18 @@ function parse(tokens) {
578
747
  return { type: 'GoogleOAuthStatement', options: parsePropertyList('"google oauth" block') };
579
748
  }
580
749
 
581
- // ── v1.0.0 — capability-gap features (all contextual, IOPL-native) ──
750
+ // ── v1.0.1 — capability-gap features (all contextual, IOPL-native) ──
582
751
 
583
752
  // define a kind called "Person" with … done → record schema (classes)
584
- if (token.value === 'define' &&
753
+ if ((token.type === TOKEN.DEFINE || (token.type === TOKEN.IDENTIFIER && token.value === 'define')) &&
585
754
  peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'a') {
586
755
  return parseDefineKind();
587
756
  }
588
757
 
589
758
  // load env file "<path>" → apply .env KEY=VALUE pairs to process.env
590
- if (token.value === 'load' &&
759
+ if ((token.type === TOKEN.LOAD || (token.type === TOKEN.IDENTIFIER && token.value === 'load')) &&
591
760
  peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'env' &&
592
- peekAt(2).type === TOKEN.IDENTIFIER && peekAt(2).value === 'file') {
761
+ (peekAt(2).type === TOKEN.IDENTIFIER || peekAt(2).type === TOKEN.FILE_KW) && peekAt(2).value === 'file') {
593
762
  advance(); // load
594
763
  advance(); // env
595
764
  advance(); // file
@@ -617,12 +786,70 @@ function parse(tokens) {
617
786
  return { type: 'ExportStatement', name };
618
787
  }
619
788
 
789
+ // throw <value> → raise an error for the caller's try/recover to catch.
790
+ // "throw(...)" calls and "throw becomes x" keep their ordinary meaning.
791
+ if (token.value === 'throw' &&
792
+ peekAt(1).type !== TOKEN.LPAREN && peekAt(1).type !== TOKEN.BECOMES) {
793
+ advance(); // throw
794
+ const value = parseExpression();
795
+ return { type: 'ThrowStatement', value };
796
+ }
797
+
798
+ // break / continue → loop control flow. Contextual keywords: a variable
799
+ // literally named break/continue is rejected by the teaching guard in
800
+ // generateStatement when not inside a loop.
801
+ if (token.value === 'break' &&
802
+ peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
803
+ advance(); // break
804
+ return { type: 'BreakStatement' };
805
+ }
806
+ if (token.value === 'continue' &&
807
+ peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
808
+ advance(); // continue
809
+ return { type: 'ContinueStatement' };
810
+ }
811
+
812
+ // debugger statement
813
+ if (token.value === 'debugger' &&
814
+ peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
815
+ advance(); // debugger
816
+ return { type: 'DebuggerStatement' };
817
+ }
818
+
620
819
  const expr = parsePrimary();
621
820
 
622
- if (peek().type === TOKEN.BECOMES) {
623
- advance();
821
+ // Assignment operators: becomes, is now, set to, change to, or becomes (||=), and becomes (&&=), nullish becomes (??=)
822
+ let becomeOp = null;
823
+ if (peek().type === TOKEN.OR && peekAt(1).type === TOKEN.BECOMES) {
824
+ advance(); // or
825
+ advance(); // becomes
826
+ becomeOp = '||=';
827
+ } else if (peek().type === TOKEN.AND && peekAt(1).type === TOKEN.BECOMES) {
828
+ advance(); // and
829
+ advance(); // becomes
830
+ becomeOp = '&&=';
831
+ } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'nullish' && peekAt(1).type === TOKEN.BECOMES) {
832
+ advance(); // nullish
833
+ advance(); // becomes
834
+ becomeOp = '??=';
835
+ } else if (peek().type === TOKEN.BECOMES) {
836
+ advance(); // becomes
837
+ becomeOp = '=';
838
+ } else if (peek().type === TOKEN.IS && peekAt(1).type === TOKEN.NOW) {
839
+ advance(); // is
840
+ advance(); // now
841
+ becomeOp = '=';
842
+ } else if (peek().type === TOKEN.SET_TO) {
843
+ advance(); // set to
844
+ becomeOp = '=';
845
+ } else if (peek().type === TOKEN.CHANGE_TO) {
846
+ advance(); // change to
847
+ becomeOp = '=';
848
+ }
849
+
850
+ if (becomeOp !== null) {
624
851
  const value = parseExpression();
625
- return { type: 'BecomeStatement', target: expr, value };
852
+ return { type: 'BecomeStatement', target: expr, value, op: becomeOp };
626
853
  }
627
854
 
628
855
  if (expr.type === 'CallExpression' ||
@@ -651,33 +878,55 @@ function parse(tokens) {
651
878
  throw new Error(makeError(`Unexpected keyword "${token.value}".`, token));
652
879
  }
653
880
 
654
- // remember <name> as <value>
881
+ // remember <name> as <value> / let <name> is <value>
655
882
  // remember <name> as\n <key> is <val>\n...\ndone (object literal)
656
- // remember <name> as javascript\n <raw JS>\ndone (v1.1.1 JavaScript block)
883
+ // remember [a, b] as array (array destructuring)
884
+ // remember {x, y} as obj (object destructuring)
657
885
  function parseRemember() {
658
- consume(TOKEN.REMEMBER);
659
- const name = consume(
660
- TOKEN.IDENTIFIER,
661
- 'Expected a variable name after "remember".\n\nExample:\n remember age as 16'
662
- ).value;
886
+ const isLet = peek().type === TOKEN.LET;
887
+ if (isLet) {
888
+ consume(TOKEN.LET);
889
+ } else {
890
+ consume(TOKEN.REMEMBER);
891
+ }
892
+
893
+ // Check for destructuring patterns: [ ... ] or { ... }
894
+ let target;
895
+ if (peek().type === TOKEN.LBRACKET) {
896
+ target = parseArrayLiteral(); // returns ArrayLiteral with elements
897
+ target.type = 'ArrayPattern';
898
+ } else if (peek().type === TOKEN.LBRACE) {
899
+ target = parseInlineObjectLiteral(true); // returns InlineObjectLiteral with properties, destructuring mode
900
+ target.type = 'ObjectPattern';
901
+ } else {
902
+ // Allow certain keywords as variable names (they're keywords in other contexts but valid as identifiers)
903
+ // BACK for "give back", REPLY for "reply" statement, etc.
904
+ const KEYWORDS_AS_IDENTIFIERS = new Set([TOKEN.BACK, TOKEN.REPLY, TOKEN.RESPOND, TOKEN.SEND_BACK, TOKEN.FILE_KW]);
905
+ let nameToken = peek();
906
+ if (KEYWORDS_AS_IDENTIFIERS.has(nameToken.type)) {
907
+ advance();
908
+ target = nameToken.value;
909
+ } else {
910
+ target = consume(
911
+ TOKEN.IDENTIFIER,
912
+ `Expected a variable name after "${isLet ? 'let' : 'remember'}".\n\nExample:\n ${isLet ? 'let age is 16' : 'remember age as 16'}`
913
+ ).value;
914
+ }
915
+ }
916
+
917
+ // "let" uses "is" or "be" for simple vars, but also accepts "as" for both simple and destructuring
918
+ // "remember" always uses "as"
919
+ const isDestructuring = target && typeof target === 'object' && (target.type === 'ArrayPattern' || target.type === 'ObjectPattern');
920
+ const assignToken = isLet ? ((peek().type === TOKEN.IS || peek().type === TOKEN.BE) ? peek().type : TOKEN.AS) : TOKEN.AS;
921
+ const expectedKeyword = (isLet && (peek().type === TOKEN.IS || peek().type === TOKEN.BE)) ? (peek().type === TOKEN.BE ? 'be' : 'is') : 'as';
663
922
  consume(
664
- TOKEN.AS,
665
- 'Expected keyword "as" after the variable name.\n\nExample:\n remember age as 16'
923
+ assignToken,
924
+ `Expected keyword "${expectedKeyword}" after the variable name.\n\nExample:\n ${isLet ? 'let age is 16' : 'remember age as 16'}`
666
925
  );
667
926
 
668
- // JavaScript block: remember <name> as javascript … done
669
- if (peek().type === TOKEN.JAVASCRIPT_KW) {
670
- advance(); // consume javascript
671
- const bodyToken = peek();
672
- if (bodyToken.type !== TOKEN.JS_BODY) {
673
- throw new Error(makeError(
674
- 'Expected a JavaScript block after "javascript".\n\nExample:\n remember result as javascript\n await axios.get(url)\n done',
675
- bodyToken
676
- ));
677
- }
678
- const body = advance().value; // consume JS_BODY
679
- consume(TOKEN.DONE, 'Expected "done" to close the JavaScript block.');
680
- return { type: 'JavaScriptBlock', name, body };
927
+ // Object literal: next token is IDENTIFIER followed by IS or BE
928
+ if (peek().type === TOKEN.IDENTIFIER && (peekAt(1).type === TOKEN.IS || peekAt(1).type === TOKEN.BE)) {
929
+ return { type: 'RememberStatement', name: target, value: parseObjectLiteral() };
681
930
  }
682
931
 
683
932
  // v2.1.0 — remember <name> as query|insert|update|delete … done
@@ -692,22 +941,22 @@ function parse(tokens) {
692
941
  const kind = kindToken.value;
693
942
  const sql = advance().value; // consume SQL_BODY
694
943
  consume(TOKEN.DONE, `Expected "done" to close the "${kind}" block.`);
695
- return { type: 'RememberSqlStatement', name, kind, ...extractSqlParams(sql) };
696
- }
697
-
698
- // Object literal: next token is IDENTIFIER followed by IS
699
- if (peek().type === TOKEN.IDENTIFIER && peekAt(1).type === TOKEN.IS) {
700
- return { type: 'RememberStatement', name, value: parseObjectLiteral() };
944
+ return { type: 'RememberSqlStatement', name: target, kind, ...extractSqlParams(sql) };
701
945
  }
702
946
 
703
947
  const value = parseExpression();
704
- return { type: 'RememberStatement', name, value };
948
+ return { type: 'RememberStatement', name: target, value };
705
949
  }
706
950
 
707
951
  // ask <variable>
708
952
  // ask "<prompt>" as <variable>
709
- function parseAsk() {
710
- consume(TOKEN.ASK);
953
+ function parseAsk() {
954
+ const isPrompt = peek().type === TOKEN.PROMPT;
955
+ if (isPrompt) {
956
+ consume(TOKEN.PROMPT);
957
+ } else {
958
+ consume(TOKEN.ASK);
959
+ }
711
960
  if (peek().type === TOKEN.STRING) {
712
961
  const prompt = advance().value;
713
962
  consume(TOKEN.AS,
@@ -717,26 +966,10 @@ function parse(tokens) {
717
966
  return { type: 'AskStatement', prompt, variable };
718
967
  }
719
968
  const variable = consume(TOKEN.IDENTIFIER,
720
- 'Expected a variable name after "ask".\n\nExample:\n ask name').value;
969
+ 'Expected a variable name after "as".\n\nExample:\n ask "What is your name?" as name').value;
721
970
  return { type: 'AskStatement', variable };
722
971
  }
723
972
 
724
- // javascript\n <raw JS>\ndone — statement-level JavaScript block.
725
- // Mirrors the `remember <name> as javascript` form but produces no value.
726
- function parseJavaScriptBlock() {
727
- consume(TOKEN.JAVASCRIPT_KW);
728
- const bodyToken = peek();
729
- if (bodyToken.type !== TOKEN.JS_BODY) {
730
- throw new Error(makeError(
731
- 'Expected a JavaScript block after "javascript".\n\nExample:\n javascript\n console.log("hi")\n done',
732
- bodyToken
733
- ));
734
- }
735
- const body = advance().value; // consume JS_BODY
736
- consume(TOKEN.DONE, 'Expected "done" to close the JavaScript block.');
737
- return { type: 'JavaScriptBlock', name: null, body };
738
- }
739
-
740
973
  // v2.0.1 — OCR capability.
741
974
  //
742
975
  // ocr "<image>" as <variable>
@@ -765,7 +998,15 @@ function parse(tokens) {
765
998
  }
766
999
 
767
1000
  function parseShow() {
768
- consume(TOKEN.SHOW);
1001
+ const isPrint = peek().type === TOKEN.PRINT;
1002
+ const isDisplay = peek().type === TOKEN.DISPLAY;
1003
+ if (isPrint) {
1004
+ consume(TOKEN.PRINT);
1005
+ } else if (isDisplay) {
1006
+ consume(TOKEN.DISPLAY);
1007
+ } else {
1008
+ consume(TOKEN.SHOW);
1009
+ }
769
1010
  // Support both keyword form (show "text") and call form (show("text")).
770
1011
  // A "(" after "show" only means a call when the matching ")" ends the
771
1012
  // expression; otherwise it is a grouped value like show (2 + 3) * 4.
@@ -797,6 +1038,8 @@ function parse(tokens) {
797
1038
  after.type === TOKEN.PERCENT || after.type === TOKEN.PLUS ||
798
1039
  after.type === TOKEN.MINUS || after.type === TOKEN.LBRACKET ||
799
1040
  after.type === TOKEN.DOT ||
1041
+ after.type === TOKEN.TIMES_WORD || after.type === TOKEN.DIVIDED_BY_WORD ||
1042
+ after.type === TOKEN.PLUS_WORD || after.type === TOKEN.MINUS_WORD ||
800
1043
  (after.type === TOKEN.IDENTIFIER &&
801
1044
  ['of', 'length', 'above', 'below', 'contains', 'matches', 'becomes'].includes(after.value))
802
1045
  );
@@ -806,13 +1049,27 @@ function parse(tokens) {
806
1049
  return false;
807
1050
  }
808
1051
 
809
- // make name(params) ... done
1052
+ // make name(params) ... done / define name(params) ... done / function name(params) ... done
810
1053
  function parseMake() {
811
- consume(TOKEN.MAKE);
812
- const name = consume(
813
- TOKEN.IDENTIFIER,
814
- 'Expected a function name after "make".\n\nExample:\n make greet()\n show "Hello"\n done'
815
- ).value;
1054
+ const isDefine = peek().type === TOKEN.DEFINE;
1055
+ const isFunction = peek().type === TOKEN.FUNCTION;
1056
+ if (isDefine) {
1057
+ consume(TOKEN.DEFINE);
1058
+ } else if (isFunction) {
1059
+ consume(TOKEN.FUNCTION);
1060
+ } else {
1061
+ consume(TOKEN.MAKE);
1062
+ }
1063
+ const keyword = isDefine ? 'define' : isFunction ? 'function' : 'make';
1064
+ // Allow "load" as a function name (it's also a keyword for "load env file")
1065
+ const nameToken = peek();
1066
+ if (nameToken.type !== TOKEN.IDENTIFIER && nameToken.type !== TOKEN.LOAD) {
1067
+ throw new Error(makeError(
1068
+ `Expected a function name after "${keyword}".\n\nExample:\n ${keyword} greet()\n show "Hello"\n done`,
1069
+ nameToken
1070
+ ));
1071
+ }
1072
+ const name = advance().value;
816
1073
  consume(TOKEN.LPAREN, `Expected "(" after function name "${name}".`);
817
1074
  const params = parseParamList();
818
1075
  consume(TOKEN.RPAREN, 'Expected ")" to close the parameter list.');
@@ -820,27 +1077,164 @@ function parse(tokens) {
820
1077
  return { type: 'FunctionDeclaration', name, params, body };
821
1078
  }
822
1079
 
1080
+ // v2.3 — English-like function declaration: "to <name> <a> and <b> together ... done"
1081
+ // Parameters are identifiers joined by "and". Body ends with "together" or "done".
1082
+ function parseToFunction() {
1083
+ consume(TOKEN.TO);
1084
+ const nameToken = peek();
1085
+ if (nameToken.type !== TOKEN.IDENTIFIER) {
1086
+ throw new Error(makeError(
1087
+ 'Expected a function name after "to".\n\nExample:\n to add a and b together\n give a + b\n together',
1088
+ nameToken
1089
+ ));
1090
+ }
1091
+ const name = advance().value;
1092
+ const params = [];
1093
+ // Parameters are identifiers joined by "and"
1094
+ while (peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.DONE) {
1095
+ if (peek().type === TOKEN.AND) {
1096
+ advance(); // skip "and" between parameters
1097
+ continue;
1098
+ }
1099
+ if (peek().type === TOKEN.EOF) {
1100
+ throw new Error(makeError(
1101
+ `Expected "together" or "done" to close function "${name}" before end of file.`,
1102
+ peek()
1103
+ ));
1104
+ }
1105
+ const paramToken = peek();
1106
+ if (paramToken.type !== TOKEN.IDENTIFIER) {
1107
+ throw new Error(makeError(
1108
+ `Expected a parameter name or "together"/"done" in function "${name}".`,
1109
+ paramToken
1110
+ ));
1111
+ }
1112
+ params.push({ name: advance().value });
1113
+ }
1114
+ const body = parseBody(`function "${name}"`);
1115
+ return { type: 'FunctionDeclaration', name, params, body };
1116
+ }
1117
+
1118
+ // v2.3 — English-like array literal: "list with 1, 2, 3"
1119
+ // Parse comma-separated elements for "list with" (shared helper)
1120
+ function parseListWithElements() {
1121
+ const elements = [];
1122
+ if (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.EOF &&
1123
+ peek().type !== TOKEN.FOLDER &&
1124
+ !(peek().type === TOKEN.IDENTIFIER && (peek().value === 'folder' || peek().value === 'done' || peek().value === 'together'))) {
1125
+ elements.push(parseExpression());
1126
+ while (peek().type === TOKEN.COMMA) {
1127
+ advance(); // consume comma
1128
+ elements.push(parseExpression());
1129
+ }
1130
+ }
1131
+ return elements;
1132
+ }
1133
+
1134
+ function parseListWith() {
1135
+ // Accept both "list_with" keyword and contextual "list" + "with"
1136
+ if (peek().type === TOKEN.LIST_WITH) {
1137
+ consume(TOKEN.LIST_WITH);
1138
+ } else {
1139
+ advance(); // "list"
1140
+ consume(TOKEN.WITH, 'Expected "with" after "list".');
1141
+ }
1142
+ const elements = parseListWithElements();
1143
+ return { type: 'ArrayLiteral', elements };
1144
+ }
1145
+
1146
+ // v2.3 — English-like object literal: "record with name 'Alice' and age 30"
1147
+ // consumeTerminator: true when used as expression (done closes record), false when standalone statement
1148
+ function parseRecordWith(consumeTerminator) {
1149
+ // Accept both "record_with" keyword and contextual "record" + "with"
1150
+ if (peek().type === TOKEN.RECORD_WITH) {
1151
+ consume(TOKEN.RECORD_WITH);
1152
+ } else {
1153
+ advance(); // "record"
1154
+ consume(TOKEN.WITH, 'Expected "with" after "record".');
1155
+ }
1156
+ const properties = [];
1157
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.EOF) {
1158
+ const keyToken = peek();
1159
+ if (keyToken.type !== TOKEN.IDENTIFIER) {
1160
+ throw new Error(makeError(
1161
+ 'Expected a property name after "record with".\n\nExample:\n record with name "Alice" and age 30',
1162
+ keyToken
1163
+ ));
1164
+ }
1165
+ advance(); // consume key
1166
+ const key = keyToken.value;
1167
+ if (peek().type === TOKEN.DONE || peek().type === TOKEN.TOGETHER || peek().type === TOKEN.EOF || peek().type === TOKEN.AND) {
1168
+ properties.push({ key, value: { type: 'UndefinedLiteral' } });
1169
+ } else {
1170
+ const value = parseNullish();
1171
+ properties.push({ key, value });
1172
+ }
1173
+ if (peek().type === TOKEN.AND) {
1174
+ advance(); // consume "and"
1175
+ }
1176
+ }
1177
+ if (consumeTerminator && (peek().type === TOKEN.DONE || peek().type === TOKEN.TOGETHER)) {
1178
+ advance(); // consume done/together when used as expression
1179
+ }
1180
+ return { type: 'InlineObjectLiteral', properties };
1181
+ }
1182
+
823
1183
  function parseParamList() {
824
1184
  const params = [];
825
1185
  if (peek().type === TOKEN.RPAREN) return params;
826
- const firstName = consume(TOKEN.IDENTIFIER, 'Expected a parameter name.').value;
827
- const firstParam = { name: firstName };
828
- if (peek().type === TOKEN.AS) {
829
- advance(); // as
830
- const dv = parseDefaultValue();
831
- if (dv) firstParam.defaultValue = dv;
832
- }
833
- params.push(firstParam);
834
- while (peek().type === TOKEN.COMMA) {
835
- advance();
836
- const pName = consume(TOKEN.IDENTIFIER, 'Expected a parameter name after ",".').value;
837
- const param = { name: pName };
1186
+
1187
+ function parseParam() {
1188
+ // Rest parameter: ...args
1189
+ if (peek().type === TOKEN.SPREAD) {
1190
+ advance();
1191
+ const name = consume(TOKEN.IDENTIFIER, 'Expected a parameter name after "...".').value;
1192
+ return { type: 'RestElement', name };
1193
+ }
1194
+ // Destructuring: [a, b] or {x, y}
1195
+ if (peek().type === TOKEN.LBRACKET) {
1196
+ const pattern = parseArrayLiteral();
1197
+ pattern.type = 'ArrayPattern';
1198
+ if (peek().type === TOKEN.AS) {
1199
+ advance();
1200
+ const dv = parseDefaultValue();
1201
+ if (dv) pattern.defaultValue = dv;
1202
+ }
1203
+ return pattern;
1204
+ }
1205
+ if (peek().type === TOKEN.LBRACE) {
1206
+ const pattern = parseInlineObjectLiteral();
1207
+ pattern.type = 'ObjectPattern';
1208
+ if (peek().type === TOKEN.AS) {
1209
+ advance();
1210
+ const dv = parseDefaultValue();
1211
+ if (dv) pattern.defaultValue = dv;
1212
+ }
1213
+ return pattern;
1214
+ }
1215
+ // Regular parameter
1216
+ // Contextual keywords (back/reply/respond/send back/file) are valid
1217
+ // identifier names when used as a parameter, mirroring `remember`.
1218
+ const PARAM_KEYWORDS = new Set([TOKEN.BACK, TOKEN.REPLY, TOKEN.RESPOND, TOKEN.SEND_BACK, TOKEN.FILE_KW]);
1219
+ let name;
1220
+ if (PARAM_KEYWORDS.has(peek().type)) {
1221
+ name = advance().value;
1222
+ } else {
1223
+ name = consume(TOKEN.IDENTIFIER, 'Expected a parameter name.').value;
1224
+ }
1225
+ const param = { name };
838
1226
  if (peek().type === TOKEN.AS) {
839
1227
  advance(); // as
840
1228
  const dv = parseDefaultValue();
841
1229
  if (dv) param.defaultValue = dv;
842
1230
  }
843
- params.push(param);
1231
+ return param;
1232
+ }
1233
+
1234
+ params.push(parseParam());
1235
+ while (peek().type === TOKEN.COMMA) {
1236
+ advance();
1237
+ params.push(parseParam());
844
1238
  }
845
1239
  return params;
846
1240
  }
@@ -871,12 +1265,24 @@ function parse(tokens) {
871
1265
  }
872
1266
 
873
1267
  function parseGive() {
874
- consume(TOKEN.GIVE);
1268
+ const isReturn = peek().type === TOKEN.RETURN;
1269
+ const isGiveBack = peek().type === TOKEN.GIVE_BACK;
1270
+ const isGive = peek().type === TOKEN.GIVE;
1271
+ if (isReturn) {
1272
+ consume(TOKEN.RETURN);
1273
+ } else if (isGiveBack) {
1274
+ consume(TOKEN.GIVE_BACK);
1275
+ } else if (isGive && peekAt(1).type === TOKEN.BACK) {
1276
+ consume(TOKEN.GIVE);
1277
+ consume(TOKEN.BACK);
1278
+ } else {
1279
+ consume(TOKEN.GIVE);
1280
+ }
875
1281
  const value = parseExpression();
876
1282
  return { type: 'GiveStatement', value };
877
1283
  }
878
1284
 
879
- // v1.0.0 — generators: `yield <expr>` (optionally bare `yield`).
1285
+ // v1.0.1 — generators: `yield <expr>` (optionally bare `yield`).
880
1286
  function parseYield() {
881
1287
  consume(TOKEN.YIELD);
882
1288
  let value = null;
@@ -886,7 +1292,7 @@ function parse(tokens) {
886
1292
  return { type: 'YieldStatement', value };
887
1293
  }
888
1294
 
889
- // v1.0.0 — record kinds: `define a kind called "Person" with … done`
1295
+ // v1.0.1 — record kinds: `define a kind called "Person" with … done`
890
1296
  // The field block reuses the property-list grammar (`age is 0`), so each
891
1297
  // field gets a default expression just like an object literal.
892
1298
  function parseDefineKind() {
@@ -918,12 +1324,21 @@ function parse(tokens) {
918
1324
  const t = consume(TOKEN.IDENTIFIER, 'Expected a kind name after "kind called".');
919
1325
  name = t.value;
920
1326
  }
1327
+ let extendsKind = null;
1328
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'extends') {
1329
+ advance();
1330
+ if (peek().type === TOKEN.STRING) {
1331
+ extendsKind = advance().value;
1332
+ } else {
1333
+ extendsKind = consume(TOKEN.IDENTIFIER, 'Expected a kind name after "extends".').value;
1334
+ }
1335
+ }
921
1336
  consume(TOKEN.WITH, 'Expected "with" after the kind name.\n\nExample:\n define a kind called "Person" with\n name is ""\n done');
922
1337
  const fields = parsePropertyList('kind "' + name + '" definition');
923
- return { type: 'DefineKindStatement', name, fields };
1338
+ return { type: 'DefineKindStatement', name, fields, extends: extendsKind };
924
1339
  }
925
1340
 
926
- // v1.0.0 — record constructor (expression): `create a Person with name "Ada" and age 17`
1341
+ // v1.0.1 — record constructor (expression): `create a Person with name "Ada" and age 17`
927
1342
  function parseCreateKind() {
928
1343
  advance(); // create
929
1344
  advance(); // a / an
@@ -943,7 +1358,7 @@ function parse(tokens) {
943
1358
  return { type: 'CreateKindExpression', kind, pairs };
944
1359
  }
945
1360
 
946
- // v1.0.0 — native test DSL: `test "name" … done`
1361
+ // v1.0.1 — native test DSL: `test "name" … done`
947
1362
  function parseTestStatement() {
948
1363
  advance(); // test
949
1364
  const name = consume(TOKEN.STRING, 'Expected a test name string after "test".').value;
@@ -951,7 +1366,7 @@ function parse(tokens) {
951
1366
  return { type: 'TestStatement', name, body };
952
1367
  }
953
1368
 
954
- // v1.0.0 — assertions: `check <a> (equals|is|contains|raises) <b>`
1369
+ // v1.0.1 — assertions: `check <a> (equals|is|contains|raises) <b>`
955
1370
  function parseCheckStatement() {
956
1371
  advance(); // check
957
1372
  const a = parseExpression();
@@ -971,8 +1386,53 @@ function parse(tokens) {
971
1386
  // for every <item> in <collection> ... done (alias — "every" maps to EACH token)
972
1387
  function parseForEach() {
973
1388
  consume(TOKEN.FOR);
1389
+
1390
+ // for index <name> from <start> to <end> [by <step>] ... done
1391
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'index') {
1392
+ advance(); // index
1393
+ const name = consume(
1394
+ TOKEN.IDENTIFIER,
1395
+ 'Expected an index name after "for index".\n\nExample:\n for index i from 0 to 9\n show i\n done'
1396
+ ).value;
1397
+ if (peek().type === TOKEN.IN || (peek().type === TOKEN.IDENTIFIER && peek().value === 'in')) {
1398
+ // for index <name> in <collection> — zero-based index over a list.
1399
+ advance(); // in
1400
+ const collection = parseExpression();
1401
+ const body = parseBody('"for index" loop');
1402
+ return { type: 'ForIndexStatement', name, start: null, end: collection, step: null, over: collection, body };
1403
+ }
1404
+ if (peek().type !== TOKEN.IDENTIFIER || peek().value !== 'from') {
1405
+ throw new Error(makeError(
1406
+ 'Expected "from" or "in" after the "for index" name.\n\nExample:\n for index i from 0 to 9\n for index i in players',
1407
+ peek()
1408
+ ));
1409
+ }
1410
+ advance(); // from
1411
+ const start = parseExpression();
1412
+ if (peek().type === TOKEN.TO || (peek().type === TOKEN.IDENTIFIER && peek().value === 'to')) {
1413
+ advance(); // to
1414
+ } else {
1415
+ throw new Error(makeError(
1416
+ 'Expected "to" between the start and end of a "for index" loop.\n\nExample:\n for index i from 0 to 9',
1417
+ peek()
1418
+ ));
1419
+ }
1420
+ const end = parseExpression();
1421
+ let step = null;
1422
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'by') {
1423
+ advance(); // by
1424
+ step = parseExpression();
1425
+ }
1426
+ const body = parseBody('"for index" loop');
1427
+ return { type: 'ForIndexStatement', name, start, end, step, over: null, body };
1428
+ }
1429
+
974
1430
  consume(TOKEN.EACH,
975
- 'Expected "each" or "every" after "for".\n\nExample:\n for each item in players\n show item\n done');
1431
+ 'Expected "each", "every" or "index" after "for".\n\nExample:\n for each item in players\n show item\n done');
1432
+ // Also accept "every" (TOKEN.EACH with value "every") as an alias for "each"
1433
+ if (peek().type === TOKEN.EACH && peek().value === 'every') {
1434
+ advance(); // consume "every"
1435
+ }
976
1436
  const item = consume(TOKEN.IDENTIFIER, 'Expected an item name after "each" or "every".').value;
977
1437
  consume(TOKEN.IN, `Expected "in" after "${item}".\n\nExample:\n for each item in players`);
978
1438
  const collection = parseExpression();
@@ -988,12 +1448,43 @@ function parse(tokens) {
988
1448
  return { type: 'WhileStatement', condition, body };
989
1449
  }
990
1450
 
991
- // import "./file.ps"
1451
+ // import "./file.pln"
1452
+ // import { name1, name2 } from "./file.pln" (named imports — binds only the
1453
+ // listed symbols; the whole file is still bundled as a dependency)
992
1454
  function parseImport() {
993
1455
  consume(TOKEN.IMPORT);
1456
+
1457
+ // Named-import form: import { a, b } from "./file.pln"
1458
+ if (peek().type === TOKEN.LBRACE) {
1459
+ advance(); // {
1460
+ const names = [];
1461
+ while (true) {
1462
+ names.push(consume(
1463
+ TOKEN.IDENTIFIER,
1464
+ 'Expected an exported name inside the import braces.\n\nExample:\n import { helper } from "./util.pln"'
1465
+ ).value);
1466
+ if (peek().type === TOKEN.COMMA) { advance(); continue; }
1467
+ break;
1468
+ }
1469
+ consume(TOKEN.RBRACE,
1470
+ 'Expected "}" to close the import braces.\n\nExample:\n import { helper } from "./util.pln"');
1471
+ // The "from" is a plain identifier; tolerate its optional presence so
1472
+ // both "import { x } from "./f.pln"" and "import { x } "./f.pln"" read
1473
+ // naturally, but require it for the documented form.
1474
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'from') {
1475
+ advance(); // from
1476
+ }
1477
+ const filePath = consume(
1478
+ TOKEN.STRING,
1479
+ 'Expected a file path string after the import.\n\nExample:\n import { helper } from "./util.pln"'
1480
+ ).value;
1481
+ return { type: 'ImportStatement', path: filePath, names };
1482
+ }
1483
+
1484
+ // Whole-module form: import "./file.pln"
994
1485
  const filePath = consume(
995
1486
  TOKEN.STRING,
996
- 'Expected a file path string after "import".\n\nExample:\n import "./math.ps"'
1487
+ 'Expected a file path string after "import".\n\nExample:\n import "./math.pln"'
997
1488
  ).value;
998
1489
  return { type: 'ImportStatement', path: filePath };
999
1490
  }
@@ -1029,6 +1520,38 @@ function parse(tokens) {
1029
1520
  function parseWhen() {
1030
1521
  consume(TOKEN.WHEN);
1031
1522
 
1523
+ // v2.3 — "when <condition> ... done": English-like if statement.
1524
+ // Detect: when <expr> is ... / when <expr> above ... etc.
1525
+ // Must come after existing "when" event-handler checks.
1526
+ // Check if next token starts a condition (not someone, not "nothing", not socket,
1527
+ // not a string followed by "happens")
1528
+ const nextToken = peek();
1529
+ const isEventWhen =
1530
+ (nextToken.type === TOKEN.STRING && peekAt(1).type === TOKEN.HAPPENS) ||
1531
+ nextToken.type === TOKEN.SOMEONE ||
1532
+ (nextToken.type === TOKEN.IDENTIFIER && (nextToken.value === 'nothing' || nextToken.value === 'socket'));
1533
+
1534
+ if (!isEventWhen) {
1535
+ const condition = parseCondition();
1536
+ // Optional "then" keyword
1537
+ if (peek().type === TOKEN.THEN) {
1538
+ advance(); // consume "then"
1539
+ }
1540
+ const consequent = [];
1541
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1542
+ if (peek().type === TOKEN.EOF) {
1543
+ throw new Error(makeError(
1544
+ 'Expected keyword "done" to close the "when" block before end of file.',
1545
+ peek()
1546
+ ));
1547
+ }
1548
+ const stmt = parseStatement();
1549
+ if (stmt) consequent.push(stmt);
1550
+ }
1551
+ advance(); // consume DONE or TOGETHER
1552
+ return { type: 'IfStatement', condition, consequent, alternate: null };
1553
+ }
1554
+
1032
1555
  // v2.1.1 — "when nothing matches … done" registers the 404 catch-all.
1033
1556
  // It must appear after every route in the source; the generated handler
1034
1557
  // keeps that position.
@@ -1162,20 +1685,37 @@ function parse(tokens) {
1162
1685
  return { type: 'TelegramCallbackStatement', data, body };
1163
1686
  }
1164
1687
 
1165
- // listen on <port> ... done
1688
+ // listen on <port> ... done / start on <port> ... done / serve on <port> ... done
1166
1689
  function parseListen() {
1167
- consume(TOKEN.LISTEN);
1690
+ const isStartOn = peek().type === TOKEN.START_ON;
1691
+ const isServeOn = peek().type === TOKEN.SERVE_ON;
1692
+ if (isStartOn) {
1693
+ consume(TOKEN.START_ON);
1694
+ } else if (isServeOn) {
1695
+ consume(TOKEN.SERVE_ON);
1696
+ } else {
1697
+ consume(TOKEN.LISTEN);
1698
+ }
1168
1699
  consume(TOKEN.ON,
1169
- 'Expected "on" after "listen".\n\nExample:\n listen on 3000\n show "Running"\n done');
1700
+ 'Expected "on" after "listen" / "start on" / "serve on".\n\nExample:\n listen on 3000\n show "Running"\n done');
1170
1701
  const port = parseExpression();
1171
1702
  const body = parseBody('"listen" block');
1172
1703
  return { type: 'ListenStatement', port, body };
1173
1704
  }
1174
1705
 
1175
- // reply <expr>
1176
- // reply json\n <key> is <val>\n...\ndone
1706
+ // reply <expr> / respond <expr> / send back <expr>
1707
+ // reply json\n <key> is <val>\n...\ndone
1708
+ // reply file "<path>"
1177
1709
  function parseReply() {
1178
- consume(TOKEN.REPLY);
1710
+ const isRespond = peek().type === TOKEN.RESPOND;
1711
+ const isSendBack = peek().type === TOKEN.SEND_BACK;
1712
+ if (isRespond) {
1713
+ consume(TOKEN.RESPOND);
1714
+ } else if (isSendBack) {
1715
+ consume(TOKEN.SEND_BACK);
1716
+ } else {
1717
+ consume(TOKEN.REPLY);
1718
+ }
1179
1719
  if (peek().type === TOKEN.JSON_KW) {
1180
1720
  advance(); // consume json
1181
1721
  const properties = [];
@@ -1194,6 +1734,12 @@ function parse(tokens) {
1194
1734
  advance(); // consume DONE
1195
1735
  return { type: 'ReplyJsonStatement', properties };
1196
1736
  }
1737
+ if (peek().type === TOKEN.FILE_KW) {
1738
+ advance(); // consume file
1739
+ const filePath = consume(TOKEN.STRING,
1740
+ 'Expected a file path string after "reply file".\n\nExample:\n route get "/"\n reply file "public/index.html"\n done').value;
1741
+ return { type: 'ReplyFileStatement', filePath };
1742
+ }
1197
1743
  const value = parseExpression();
1198
1744
 
1199
1745
  // reply <value> with buttons ... done → Telegram inline keyboard block.
@@ -1241,11 +1787,19 @@ function parse(tokens) {
1241
1787
  return rows;
1242
1788
  }
1243
1789
 
1244
- // serve folder "<path>"
1790
+ // serve folder "<path>" / serve static "<path>" / serve public "<path>"
1245
1791
  function parseServeFolder() {
1246
- consume(TOKEN.SERVE);
1792
+ const isStatic = peek().type === TOKEN.SERVE_STATIC;
1793
+ const isPublic = peek().type === TOKEN.SERVE_PUBLIC;
1794
+ if (isStatic) {
1795
+ consume(TOKEN.SERVE_STATIC);
1796
+ } else if (isPublic) {
1797
+ consume(TOKEN.SERVE_PUBLIC);
1798
+ } else {
1799
+ consume(TOKEN.SERVE);
1800
+ }
1247
1801
  consume(TOKEN.FOLDER,
1248
- 'Expected "folder" after "serve".\n\nExample:\n serve folder "public"');
1802
+ 'Expected "folder" after "serve" / "serve static" / "serve public".\n\nExample:\n serve folder "public"');
1249
1803
  const folder = consume(TOKEN.STRING,
1250
1804
  'Expected a folder path string after "serve folder".\n\nExample:\n serve folder "public"').value;
1251
1805
  return { type: 'ServeFolderStatement', folder };
@@ -1303,11 +1857,16 @@ function parse(tokens) {
1303
1857
  return { type: 'ExpressionStatement', expression: { type: 'CallExpression', name: 'bot', args: [token] } };
1304
1858
  }
1305
1859
 
1306
- // start <port>
1860
+ // start <port> / run on <port>
1307
1861
  // start telegram bot — explicit Telegram startup marker. Polling keeps
1308
1862
  // the bot alive, so this form is only for documentation/intent.
1309
1863
  function parseStart() {
1310
- consume(TOKEN.START_KW);
1864
+ const isRunOn = peek().type === TOKEN.RUN_ON;
1865
+ if (isRunOn) {
1866
+ consume(TOKEN.RUN_ON);
1867
+ } else {
1868
+ consume(TOKEN.START_KW);
1869
+ }
1311
1870
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'telegram') {
1312
1871
  advance();
1313
1872
  const botToken = peek();
@@ -1326,7 +1885,7 @@ function parse(tokens) {
1326
1885
 
1327
1886
  // ── v0.6 — SQLite DX ───────────────────────────────────────────────────────
1328
1887
 
1329
- // database "<file>" [using "<driver>"]
1888
+ // database "<file>" [using "<driver>"] / connect database "<file>" [using "<driver>"] / use database "<file>" [using "<driver>"]
1330
1889
  //
1331
1890
  // v2.1.1 — the optional driver selects the SQLite engine without changing
1332
1891
  // any other PlainScript database semantics:
@@ -1335,9 +1894,28 @@ function parse(tokens) {
1335
1894
  // The default ("auto") tries native first and falls back to the wasm
1336
1895
  // engine when the native binding is unavailable on this platform.
1337
1896
  function parseDatabase() {
1338
- consume(TOKEN.DATABASE_KW);
1897
+ const isConnect = peek().type === TOKEN.CONNECT_DB;
1898
+ const isUse = peek().type === TOKEN.USE_DATABASE;
1899
+ let keyword, example;
1900
+ if (isConnect) {
1901
+ keyword = 'connect database';
1902
+ example = 'connect database "app.db"';
1903
+ } else if (isUse) {
1904
+ keyword = 'use database';
1905
+ example = 'use database "app.db"';
1906
+ } else {
1907
+ keyword = 'database';
1908
+ example = 'database "app.db"';
1909
+ }
1910
+ if (isConnect) {
1911
+ consume(TOKEN.CONNECT_DB);
1912
+ } else if (isUse) {
1913
+ consume(TOKEN.USE_DATABASE);
1914
+ } else {
1915
+ consume(TOKEN.DATABASE_KW);
1916
+ }
1339
1917
  const file = consume(TOKEN.STRING,
1340
- 'Expected a database file path after "database".\n\nExample:\n database "app.db"').value;
1918
+ `Expected a database file path after "${keyword}".\n\nExample:\n ${example}`).value;
1341
1919
  let driver = null;
1342
1920
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'using') {
1343
1921
  advance(); // using
@@ -1362,6 +1940,19 @@ function parse(tokens) {
1362
1940
  return { type: 'PostgresStatement', connection };
1363
1941
  }
1364
1942
 
1943
+ // v2.2.0 — mongo "<connection-string>" [db "<name>"]: binds the MongoDB client.
1944
+ // Usage: mongo "mongodb://localhost:27017" db "mydb"
1945
+ function parseMongo() {
1946
+ const token = advance(); // mongo or mongodb
1947
+ const connection = parseExpression();
1948
+ let dbName = null;
1949
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'db') {
1950
+ advance(); // db
1951
+ dbName = parseExpression();
1952
+ }
1953
+ return { type: 'MongoStatement', connection, dbName };
1954
+ }
1955
+
1365
1956
  // query/insert/update/delete/execute SQL_BODY DONE
1366
1957
  //
1367
1958
  // v2.1.0 — the raw SQL may reference PlainScript variables with {name}
@@ -1385,12 +1976,20 @@ function parse(tokens) {
1385
1976
 
1386
1977
  // ── v2.1.1 — error handling, retries and backend middleware ───────────────
1387
1978
 
1388
- // try … [recover [when <err> catches "<ErrorType>"]] … done
1979
+ function isHandledBy() {
1980
+ return peek().type === TOKEN.IDENTIFIER && peek().value === 'handled' &&
1981
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'by';
1982
+ }
1983
+
1984
+ // try … [recover [when <err> catches "<ErrorType>"]] [finally …] … done
1985
+ // also: try … done handled by … done (v2.4 English alternative)
1389
1986
  function parseTryStatement() {
1390
1987
  advance(); // try
1391
1988
  const tryBody = [];
1989
+ // Parse try body - stop at "done", "recover", "finally", or "handled by"
1392
1990
  while (!(peek().type === TOKEN.DONE ||
1393
- (peek().type === TOKEN.IDENTIFIER && peek().value === 'recover'))) {
1991
+ (peek().type === TOKEN.IDENTIFIER && (peek().value === 'recover' || peek().value === 'finally')) ||
1992
+ isHandledBy())) {
1394
1993
  if (peek().type === TOKEN.EOF) {
1395
1994
  throw new Error(makeError(
1396
1995
  'Expected keyword "done" to close the "try" block before end of file.',
@@ -1400,15 +1999,20 @@ function parse(tokens) {
1400
1999
  const stmt = parseStatement();
1401
2000
  if (stmt) tryBody.push(stmt);
1402
2001
  }
2002
+ // Consume the "done" that closes the try body (if present)
2003
+ // "handled by" before done means recover is inline (no done separator)
2004
+ if (peek().type === TOKEN.DONE) {
2005
+ advance(); // consume "done" that closes try body
2006
+ }
1403
2007
  const catches = [];
1404
- while (peek().type !== TOKEN.DONE) {
1405
- if (peek().type === TOKEN.EOF) {
1406
- throw new Error(makeError(
1407
- 'Expected keyword "done" to close the "try" block before end of file.',
1408
- peek()
1409
- ));
2008
+ // Check for recover/handled-by/finally sections (may be multiple recover blocks)
2009
+ while ((peek().type === TOKEN.IDENTIFIER && peek().value === 'recover') || isHandledBy()) {
2010
+ if (isHandledBy()) {
2011
+ advance(); // handled
2012
+ advance(); // by
2013
+ } else {
2014
+ advance(); // recover
1410
2015
  }
1411
- advance(); // recover
1412
2016
  let paramName = null;
1413
2017
  let errorType = null;
1414
2018
  if (peek().type === TOKEN.AS) {
@@ -1427,7 +2031,8 @@ function parse(tokens) {
1427
2031
  }
1428
2032
  const recoverBody = [];
1429
2033
  while (peek().type !== TOKEN.DONE &&
1430
- !(peek().type === TOKEN.IDENTIFIER && peek().value === 'recover')) {
2034
+ !(peek().type === TOKEN.IDENTIFIER && (peek().value === 'recover' || peek().value === 'finally')) &&
2035
+ !isHandledBy()) {
1431
2036
  if (peek().type === TOKEN.EOF) {
1432
2037
  throw new Error(makeError(
1433
2038
  'Expected keyword "done" to close the "recover" block before end of file.',
@@ -1437,10 +2042,27 @@ function parse(tokens) {
1437
2042
  const stmt = parseStatement();
1438
2043
  if (stmt) recoverBody.push(stmt);
1439
2044
  }
2045
+ advance(); // consume "done" that closes recover body
1440
2046
  catches.push({ param: paramName, errorType, body: recoverBody });
1441
2047
  }
1442
- advance(); // done
1443
- return { type: 'TryStatement', body: tryBody, catches };
2048
+ let finallyBody = null;
2049
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'finally') {
2050
+ advance(); // finally
2051
+ finallyBody = [];
2052
+ while (peek().type !== TOKEN.DONE) {
2053
+ if (peek().type === TOKEN.EOF) {
2054
+ throw new Error(makeError(
2055
+ 'Expected keyword "done" to close the "finally" block before end of file.',
2056
+ peek()
2057
+ ));
2058
+ }
2059
+ const stmt = parseStatement();
2060
+ if (stmt) finallyBody.push(stmt);
2061
+ }
2062
+ advance(); // consume "done" that closes the finally block
2063
+ }
2064
+ // No final "done" advance here — the enclosing parseBody() consumes it
2065
+ return { type: 'TryStatement', body: tryBody, catches, finallyBody };
1444
2066
  }
1445
2067
 
1446
2068
  // retry <n> times [every <n> seconds] … done
@@ -1454,7 +2076,8 @@ function parse(tokens) {
1454
2076
  ));
1455
2077
  }
1456
2078
  const timesToken = peek();
1457
- if (timesToken.type !== TOKEN.IDENTIFIER || timesToken.value !== 'times') {
2079
+ if (!((timesToken.type === TOKEN.IDENTIFIER && timesToken.value === 'times') ||
2080
+ timesToken.type === TOKEN.TIMES_WORD)) {
1458
2081
  throw new Error(makeError(
1459
2082
  'Expected "times" after the number of retries.\n\nExample:\n retry 3 times',
1460
2083
  timesToken
@@ -1511,16 +2134,25 @@ function parse(tokens) {
1511
2134
  }
1512
2135
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'allow' && mimes === null) {
1513
2136
  advance(); // allow
1514
- const list = parseArrayLiteral();
1515
- for (const element of list.elements) {
2137
+ let elements;
2138
+ // v2.4 — accept "list with" as alternative to bracket syntax
2139
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'list' &&
2140
+ peekAt(1).type === TOKEN.WITH) {
2141
+ advance(); // "list"
2142
+ advance(); // "with"
2143
+ elements = parseListWithElements();
2144
+ } else {
2145
+ elements = parseArrayLiteral().elements;
2146
+ }
2147
+ for (const element of elements) {
1516
2148
  if (element.type !== 'StringLiteral') {
1517
2149
  throw new Error(makeError(
1518
- 'MIME types in "accept uploads allow [...]" must be strings.\n\nExample:\n accept uploads allow ["image/png", "image/jpeg"]',
2150
+ 'MIME types in "accept uploads allow" must be strings.\n\nExample:\n accept uploads allow list with "image/png", "image/jpeg"',
1519
2151
  peek()
1520
2152
  ));
1521
2153
  }
1522
2154
  }
1523
- mimes = list.elements.map(element => element.value);
2155
+ mimes = elements.map(element => element.value);
1524
2156
  continue;
1525
2157
  }
1526
2158
  // ("folder" lexes as the FOLDER keyword, so both token shapes count.)
@@ -1570,7 +2202,7 @@ function parse(tokens) {
1570
2202
  const name = consume(TOKEN.STRING,
1571
2203
  'Expected a cookie name string after "set cookie".\n\nExample:\n set cookie "theme" to "dark"').value;
1572
2204
  const toToken = peek();
1573
- if (toToken.type !== TOKEN.IDENTIFIER || toToken.value !== 'to') {
2205
+ if (toToken.type !== TOKEN.IDENTIFIER && toToken.type !== TOKEN.TO) {
1574
2206
  throw new Error(makeError(
1575
2207
  'Expected "to" after the cookie name.\n\nExample:\n set cookie "theme" to "dark"',
1576
2208
  toToken
@@ -1615,7 +2247,7 @@ function parse(tokens) {
1615
2247
  advance(); // limit
1616
2248
  advance(); // requests
1617
2249
  const toToken = peek();
1618
- if (toToken.type !== TOKEN.IDENTIFIER || toToken.value !== 'to') {
2250
+ if (toToken.type !== TOKEN.IDENTIFIER && toToken.type !== TOKEN.TO) {
1619
2251
  throw new Error(makeError(
1620
2252
  'Expected "to" after "limit requests".\n\nExample:\n limit requests to 100 per minute',
1621
2253
  toToken
@@ -1655,7 +2287,7 @@ function parse(tokens) {
1655
2287
  const condition = parseCondition();
1656
2288
 
1657
2289
  const consequent = [];
1658
- while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE) {
2290
+ while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1659
2291
  if (peek().type === TOKEN.EOF) {
1660
2292
  throw new Error(makeError(
1661
2293
  'Expected keyword "done" before end of file to close the "if" block.',
@@ -1677,7 +2309,7 @@ function parse(tokens) {
1677
2309
  alternate = [parseElseIfChain()];
1678
2310
  } else {
1679
2311
  alternate = [];
1680
- while (peek().type !== TOKEN.DONE) {
2312
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1681
2313
  if (peek().type === TOKEN.EOF) {
1682
2314
  throw new Error(makeError(
1683
2315
  'Expected keyword "done" before end of file to close the "otherwise" block.',
@@ -1690,7 +2322,7 @@ function parse(tokens) {
1690
2322
  }
1691
2323
  }
1692
2324
 
1693
- advance(); // consume DONE
2325
+ advance(); // consume DONE or TOGETHER
1694
2326
  return { type: 'IfStatement', condition, consequent, alternate };
1695
2327
  }
1696
2328
 
@@ -1703,7 +2335,7 @@ function parse(tokens) {
1703
2335
  const condition = parseCondition();
1704
2336
 
1705
2337
  const consequent = [];
1706
- while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE) {
2338
+ while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1707
2339
  if (peek().type === TOKEN.EOF) {
1708
2340
  throw new Error(makeError(
1709
2341
  'Expected keyword "done" before end of file to close the "otherwise if" block.',
@@ -1722,7 +2354,7 @@ function parse(tokens) {
1722
2354
  alternate = [parseElseIfChain()];
1723
2355
  } else {
1724
2356
  alternate = [];
1725
- while (peek().type !== TOKEN.DONE) {
2357
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1726
2358
  if (peek().type === TOKEN.EOF) {
1727
2359
  throw new Error(makeError(
1728
2360
  'Expected keyword "done" before end of file to close the "otherwise" block.',
@@ -1742,7 +2374,7 @@ function parse(tokens) {
1742
2374
 
1743
2375
  function parseBody(context) {
1744
2376
  const body = [];
1745
- while (peek().type !== TOKEN.DONE) {
2377
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1746
2378
  if (peek().type === TOKEN.EOF) {
1747
2379
  throw new Error(makeError(
1748
2380
  `Expected keyword "done" to close the ${context} before end of file.`,
@@ -1752,37 +2384,83 @@ function parse(tokens) {
1752
2384
  const stmt = parseStatement();
1753
2385
  if (stmt) body.push(stmt);
1754
2386
  }
1755
- advance(); // consume DONE
2387
+ advance(); // consume DONE or TOGETHER
1756
2388
  return body;
1757
2389
  }
1758
2390
 
1759
2391
  // ── Expressions ────────────────────────────────────────────────────────────
1760
2392
 
1761
2393
  // v2.1.1 — full arithmetic precedence:
2394
+ // nullish := additive ("??" additive)*
1762
2395
  // additive := term (("+" | "-") term)*
1763
- // multiplicative ("term") := unary (("*" | "/" | "%") unary)*
2396
+ // multiplicative ("term") := power (("*" | "/" | "%") power)*
2397
+ // power := unary ("**" power)*
1764
2398
  // unary := "-" unary | "wait for" unary | primary
1765
- // primary := atom with postfix chains (indexing, members, of, length)
2399
+ // primary := atom with postfix chains (indexing, members, of, length, optional chaining)
1766
2400
  function parseExpression() {
2401
+ if (peek().type === TOKEN.CHOOSING) {
2402
+ advance();
2403
+ const condition = parseCondition();
2404
+ if (peek().type === TOKEN.THEN) advance();
2405
+ const consequent = parseExpression();
2406
+ if (peek().type === TOKEN.OTHERWISE) advance();
2407
+ const alternate = parseExpression();
2408
+ return { type: 'ConditionalExpression', condition, consequent, alternate };
2409
+ }
2410
+ let left = parseNullish();
2411
+ return left;
2412
+ }
2413
+
2414
+ function parseNullish() {
2415
+ let left = parseAdditive();
2416
+ while (peek().type === TOKEN.NULLISH_COALESCE) {
2417
+ advance();
2418
+ const right = parseAdditive();
2419
+ left = { type: 'NullishCoalesceExpression', left, right };
2420
+ }
2421
+ return left;
2422
+ }
2423
+
2424
+ function parseAdditive() {
1767
2425
  let left = parseTerm();
1768
- while (peek().type === TOKEN.PLUS || peek().type === TOKEN.MINUS) {
1769
- const operator = advance().value;
2426
+ while (peek().type === TOKEN.PLUS || peek().type === TOKEN.MINUS ||
2427
+ peek().type === TOKEN.PLUS_WORD || peek().type === TOKEN.MINUS_WORD) {
2428
+ const opToken = advance();
2429
+ const op = opToken.type === TOKEN.PLUS_WORD ? '+' :
2430
+ opToken.type === TOKEN.MINUS_WORD ? '-' :
2431
+ opToken.value;
1770
2432
  const right = parseTerm();
1771
- left = { type: 'BinaryExpression', operator, left, right };
2433
+ left = { type: 'BinaryExpression', operator: op, left, right };
1772
2434
  }
1773
2435
  return left;
1774
2436
  }
1775
2437
 
1776
2438
  function parseTerm() {
1777
- let left = parseUnary();
2439
+ let left = parsePower();
1778
2440
  while (
1779
2441
  peek().type === TOKEN.STAR ||
1780
2442
  peek().type === TOKEN.SLASH ||
1781
- peek().type === TOKEN.PERCENT
2443
+ peek().type === TOKEN.PERCENT ||
2444
+ peek().type === TOKEN.TIMES_WORD ||
2445
+ peek().type === TOKEN.DIVIDED_BY_WORD
1782
2446
  ) {
1783
- const operator = advance().value;
1784
- const right = parseUnary();
1785
- left = { type: 'BinaryExpression', operator, left, right };
2447
+ const opToken = advance();
2448
+ const op = opToken.type === TOKEN.TIMES_WORD ? '*' :
2449
+ opToken.type === TOKEN.DIVIDED_BY_WORD ? '/' :
2450
+ opToken.value;
2451
+ const right = parsePower();
2452
+ left = { type: 'BinaryExpression', operator: op, left, right };
2453
+ }
2454
+ return left;
2455
+ }
2456
+
2457
+ // Exponentiation is right-associative: 2 ** 3 ** 2 = 2 ** (3 ** 2) = 512
2458
+ function parsePower() {
2459
+ let left = parseUnary();
2460
+ if (peek().type === TOKEN.POWER) {
2461
+ advance();
2462
+ const right = parsePower(); // right-associative
2463
+ left = { type: 'BinaryExpression', operator: '**', left, right };
1786
2464
  }
1787
2465
  return left;
1788
2466
  }
@@ -1792,6 +2470,16 @@ function parse(tokens) {
1792
2470
  advance();
1793
2471
  return { type: 'UnaryExpression', operator: '-', operand: parseUnary() };
1794
2472
  }
2473
+ // Spread operator (...) - used for array/object spreading
2474
+ if (peek().type === TOKEN.SPREAD) {
2475
+ advance();
2476
+ return { type: 'SpreadExpression', argument: parseUnary() };
2477
+ }
2478
+ // await expression (native, in addition to "wait for")
2479
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'await') {
2480
+ advance();
2481
+ return { type: 'AwaitExpression', value: parseUnary() };
2482
+ }
1795
2483
  // v2.1.1 — await semantics: "wait for <value>" awaits an async operation.
1796
2484
  // The operand binds tightly (a full postfix chain), so
1797
2485
  // "wait for loadUser(id) + 1" means "(await loadUser(id)) + 1".
@@ -1802,12 +2490,37 @@ function parse(tokens) {
1802
2490
  advance(); // for
1803
2491
  return { type: 'AwaitExpression', value: parseUnary() };
1804
2492
  }
2493
+ // typeof operator
2494
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'typeof') {
2495
+ advance();
2496
+ return { type: 'UnaryExpression', operator: 'typeof', operand: parseUnary() };
2497
+ }
2498
+ // void operator
2499
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'void') {
2500
+ advance();
2501
+ return { type: 'UnaryExpression', operator: 'void', operand: parseUnary() };
2502
+ }
2503
+ // delete operator
2504
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'delete') {
2505
+ advance();
2506
+ return { type: 'UnaryExpression', operator: 'delete', operand: parseUnary() };
2507
+ }
1805
2508
  return parsePrimary();
1806
2509
  }
1807
2510
 
1808
2511
  // primary → itemExpr | atom (postfix)*
1809
2512
  function parsePrimary() {
1810
- // v1.0.0 — record constructor: `create a Person with name "Ada" and age 17`.
2513
+ // v2.4 — "record with" and "list with" as expressions (contextual)
2514
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'record' &&
2515
+ peekAt(1).type === TOKEN.WITH) {
2516
+ return parseRecordWith(true);
2517
+ }
2518
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'list' &&
2519
+ peekAt(1).type === TOKEN.WITH) {
2520
+ return parseListWith();
2521
+ }
2522
+
2523
+ // v1.0.1 — record constructor: `create a Person with name "Ada" and age 17`.
1811
2524
  // `create` then an article ("a"/"an") then a kind name then "with" pairs.
1812
2525
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'create') {
1813
2526
  const a1 = peekAt(1);
@@ -1821,7 +2534,7 @@ function parse(tokens) {
1821
2534
  }
1822
2535
  }
1823
2536
 
1824
- // v1.0.0 — concurrency combinators: `all of [a(), b()]`, `any of [...]`,
2537
+ // v1.0.1 — concurrency combinators: `all of [a(), b()]`, `any of [...]`,
1825
2538
  // `settled of [...]`. Guard on the identifier + "of" lookahead so plain
1826
2539
  // property reads like `all of the_list` still work as well as prose.
1827
2540
  if (peek().type === TOKEN.IDENTIFIER &&
@@ -1833,7 +2546,7 @@ function parse(tokens) {
1833
2546
  return { type: 'ConcurrencyExpression', combo: comboKw, items };
1834
2547
  }
1835
2548
 
1836
- // v1.0.0 — `spread of <collection>` unfolds an iterable into a new array.
2549
+ // v1.0.1 — `spread of <collection>` unfolds an iterable into a new array.
1837
2550
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'spread' &&
1838
2551
  peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'of') {
1839
2552
  advance(); // spread
@@ -1853,8 +2566,54 @@ function parse(tokens) {
1853
2566
  node = { type: 'IndexExpression', object: node, index };
1854
2567
  } else if (peek().type === TOKEN.DOT) {
1855
2568
  advance();
1856
- const property = consume(TOKEN.IDENTIFIER, 'Expected a property name after ".".').value;
2569
+ // After ".", any word is a valid JS property/method name — including
2570
+ // words that are PlainScript keywords in other contexts (e.g. crypto
2571
+ // .update(...), obj .delete()). So accept any word token, not just an
2572
+ // identifier.
2573
+ const propToken = peek();
2574
+ if (propToken.type === TOKEN.EOF || !/^[A-Za-z_$]/.test(propToken.value)) {
2575
+ throw new Error(makeError('Expected a property name after ".".', propToken));
2576
+ }
2577
+ advance();
2578
+ const property = propToken.value;
1857
2579
  node = { type: 'MemberExpression', object: node, property };
2580
+ // Method call: object.method(args). Only member access may introduce
2581
+ // a call here; plain `name(args)` is handled in parseAtom.
2582
+ if (peek().type === TOKEN.LPAREN) {
2583
+ advance(); // (
2584
+ const { separator, args } = parseArgList();
2585
+ consume(TOKEN.RPAREN, 'Expected ")" to close the method call.');
2586
+ if (separator) {
2587
+ throw new Error(makeError(
2588
+ 'Method calls cannot use "to"/"from" arguments.\n\nExample:\n mrz.parse(line)',
2589
+ peek()
2590
+ ));
2591
+ }
2592
+ node = { type: 'CallExpression', callee: node, args };
2593
+ }
2594
+ } else if (peek().type === TOKEN.OPTIONAL_CHAIN) {
2595
+ // Optional chaining: obj?.prop or obj?.method()
2596
+ advance(); // consume ?.
2597
+ const propToken = peek();
2598
+ if (propToken.type === TOKEN.EOF || !/^[A-Za-z_$]/.test(propToken.value)) {
2599
+ throw new Error(makeError('Expected a property name after "?.".', propToken));
2600
+ }
2601
+ advance();
2602
+ const property = propToken.value;
2603
+ node = { type: 'OptionalChainExpression', object: node, property };
2604
+ // Optional method call: obj?.method()
2605
+ if (peek().type === TOKEN.LPAREN) {
2606
+ advance(); // (
2607
+ const { separator, args } = parseArgList();
2608
+ consume(TOKEN.RPAREN, 'Expected ")" to close the method call.');
2609
+ if (separator) {
2610
+ throw new Error(makeError(
2611
+ 'Method calls cannot use "to"/"from" arguments.\n\nExample:\n obj?.method()',
2612
+ peek()
2613
+ ));
2614
+ }
2615
+ node = { type: 'OptionalCallExpression', callee: node, args };
2616
+ }
1858
2617
  } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') {
1859
2618
  if (node.type !== 'Identifier') {
1860
2619
  throw new Error(makeError(
@@ -1868,6 +2627,11 @@ function parse(tokens) {
1868
2627
  } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'length') {
1869
2628
  advance();
1870
2629
  node = { type: 'LengthExpression', object: node };
2630
+ } else if (peek().type === TOKEN.AT && peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'position') {
2631
+ advance(); // at
2632
+ advance(); // position
2633
+ const idx = consume(TOKEN.NUMBER, 'Expected a number after "at position".').value;
2634
+ node = { type: 'IndexExpression', object: node, index: { type: 'NumberLiteral', value: idx } };
1871
2635
  } else {
1872
2636
  break;
1873
2637
  }
@@ -1888,6 +2652,9 @@ function parse(tokens) {
1888
2652
  if (second.type !== TOKEN.IDENTIFIER) return null;
1889
2653
  if (third.type !== TOKEN.IDENTIFIER) return null;
1890
2654
 
2655
+ // v2.4 — skip "different from" which is a comparison, not an item expression
2656
+ if (second.value === 'different' && third.value === 'from') return null;
2657
+
1891
2658
  // "first from players" / "last from players" — missing noun
1892
2659
  if ((first.value === 'first' || first.value === 'last') && second.value === 'from') {
1893
2660
  throw new Error(makeError(
@@ -1929,7 +2696,7 @@ function parse(tokens) {
1929
2696
  ));
1930
2697
  }
1931
2698
 
1932
- // atom → STRING | NUMBER | true | false | null | '(' expr ')' |
2699
+ // atom → STRING | NUMBER | true | false | null | undefined | BigInt | '(' expr ')' |
1933
2700
  // '[' ... ']' | '{' ... '}' | httpCall | IDENTIFIER '(' args ')' | IDENTIFIER
1934
2701
  function parseAtom() {
1935
2702
  const token = peek();
@@ -1937,10 +2704,30 @@ function parse(tokens) {
1937
2704
  if (token.type === TOKEN.STRING) { advance(); return { type: 'StringLiteral', value: token.value }; }
1938
2705
  if (token.type === TOKEN.TEMPLATE_STRING) { advance(); return { type: 'TemplateLiteral', value: token.value }; }
1939
2706
  if (token.type === TOKEN.NUMBER) { advance(); return { type: 'NumberLiteral', value: token.value }; }
2707
+ if (token.type === TOKEN.BIGINT) { advance(); return { type: 'BigIntLiteral', value: token.value }; }
1940
2708
  // v2.1.1 — boolean and null literals
1941
2709
  if (token.type === TOKEN.TRUE_KW) { advance(); return { type: 'BooleanLiteral', value: true }; }
1942
2710
  if (token.type === TOKEN.FALSE_KW) { advance(); return { type: 'BooleanLiteral', value: false }; }
1943
2711
  if (token.type === TOKEN.NULL_KW) { advance(); return { type: 'NullLiteral' }; }
2712
+ if (token.type === TOKEN.UNDEFINED_KW) { advance(); return { type: 'UndefinedLiteral' }; }
2713
+ // symbol keyword - parse as Symbol() call
2714
+ if (token.type === TOKEN.SYMBOL_KW) {
2715
+ advance();
2716
+ if (peek().type === TOKEN.LPAREN) {
2717
+ advance(); // consume (
2718
+ const { separator, args } = parseArgList();
2719
+ consume(TOKEN.RPAREN, 'Expected ")" to close the symbol call.');
2720
+ if (separator) {
2721
+ throw new Error(makeError(
2722
+ 'Symbol calls cannot use "to"/"from" arguments.\n\nExample:\n symbol("desc")',
2723
+ peek()
2724
+ ));
2725
+ }
2726
+ return { type: 'CallExpression', name: 'Symbol', args };
2727
+ }
2728
+ // Bare symbol keyword - treat as Symbol() with no args
2729
+ return { type: 'CallExpression', name: 'Symbol', args: [] };
2730
+ }
1944
2731
  // v2.1.1 — parenthesised grouping: (a + b) * c
1945
2732
  if (token.type === TOKEN.LPAREN) {
1946
2733
  advance();
@@ -1960,8 +2747,48 @@ function parse(tokens) {
1960
2747
  return parseHttpCall(httpMethod);
1961
2748
  }
1962
2749
 
1963
- if (token.type === TOKEN.IDENTIFIER) {
2750
+ // Handle import.meta (IMPORT token followed by .meta)
2751
+ if (token.type === TOKEN.IMPORT && peekAt(1).type === TOKEN.DOT && peekAt(2).type === TOKEN.IDENTIFIER && peekAt(2).value === 'meta') {
2752
+ advance(); // import
2753
+ advance(); // .
2754
+ advance(); // meta
2755
+ return { type: 'ImportMetaExpression' };
2756
+ }
2757
+
2758
+ // Keywords that can also be used as identifiers in expression context
2759
+ const IDENTIFIER_KEYWORDS = new Set([TOKEN.BACK, TOKEN.REPLY, TOKEN.RESPOND, TOKEN.SEND_BACK, TOKEN.FILE_KW]);
2760
+ if (token.type === TOKEN.IDENTIFIER || IDENTIFIER_KEYWORDS.has(token.type)) {
2761
+ if (peekAt(1).type === TOKEN.USES || peekAt(1).type === TOKEN.FILLS) {
2762
+ const callee = { type: 'Identifier', name: token.value };
2763
+ advance();
2764
+ advance(); // uses/fills
2765
+ const args = [];
2766
+ while (peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.DONE && peek().type !== TOKEN.EOF) {
2767
+ if (peek().type === TOKEN.COMMA) { advance(); continue; }
2768
+ args.push(parseExpression());
2769
+ }
2770
+ if (peek().type === TOKEN.TOGETHER) advance();
2771
+ return { type: 'CallExpression', callee, args };
2772
+ }
1964
2773
  if (peekAt(1).type === TOKEN.LPAREN) return parseCallExpression();
2774
+ // Handle 'this' and 'super' as special identifiers
2775
+ if (token.value === 'this') {
2776
+ advance();
2777
+ return { type: 'ThisExpression' };
2778
+ }
2779
+ if (token.value === 'super') {
2780
+ advance();
2781
+ // super.property or super(args)
2782
+ if (peek().type === TOKEN.DOT) {
2783
+ advance(); // .
2784
+ const prop = consume(TOKEN.IDENTIFIER, 'Expected property name after "super."').value;
2785
+ return { type: 'SuperProperty', property: prop };
2786
+ }
2787
+ if (peek().type === TOKEN.LPAREN) {
2788
+ return parseCallExpression(); // super() call
2789
+ }
2790
+ return { type: 'SuperExpression' };
2791
+ }
1965
2792
  advance();
1966
2793
  return { type: 'Identifier', name: token.value };
1967
2794
  }
@@ -2046,7 +2873,13 @@ function parse(tokens) {
2046
2873
  if (peek().type === TOKEN.EOF) {
2047
2874
  throw new Error(makeError('Expected "]" to close the array before end of file.', peek()));
2048
2875
  }
2049
- elements.push(parseExpression());
2876
+ // Support spread elements: [...arr, ...other]
2877
+ if (peek().type === TOKEN.SPREAD) {
2878
+ advance();
2879
+ elements.push({ type: 'SpreadElement', argument: parseExpression() });
2880
+ } else {
2881
+ elements.push(parseExpression());
2882
+ }
2050
2883
  if (peek().type === TOKEN.COMMA) advance();
2051
2884
  }
2052
2885
  consume(TOKEN.RBRACKET, 'Expected "]" to close the array.');
@@ -2054,7 +2887,8 @@ function parse(tokens) {
2054
2887
  }
2055
2888
 
2056
2889
  // v1.2 — Inline object literal: { key: value, ... }
2057
- function parseInlineObjectLiteral() {
2890
+ // If `isPattern` is true, allows shorthand { x, y } for destructuring
2891
+ function parseInlineObjectLiteral(isPattern) {
2058
2892
  consume(TOKEN.LBRACE);
2059
2893
  const properties = [];
2060
2894
  while (peek().type !== TOKEN.RBRACE) {
@@ -2064,8 +2898,16 @@ function parse(tokens) {
2064
2898
  peek()
2065
2899
  ));
2066
2900
  }
2901
+ // Support spread properties: { ...obj, key: value }
2902
+ if (peek().type === TOKEN.SPREAD) {
2903
+ advance();
2904
+ properties.push({ type: 'SpreadProperty', argument: parseExpression() });
2905
+ if (peek().type === TOKEN.COMMA) advance();
2906
+ continue;
2907
+ }
2067
2908
  const keyToken = peek();
2068
- if (keyToken.type !== TOKEN.IDENTIFIER && keyToken.type !== TOKEN.STRING) {
2909
+ // Allow keywords that are valid JS identifiers as property names (e.g., "back" from "give back")
2910
+ if (keyToken.type !== TOKEN.IDENTIFIER && keyToken.type !== TOKEN.STRING && keyToken.type !== TOKEN.BACK) {
2069
2911
  throw new Error(makeError(
2070
2912
  'Expected a property name inside the inline object.\n\nExample:\n { text: "hi" }',
2071
2913
  keyToken
@@ -2073,8 +2915,15 @@ function parse(tokens) {
2073
2915
  }
2074
2916
  advance();
2075
2917
  const key = keyToken.value;
2076
- consume(TOKEN.COLON, `Expected ":" after property name "${key}".\n\nExample:\n { ${key}: "hi" }`);
2077
- const value = parseExpression();
2918
+ let value = null;
2919
+ if (!isPattern && peek().type === TOKEN.COLON) {
2920
+ consume(TOKEN.COLON, `Expected ":" after property name "${key}".\n\nExample:\n { ${key}: "hi" }`);
2921
+ value = parseExpression();
2922
+ } else if (isPattern && peek().type === TOKEN.COLON) {
2923
+ // Allow explicit key: value in patterns too
2924
+ consume(TOKEN.COLON, `Expected ":" after property name "${key}".\n\nExample:\n { ${key}: "hi" }`);
2925
+ value = parseExpression();
2926
+ }
2078
2927
  properties.push({ key, value });
2079
2928
  if (peek().type === TOKEN.COMMA) advance();
2080
2929
  }
@@ -2092,8 +2941,19 @@ function parse(tokens) {
2092
2941
  peek()
2093
2942
  ));
2094
2943
  }
2095
- const key = consume(TOKEN.IDENTIFIER, 'Expected a property name.').value;
2096
- consume(TOKEN.IS, `Expected "is" after property name "${key}".\n\nExample:\n name is "Ayokunle"`);
2944
+ // Allow "back" (TOKEN.BACK) as a property name (it's a keyword for "give back" but valid in object literals)
2945
+ let key;
2946
+ if (peek().type === TOKEN.BACK) {
2947
+ key = advance().value;
2948
+ } else {
2949
+ key = consume(TOKEN.IDENTIFIER, 'Expected a property name.').value;
2950
+ }
2951
+ // Accept both "is" and "be" as the property separator
2952
+ if (peek().type === TOKEN.BE) {
2953
+ advance(); // consume "be"
2954
+ } else {
2955
+ consume(TOKEN.IS, `Expected "is" after property name "${key}".\n\nExample:\n name is "Ayokunle"`);
2956
+ }
2097
2957
  const value = parseExpression();
2098
2958
  properties.push({ key, value });
2099
2959
  }
@@ -2112,7 +2972,19 @@ function parse(tokens) {
2112
2972
  peek()
2113
2973
  ));
2114
2974
  }
2115
- const key = consume(TOKEN.IDENTIFIER, 'Expected a property name.').value;
2975
+ // v2.4 — accept keyword tokens as property names (e.g., "to" in mail transport)
2976
+ const keyToken = peek();
2977
+ if (keyToken.type === TOKEN.IDENTIFIER || keyToken.type === TOKEN.TO ||
2978
+ keyToken.type === TOKEN.FROM || keyToken.type === TOKEN.AND ||
2979
+ keyToken.type === TOKEN.OR || keyToken.type === TOKEN.NOT ||
2980
+ keyToken.type === TOKEN.IN || keyToken.type === TOKEN.WITH ||
2981
+ keyToken.type === TOKEN.AS || keyToken.type === TOKEN.IF ||
2982
+ keyToken.type === TOKEN.OTHERWISE) {
2983
+ advance();
2984
+ } else {
2985
+ throw new Error(makeError('Expected a property name.', keyToken));
2986
+ }
2987
+ const key = keyToken.value;
2116
2988
  consume(TOKEN.IS, `Expected "is" after property name "${key}".\n\nExample:\n ${key} is "value"`);
2117
2989
  const value = parseExpression();
2118
2990
  properties.push({ key, value });
@@ -2561,9 +3433,10 @@ function parse(tokens) {
2561
3433
  args.push(parseExpression());
2562
3434
  }
2563
3435
  // v1.1 — collection expressions: add(item to list) / remove(item from list) / write(data to "file")
2564
- if (args.length === 1 && peek().type === TOKEN.IDENTIFIER &&
2565
- (peek().value === 'to' || peek().value === 'from')) {
2566
- separator = peek().value;
3436
+ if (args.length === 1 && (
3437
+ (peek().type === TOKEN.IDENTIFIER && (peek().value === 'to' || peek().value === 'from')) ||
3438
+ peek().type === TOKEN.TO)) {
3439
+ separator = peek().value === 'to' ? 'to' : peek().value;
2567
3440
  advance();
2568
3441
  if (peek().type === TOKEN.EOF) {
2569
3442
  throw new Error(makeError(`Expected a value after "${separator}".`, peek()));
@@ -2590,6 +3463,94 @@ function parse(tokens) {
2590
3463
  ));
2591
3464
  }
2592
3465
 
3466
+ // switch <expr> against ... done
3467
+ function parseSwitchStatement() {
3468
+ advance(); // switch
3469
+ const discriminant = parseExpression();
3470
+ consume(TOKEN.AGAINST, 'Expected "against" after the switch expression.\n\nExample:\n switch value against\n "case1" → show "one"\n otherwise → show "other"\n done');
3471
+ const cases = [];
3472
+ let defaultCase = null;
3473
+ while (peek().type !== TOKEN.DONE) {
3474
+ if (peek().type === TOKEN.EOF) {
3475
+ throw new Error(makeError(
3476
+ 'Expected keyword "done" to close the "switch" block before end of file.',
3477
+ peek()
3478
+ ));
3479
+ }
3480
+ // otherwise → body
3481
+ if (peek().type === TOKEN.OTHERWISE) {
3482
+ advance(); // otherwise
3483
+ consume(TOKEN.ARROW, 'Expected "->" after "otherwise".\n\nExample:\n otherwise → show "other"');
3484
+ defaultCase = [];
3485
+ while (peek().type !== TOKEN.DONE) {
3486
+ if (peek().type === TOKEN.EOF) {
3487
+ throw new Error(makeError(
3488
+ 'Expected keyword "done" to close the "switch" block before end of file.',
3489
+ peek()
3490
+ ));
3491
+ }
3492
+ const stmt = parseStatement();
3493
+ if (stmt) defaultCase.push(stmt);
3494
+ }
3495
+ break;
3496
+ }
3497
+ const test = parseExpression();
3498
+ consume(TOKEN.ARROW, 'Expected "->" after the case expression.\n\nExample:\n "red" → show "stop"');
3499
+ const caseBody = [];
3500
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.OTHERWISE &&
3501
+ !(peek().type === TOKEN.STRING || peek().type === TOKEN.NUMBER ||
3502
+ peek().type === TOKEN.TRUE_KW || peek().type === TOKEN.FALSE_KW ||
3503
+ peek().type === TOKEN.NULL_KW)) {
3504
+ if (peek().type === TOKEN.EOF) {
3505
+ throw new Error(makeError(
3506
+ 'Expected keyword "done" to close the "switch" block before end of file.',
3507
+ peek()
3508
+ ));
3509
+ }
3510
+ const stmt = parseStatement();
3511
+ if (stmt) caseBody.push(stmt);
3512
+ }
3513
+ cases.push({ test, body: caseBody });
3514
+ }
3515
+ advance(); // done
3516
+ return { type: 'SwitchStatement', discriminant, cases, defaultCase };
3517
+ }
3518
+
3519
+ // class Name { ... }
3520
+ function parseClassDeclaration() {
3521
+ advance(); // class
3522
+ const name = consume(TOKEN.IDENTIFIER, 'Expected a class name after "class".').value;
3523
+ let superClass = null;
3524
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'extends') {
3525
+ advance();
3526
+ superClass = parseExpression();
3527
+ }
3528
+ // Class body: methods and properties
3529
+ // For now, we'll use a simplified approach - class body is a block of statements
3530
+ // In JavaScript, class body contains method definitions
3531
+ consume(TOKEN.LBRACE, 'Expected "{" after class name.');
3532
+ const body = [];
3533
+ while (peek().type !== TOKEN.RBRACE && peek().type !== TOKEN.EOF) {
3534
+ const stmt = parseStatement();
3535
+ if (stmt) body.push(stmt);
3536
+ }
3537
+ consume(TOKEN.RBRACE, 'Expected "}" to close the class body.');
3538
+ return { type: 'ClassDeclaration', name, superClass, body };
3539
+ }
3540
+
3541
+ // new ClassName(args)
3542
+ function parseNewExpression() {
3543
+ advance(); // new
3544
+ const callee = parsePrimary();
3545
+ if (peek().type === TOKEN.LPAREN) {
3546
+ advance(); // (
3547
+ const { separator, args } = parseArgList();
3548
+ consume(TOKEN.RPAREN, 'Expected ")" to close the constructor call.');
3549
+ return { type: 'NewExpression', callee, args };
3550
+ }
3551
+ return { type: 'NewExpression', callee, args: [] };
3552
+ }
3553
+
2593
3554
  // ── Program ────────────────────────────────────────────────────────────────
2594
3555
 
2595
3556
  const body = [];