plainscript-lang 1.0.1 → 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 +69 -73
  4. package/compiler/dependency-detector.js +5 -0
  5. package/compiler/formatter.js +1 -1
  6. package/compiler/generator.js +931 -89
  7. package/compiler/lexer.js +129 -53
  8. package/compiler/parser.js +995 -152
  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 +101 -608
  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,11 +348,36 @@ 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();
379
+ if (token.type === TOKEN.RETURN) return parseGive(); // alias for give
380
+ if (token.type === TOKEN.GIVE_BACK) return parseGive(); // alias for give
272
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();
@@ -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();
@@ -581,15 +750,15 @@ function parse(tokens) {
581
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
@@ -640,12 +809,47 @@ function parse(tokens) {
640
809
  return { type: 'ContinueStatement' };
641
810
  }
642
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
+
643
819
  const expr = parsePrimary();
644
820
 
645
- if (peek().type === TOKEN.BECOMES) {
646
- 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) {
647
851
  const value = parseExpression();
648
- return { type: 'BecomeStatement', target: expr, value };
852
+ return { type: 'BecomeStatement', target: expr, value, op: becomeOp };
649
853
  }
650
854
 
651
855
  if (expr.type === 'CallExpression' ||
@@ -674,33 +878,55 @@ function parse(tokens) {
674
878
  throw new Error(makeError(`Unexpected keyword "${token.value}".`, token));
675
879
  }
676
880
 
677
- // remember <name> as <value>
881
+ // remember <name> as <value> / let <name> is <value>
678
882
  // remember <name> as\n <key> is <val>\n...\ndone (object literal)
679
- // 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)
680
885
  function parseRemember() {
681
- consume(TOKEN.REMEMBER);
682
- const name = consume(
683
- TOKEN.IDENTIFIER,
684
- 'Expected a variable name after "remember".\n\nExample:\n remember age as 16'
685
- ).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';
686
922
  consume(
687
- TOKEN.AS,
688
- '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'}`
689
925
  );
690
926
 
691
- // JavaScript block: remember <name> as javascript … done
692
- if (peek().type === TOKEN.JAVASCRIPT_KW) {
693
- advance(); // consume javascript
694
- const bodyToken = peek();
695
- if (bodyToken.type !== TOKEN.JS_BODY) {
696
- throw new Error(makeError(
697
- 'Expected a JavaScript block after "javascript".\n\nExample:\n remember result as javascript\n await axios.get(url)\n done',
698
- bodyToken
699
- ));
700
- }
701
- const body = advance().value; // consume JS_BODY
702
- consume(TOKEN.DONE, 'Expected "done" to close the JavaScript block.');
703
- 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() };
704
930
  }
705
931
 
706
932
  // v2.1.0 — remember <name> as query|insert|update|delete … done
@@ -715,22 +941,22 @@ function parse(tokens) {
715
941
  const kind = kindToken.value;
716
942
  const sql = advance().value; // consume SQL_BODY
717
943
  consume(TOKEN.DONE, `Expected "done" to close the "${kind}" block.`);
718
- return { type: 'RememberSqlStatement', name, kind, ...extractSqlParams(sql) };
719
- }
720
-
721
- // Object literal: next token is IDENTIFIER followed by IS
722
- if (peek().type === TOKEN.IDENTIFIER && peekAt(1).type === TOKEN.IS) {
723
- return { type: 'RememberStatement', name, value: parseObjectLiteral() };
944
+ return { type: 'RememberSqlStatement', name: target, kind, ...extractSqlParams(sql) };
724
945
  }
725
946
 
726
947
  const value = parseExpression();
727
- return { type: 'RememberStatement', name, value };
948
+ return { type: 'RememberStatement', name: target, value };
728
949
  }
729
950
 
730
951
  // ask <variable>
731
952
  // ask "<prompt>" as <variable>
732
- function parseAsk() {
733
- 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
+ }
734
960
  if (peek().type === TOKEN.STRING) {
735
961
  const prompt = advance().value;
736
962
  consume(TOKEN.AS,
@@ -740,26 +966,10 @@ function parse(tokens) {
740
966
  return { type: 'AskStatement', prompt, variable };
741
967
  }
742
968
  const variable = consume(TOKEN.IDENTIFIER,
743
- '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;
744
970
  return { type: 'AskStatement', variable };
745
971
  }
746
972
 
747
- // javascript\n <raw JS>\ndone — statement-level JavaScript block.
748
- // Mirrors the `remember <name> as javascript` form but produces no value.
749
- function parseJavaScriptBlock() {
750
- consume(TOKEN.JAVASCRIPT_KW);
751
- const bodyToken = peek();
752
- if (bodyToken.type !== TOKEN.JS_BODY) {
753
- throw new Error(makeError(
754
- 'Expected a JavaScript block after "javascript".\n\nExample:\n javascript\n console.log("hi")\n done',
755
- bodyToken
756
- ));
757
- }
758
- const body = advance().value; // consume JS_BODY
759
- consume(TOKEN.DONE, 'Expected "done" to close the JavaScript block.');
760
- return { type: 'JavaScriptBlock', name: null, body };
761
- }
762
-
763
973
  // v2.0.1 — OCR capability.
764
974
  //
765
975
  // ocr "<image>" as <variable>
@@ -788,7 +998,15 @@ function parse(tokens) {
788
998
  }
789
999
 
790
1000
  function parseShow() {
791
- 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
+ }
792
1010
  // Support both keyword form (show "text") and call form (show("text")).
793
1011
  // A "(" after "show" only means a call when the matching ")" ends the
794
1012
  // expression; otherwise it is a grouped value like show (2 + 3) * 4.
@@ -820,6 +1038,8 @@ function parse(tokens) {
820
1038
  after.type === TOKEN.PERCENT || after.type === TOKEN.PLUS ||
821
1039
  after.type === TOKEN.MINUS || after.type === TOKEN.LBRACKET ||
822
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 ||
823
1043
  (after.type === TOKEN.IDENTIFIER &&
824
1044
  ['of', 'length', 'above', 'below', 'contains', 'matches', 'becomes'].includes(after.value))
825
1045
  );
@@ -829,13 +1049,27 @@ function parse(tokens) {
829
1049
  return false;
830
1050
  }
831
1051
 
832
- // make name(params) ... done
1052
+ // make name(params) ... done / define name(params) ... done / function name(params) ... done
833
1053
  function parseMake() {
834
- consume(TOKEN.MAKE);
835
- const name = consume(
836
- TOKEN.IDENTIFIER,
837
- 'Expected a function name after "make".\n\nExample:\n make greet()\n show "Hello"\n done'
838
- ).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;
839
1073
  consume(TOKEN.LPAREN, `Expected "(" after function name "${name}".`);
840
1074
  const params = parseParamList();
841
1075
  consume(TOKEN.RPAREN, 'Expected ")" to close the parameter list.');
@@ -843,27 +1077,164 @@ function parse(tokens) {
843
1077
  return { type: 'FunctionDeclaration', name, params, body };
844
1078
  }
845
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
+
846
1183
  function parseParamList() {
847
1184
  const params = [];
848
1185
  if (peek().type === TOKEN.RPAREN) return params;
849
- const firstName = consume(TOKEN.IDENTIFIER, 'Expected a parameter name.').value;
850
- const firstParam = { name: firstName };
851
- if (peek().type === TOKEN.AS) {
852
- advance(); // as
853
- const dv = parseDefaultValue();
854
- if (dv) firstParam.defaultValue = dv;
855
- }
856
- params.push(firstParam);
857
- while (peek().type === TOKEN.COMMA) {
858
- advance();
859
- const pName = consume(TOKEN.IDENTIFIER, 'Expected a parameter name after ",".').value;
860
- 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 };
861
1226
  if (peek().type === TOKEN.AS) {
862
1227
  advance(); // as
863
1228
  const dv = parseDefaultValue();
864
1229
  if (dv) param.defaultValue = dv;
865
1230
  }
866
- params.push(param);
1231
+ return param;
1232
+ }
1233
+
1234
+ params.push(parseParam());
1235
+ while (peek().type === TOKEN.COMMA) {
1236
+ advance();
1237
+ params.push(parseParam());
867
1238
  }
868
1239
  return params;
869
1240
  }
@@ -894,7 +1265,19 @@ function parse(tokens) {
894
1265
  }
895
1266
 
896
1267
  function parseGive() {
897
- 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
+ }
898
1281
  const value = parseExpression();
899
1282
  return { type: 'GiveStatement', value };
900
1283
  }
@@ -941,9 +1324,18 @@ function parse(tokens) {
941
1324
  const t = consume(TOKEN.IDENTIFIER, 'Expected a kind name after "kind called".');
942
1325
  name = t.value;
943
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
+ }
944
1336
  consume(TOKEN.WITH, 'Expected "with" after the kind name.\n\nExample:\n define a kind called "Person" with\n name is ""\n done');
945
1337
  const fields = parsePropertyList('kind "' + name + '" definition');
946
- return { type: 'DefineKindStatement', name, fields };
1338
+ return { type: 'DefineKindStatement', name, fields, extends: extendsKind };
947
1339
  }
948
1340
 
949
1341
  // v1.0.1 — record constructor (expression): `create a Person with name "Ada" and age 17`
@@ -1017,7 +1409,7 @@ function parse(tokens) {
1017
1409
  }
1018
1410
  advance(); // from
1019
1411
  const start = parseExpression();
1020
- if (peek().type === TOKEN.IDENTIFIER && peek().value === 'to') {
1412
+ if (peek().type === TOKEN.TO || (peek().type === TOKEN.IDENTIFIER && peek().value === 'to')) {
1021
1413
  advance(); // to
1022
1414
  } else {
1023
1415
  throw new Error(makeError(
@@ -1037,6 +1429,10 @@ function parse(tokens) {
1037
1429
 
1038
1430
  consume(TOKEN.EACH,
1039
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
+ }
1040
1436
  const item = consume(TOKEN.IDENTIFIER, 'Expected an item name after "each" or "every".').value;
1041
1437
  consume(TOKEN.IN, `Expected "in" after "${item}".\n\nExample:\n for each item in players`);
1042
1438
  const collection = parseExpression();
@@ -1052,43 +1448,43 @@ function parse(tokens) {
1052
1448
  return { type: 'WhileStatement', condition, body };
1053
1449
  }
1054
1450
 
1055
- // import "./file.ps"
1056
- // import { name1, name2 } from "./file.ps" (named imports — binds only the
1451
+ // import "./file.pln"
1452
+ // import { name1, name2 } from "./file.pln" (named imports — binds only the
1057
1453
  // listed symbols; the whole file is still bundled as a dependency)
1058
1454
  function parseImport() {
1059
1455
  consume(TOKEN.IMPORT);
1060
1456
 
1061
- // Named-import form: import { a, b } from "./file.ps"
1457
+ // Named-import form: import { a, b } from "./file.pln"
1062
1458
  if (peek().type === TOKEN.LBRACE) {
1063
1459
  advance(); // {
1064
1460
  const names = [];
1065
1461
  while (true) {
1066
1462
  names.push(consume(
1067
1463
  TOKEN.IDENTIFIER,
1068
- 'Expected an exported name inside the import braces.\n\nExample:\n import { helper } from "./util.ps"'
1464
+ 'Expected an exported name inside the import braces.\n\nExample:\n import { helper } from "./util.pln"'
1069
1465
  ).value);
1070
1466
  if (peek().type === TOKEN.COMMA) { advance(); continue; }
1071
1467
  break;
1072
1468
  }
1073
1469
  consume(TOKEN.RBRACE,
1074
- 'Expected "}" to close the import braces.\n\nExample:\n import { helper } from "./util.ps"');
1470
+ 'Expected "}" to close the import braces.\n\nExample:\n import { helper } from "./util.pln"');
1075
1471
  // The "from" is a plain identifier; tolerate its optional presence so
1076
- // both "import { x } from "./f.ps"" and "import { x } "./f.ps"" read
1472
+ // both "import { x } from "./f.pln"" and "import { x } "./f.pln"" read
1077
1473
  // naturally, but require it for the documented form.
1078
1474
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'from') {
1079
1475
  advance(); // from
1080
1476
  }
1081
1477
  const filePath = consume(
1082
1478
  TOKEN.STRING,
1083
- 'Expected a file path string after the import.\n\nExample:\n import { helper } from "./util.ps"'
1479
+ 'Expected a file path string after the import.\n\nExample:\n import { helper } from "./util.pln"'
1084
1480
  ).value;
1085
1481
  return { type: 'ImportStatement', path: filePath, names };
1086
1482
  }
1087
1483
 
1088
- // Whole-module form: import "./file.ps"
1484
+ // Whole-module form: import "./file.pln"
1089
1485
  const filePath = consume(
1090
1486
  TOKEN.STRING,
1091
- '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"'
1092
1488
  ).value;
1093
1489
  return { type: 'ImportStatement', path: filePath };
1094
1490
  }
@@ -1124,6 +1520,38 @@ function parse(tokens) {
1124
1520
  function parseWhen() {
1125
1521
  consume(TOKEN.WHEN);
1126
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
+
1127
1555
  // v2.1.1 — "when nothing matches … done" registers the 404 catch-all.
1128
1556
  // It must appear after every route in the source; the generated handler
1129
1557
  // keeps that position.
@@ -1257,20 +1685,37 @@ function parse(tokens) {
1257
1685
  return { type: 'TelegramCallbackStatement', data, body };
1258
1686
  }
1259
1687
 
1260
- // listen on <port> ... done
1688
+ // listen on <port> ... done / start on <port> ... done / serve on <port> ... done
1261
1689
  function parseListen() {
1262
- 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
+ }
1263
1699
  consume(TOKEN.ON,
1264
- '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');
1265
1701
  const port = parseExpression();
1266
1702
  const body = parseBody('"listen" block');
1267
1703
  return { type: 'ListenStatement', port, body };
1268
1704
  }
1269
1705
 
1270
- // reply <expr>
1271
- // 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>"
1272
1709
  function parseReply() {
1273
- 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
+ }
1274
1719
  if (peek().type === TOKEN.JSON_KW) {
1275
1720
  advance(); // consume json
1276
1721
  const properties = [];
@@ -1289,6 +1734,12 @@ function parse(tokens) {
1289
1734
  advance(); // consume DONE
1290
1735
  return { type: 'ReplyJsonStatement', properties };
1291
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
+ }
1292
1743
  const value = parseExpression();
1293
1744
 
1294
1745
  // reply <value> with buttons ... done → Telegram inline keyboard block.
@@ -1336,11 +1787,19 @@ function parse(tokens) {
1336
1787
  return rows;
1337
1788
  }
1338
1789
 
1339
- // serve folder "<path>"
1790
+ // serve folder "<path>" / serve static "<path>" / serve public "<path>"
1340
1791
  function parseServeFolder() {
1341
- 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
+ }
1342
1801
  consume(TOKEN.FOLDER,
1343
- '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"');
1344
1803
  const folder = consume(TOKEN.STRING,
1345
1804
  'Expected a folder path string after "serve folder".\n\nExample:\n serve folder "public"').value;
1346
1805
  return { type: 'ServeFolderStatement', folder };
@@ -1398,11 +1857,16 @@ function parse(tokens) {
1398
1857
  return { type: 'ExpressionStatement', expression: { type: 'CallExpression', name: 'bot', args: [token] } };
1399
1858
  }
1400
1859
 
1401
- // start <port>
1860
+ // start <port> / run on <port>
1402
1861
  // start telegram bot — explicit Telegram startup marker. Polling keeps
1403
1862
  // the bot alive, so this form is only for documentation/intent.
1404
1863
  function parseStart() {
1405
- 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
+ }
1406
1870
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'telegram') {
1407
1871
  advance();
1408
1872
  const botToken = peek();
@@ -1421,7 +1885,7 @@ function parse(tokens) {
1421
1885
 
1422
1886
  // ── v0.6 — SQLite DX ───────────────────────────────────────────────────────
1423
1887
 
1424
- // database "<file>" [using "<driver>"]
1888
+ // database "<file>" [using "<driver>"] / connect database "<file>" [using "<driver>"] / use database "<file>" [using "<driver>"]
1425
1889
  //
1426
1890
  // v2.1.1 — the optional driver selects the SQLite engine without changing
1427
1891
  // any other PlainScript database semantics:
@@ -1430,9 +1894,28 @@ function parse(tokens) {
1430
1894
  // The default ("auto") tries native first and falls back to the wasm
1431
1895
  // engine when the native binding is unavailable on this platform.
1432
1896
  function parseDatabase() {
1433
- 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
+ }
1434
1917
  const file = consume(TOKEN.STRING,
1435
- '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;
1436
1919
  let driver = null;
1437
1920
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'using') {
1438
1921
  advance(); // using
@@ -1457,6 +1940,19 @@ function parse(tokens) {
1457
1940
  return { type: 'PostgresStatement', connection };
1458
1941
  }
1459
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
+
1460
1956
  // query/insert/update/delete/execute SQL_BODY DONE
1461
1957
  //
1462
1958
  // v2.1.0 — the raw SQL may reference PlainScript variables with {name}
@@ -1480,12 +1976,20 @@ function parse(tokens) {
1480
1976
 
1481
1977
  // ── v2.1.1 — error handling, retries and backend middleware ───────────────
1482
1978
 
1483
- // 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)
1484
1986
  function parseTryStatement() {
1485
1987
  advance(); // try
1486
1988
  const tryBody = [];
1989
+ // Parse try body - stop at "done", "recover", "finally", or "handled by"
1487
1990
  while (!(peek().type === TOKEN.DONE ||
1488
- (peek().type === TOKEN.IDENTIFIER && peek().value === 'recover'))) {
1991
+ (peek().type === TOKEN.IDENTIFIER && (peek().value === 'recover' || peek().value === 'finally')) ||
1992
+ isHandledBy())) {
1489
1993
  if (peek().type === TOKEN.EOF) {
1490
1994
  throw new Error(makeError(
1491
1995
  'Expected keyword "done" to close the "try" block before end of file.',
@@ -1495,15 +1999,20 @@ function parse(tokens) {
1495
1999
  const stmt = parseStatement();
1496
2000
  if (stmt) tryBody.push(stmt);
1497
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
+ }
1498
2007
  const catches = [];
1499
- while (peek().type !== TOKEN.DONE) {
1500
- if (peek().type === TOKEN.EOF) {
1501
- throw new Error(makeError(
1502
- 'Expected keyword "done" to close the "try" block before end of file.',
1503
- peek()
1504
- ));
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
1505
2015
  }
1506
- advance(); // recover
1507
2016
  let paramName = null;
1508
2017
  let errorType = null;
1509
2018
  if (peek().type === TOKEN.AS) {
@@ -1522,7 +2031,8 @@ function parse(tokens) {
1522
2031
  }
1523
2032
  const recoverBody = [];
1524
2033
  while (peek().type !== TOKEN.DONE &&
1525
- !(peek().type === TOKEN.IDENTIFIER && peek().value === 'recover')) {
2034
+ !(peek().type === TOKEN.IDENTIFIER && (peek().value === 'recover' || peek().value === 'finally')) &&
2035
+ !isHandledBy()) {
1526
2036
  if (peek().type === TOKEN.EOF) {
1527
2037
  throw new Error(makeError(
1528
2038
  'Expected keyword "done" to close the "recover" block before end of file.',
@@ -1532,10 +2042,27 @@ function parse(tokens) {
1532
2042
  const stmt = parseStatement();
1533
2043
  if (stmt) recoverBody.push(stmt);
1534
2044
  }
2045
+ advance(); // consume "done" that closes recover body
1535
2046
  catches.push({ param: paramName, errorType, body: recoverBody });
1536
2047
  }
1537
- advance(); // done
1538
- 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 };
1539
2066
  }
1540
2067
 
1541
2068
  // retry <n> times [every <n> seconds] … done
@@ -1549,7 +2076,8 @@ function parse(tokens) {
1549
2076
  ));
1550
2077
  }
1551
2078
  const timesToken = peek();
1552
- if (timesToken.type !== TOKEN.IDENTIFIER || timesToken.value !== 'times') {
2079
+ if (!((timesToken.type === TOKEN.IDENTIFIER && timesToken.value === 'times') ||
2080
+ timesToken.type === TOKEN.TIMES_WORD)) {
1553
2081
  throw new Error(makeError(
1554
2082
  'Expected "times" after the number of retries.\n\nExample:\n retry 3 times',
1555
2083
  timesToken
@@ -1606,16 +2134,25 @@ function parse(tokens) {
1606
2134
  }
1607
2135
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'allow' && mimes === null) {
1608
2136
  advance(); // allow
1609
- const list = parseArrayLiteral();
1610
- 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) {
1611
2148
  if (element.type !== 'StringLiteral') {
1612
2149
  throw new Error(makeError(
1613
- '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"',
1614
2151
  peek()
1615
2152
  ));
1616
2153
  }
1617
2154
  }
1618
- mimes = list.elements.map(element => element.value);
2155
+ mimes = elements.map(element => element.value);
1619
2156
  continue;
1620
2157
  }
1621
2158
  // ("folder" lexes as the FOLDER keyword, so both token shapes count.)
@@ -1665,7 +2202,7 @@ function parse(tokens) {
1665
2202
  const name = consume(TOKEN.STRING,
1666
2203
  'Expected a cookie name string after "set cookie".\n\nExample:\n set cookie "theme" to "dark"').value;
1667
2204
  const toToken = peek();
1668
- if (toToken.type !== TOKEN.IDENTIFIER || toToken.value !== 'to') {
2205
+ if (toToken.type !== TOKEN.IDENTIFIER && toToken.type !== TOKEN.TO) {
1669
2206
  throw new Error(makeError(
1670
2207
  'Expected "to" after the cookie name.\n\nExample:\n set cookie "theme" to "dark"',
1671
2208
  toToken
@@ -1710,7 +2247,7 @@ function parse(tokens) {
1710
2247
  advance(); // limit
1711
2248
  advance(); // requests
1712
2249
  const toToken = peek();
1713
- if (toToken.type !== TOKEN.IDENTIFIER || toToken.value !== 'to') {
2250
+ if (toToken.type !== TOKEN.IDENTIFIER && toToken.type !== TOKEN.TO) {
1714
2251
  throw new Error(makeError(
1715
2252
  'Expected "to" after "limit requests".\n\nExample:\n limit requests to 100 per minute',
1716
2253
  toToken
@@ -1750,7 +2287,7 @@ function parse(tokens) {
1750
2287
  const condition = parseCondition();
1751
2288
 
1752
2289
  const consequent = [];
1753
- while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE) {
2290
+ while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1754
2291
  if (peek().type === TOKEN.EOF) {
1755
2292
  throw new Error(makeError(
1756
2293
  'Expected keyword "done" before end of file to close the "if" block.',
@@ -1772,7 +2309,7 @@ function parse(tokens) {
1772
2309
  alternate = [parseElseIfChain()];
1773
2310
  } else {
1774
2311
  alternate = [];
1775
- while (peek().type !== TOKEN.DONE) {
2312
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1776
2313
  if (peek().type === TOKEN.EOF) {
1777
2314
  throw new Error(makeError(
1778
2315
  'Expected keyword "done" before end of file to close the "otherwise" block.',
@@ -1785,7 +2322,7 @@ function parse(tokens) {
1785
2322
  }
1786
2323
  }
1787
2324
 
1788
- advance(); // consume DONE
2325
+ advance(); // consume DONE or TOGETHER
1789
2326
  return { type: 'IfStatement', condition, consequent, alternate };
1790
2327
  }
1791
2328
 
@@ -1798,7 +2335,7 @@ function parse(tokens) {
1798
2335
  const condition = parseCondition();
1799
2336
 
1800
2337
  const consequent = [];
1801
- while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE) {
2338
+ while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1802
2339
  if (peek().type === TOKEN.EOF) {
1803
2340
  throw new Error(makeError(
1804
2341
  'Expected keyword "done" before end of file to close the "otherwise if" block.',
@@ -1817,7 +2354,7 @@ function parse(tokens) {
1817
2354
  alternate = [parseElseIfChain()];
1818
2355
  } else {
1819
2356
  alternate = [];
1820
- while (peek().type !== TOKEN.DONE) {
2357
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1821
2358
  if (peek().type === TOKEN.EOF) {
1822
2359
  throw new Error(makeError(
1823
2360
  'Expected keyword "done" before end of file to close the "otherwise" block.',
@@ -1837,7 +2374,7 @@ function parse(tokens) {
1837
2374
 
1838
2375
  function parseBody(context) {
1839
2376
  const body = [];
1840
- while (peek().type !== TOKEN.DONE) {
2377
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1841
2378
  if (peek().type === TOKEN.EOF) {
1842
2379
  throw new Error(makeError(
1843
2380
  `Expected keyword "done" to close the ${context} before end of file.`,
@@ -1847,37 +2384,83 @@ function parse(tokens) {
1847
2384
  const stmt = parseStatement();
1848
2385
  if (stmt) body.push(stmt);
1849
2386
  }
1850
- advance(); // consume DONE
2387
+ advance(); // consume DONE or TOGETHER
1851
2388
  return body;
1852
2389
  }
1853
2390
 
1854
2391
  // ── Expressions ────────────────────────────────────────────────────────────
1855
2392
 
1856
2393
  // v2.1.1 — full arithmetic precedence:
2394
+ // nullish := additive ("??" additive)*
1857
2395
  // additive := term (("+" | "-") term)*
1858
- // multiplicative ("term") := unary (("*" | "/" | "%") unary)*
2396
+ // multiplicative ("term") := power (("*" | "/" | "%") power)*
2397
+ // power := unary ("**" power)*
1859
2398
  // unary := "-" unary | "wait for" unary | primary
1860
- // primary := atom with postfix chains (indexing, members, of, length)
2399
+ // primary := atom with postfix chains (indexing, members, of, length, optional chaining)
1861
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() {
1862
2425
  let left = parseTerm();
1863
- while (peek().type === TOKEN.PLUS || peek().type === TOKEN.MINUS) {
1864
- 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;
1865
2432
  const right = parseTerm();
1866
- left = { type: 'BinaryExpression', operator, left, right };
2433
+ left = { type: 'BinaryExpression', operator: op, left, right };
1867
2434
  }
1868
2435
  return left;
1869
2436
  }
1870
2437
 
1871
2438
  function parseTerm() {
1872
- let left = parseUnary();
2439
+ let left = parsePower();
1873
2440
  while (
1874
2441
  peek().type === TOKEN.STAR ||
1875
2442
  peek().type === TOKEN.SLASH ||
1876
- peek().type === TOKEN.PERCENT
2443
+ peek().type === TOKEN.PERCENT ||
2444
+ peek().type === TOKEN.TIMES_WORD ||
2445
+ peek().type === TOKEN.DIVIDED_BY_WORD
1877
2446
  ) {
1878
- const operator = advance().value;
1879
- const right = parseUnary();
1880
- 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 };
1881
2464
  }
1882
2465
  return left;
1883
2466
  }
@@ -1887,6 +2470,16 @@ function parse(tokens) {
1887
2470
  advance();
1888
2471
  return { type: 'UnaryExpression', operator: '-', operand: parseUnary() };
1889
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
+ }
1890
2483
  // v2.1.1 — await semantics: "wait for <value>" awaits an async operation.
1891
2484
  // The operand binds tightly (a full postfix chain), so
1892
2485
  // "wait for loadUser(id) + 1" means "(await loadUser(id)) + 1".
@@ -1897,11 +2490,36 @@ function parse(tokens) {
1897
2490
  advance(); // for
1898
2491
  return { type: 'AwaitExpression', value: parseUnary() };
1899
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
+ }
1900
2508
  return parsePrimary();
1901
2509
  }
1902
2510
 
1903
2511
  // primary → itemExpr | atom (postfix)*
1904
2512
  function parsePrimary() {
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
+
1905
2523
  // v1.0.1 — record constructor: `create a Person with name "Ada" and age 17`.
1906
2524
  // `create` then an article ("a"/"an") then a kind name then "with" pairs.
1907
2525
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'create') {
@@ -1973,6 +2591,29 @@ function parse(tokens) {
1973
2591
  }
1974
2592
  node = { type: 'CallExpression', callee: node, args };
1975
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
+ }
1976
2617
  } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') {
1977
2618
  if (node.type !== 'Identifier') {
1978
2619
  throw new Error(makeError(
@@ -1986,6 +2627,11 @@ function parse(tokens) {
1986
2627
  } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'length') {
1987
2628
  advance();
1988
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 } };
1989
2635
  } else {
1990
2636
  break;
1991
2637
  }
@@ -2006,6 +2652,9 @@ function parse(tokens) {
2006
2652
  if (second.type !== TOKEN.IDENTIFIER) return null;
2007
2653
  if (third.type !== TOKEN.IDENTIFIER) return null;
2008
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
+
2009
2658
  // "first from players" / "last from players" — missing noun
2010
2659
  if ((first.value === 'first' || first.value === 'last') && second.value === 'from') {
2011
2660
  throw new Error(makeError(
@@ -2047,7 +2696,7 @@ function parse(tokens) {
2047
2696
  ));
2048
2697
  }
2049
2698
 
2050
- // atom → STRING | NUMBER | true | false | null | '(' expr ')' |
2699
+ // atom → STRING | NUMBER | true | false | null | undefined | BigInt | '(' expr ')' |
2051
2700
  // '[' ... ']' | '{' ... '}' | httpCall | IDENTIFIER '(' args ')' | IDENTIFIER
2052
2701
  function parseAtom() {
2053
2702
  const token = peek();
@@ -2055,10 +2704,30 @@ function parse(tokens) {
2055
2704
  if (token.type === TOKEN.STRING) { advance(); return { type: 'StringLiteral', value: token.value }; }
2056
2705
  if (token.type === TOKEN.TEMPLATE_STRING) { advance(); return { type: 'TemplateLiteral', value: token.value }; }
2057
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 }; }
2058
2708
  // v2.1.1 — boolean and null literals
2059
2709
  if (token.type === TOKEN.TRUE_KW) { advance(); return { type: 'BooleanLiteral', value: true }; }
2060
2710
  if (token.type === TOKEN.FALSE_KW) { advance(); return { type: 'BooleanLiteral', value: false }; }
2061
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
+ }
2062
2731
  // v2.1.1 — parenthesised grouping: (a + b) * c
2063
2732
  if (token.type === TOKEN.LPAREN) {
2064
2733
  advance();
@@ -2078,8 +2747,48 @@ function parse(tokens) {
2078
2747
  return parseHttpCall(httpMethod);
2079
2748
  }
2080
2749
 
2081
- 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
+ }
2082
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
+ }
2083
2792
  advance();
2084
2793
  return { type: 'Identifier', name: token.value };
2085
2794
  }
@@ -2164,7 +2873,13 @@ function parse(tokens) {
2164
2873
  if (peek().type === TOKEN.EOF) {
2165
2874
  throw new Error(makeError('Expected "]" to close the array before end of file.', peek()));
2166
2875
  }
2167
- 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
+ }
2168
2883
  if (peek().type === TOKEN.COMMA) advance();
2169
2884
  }
2170
2885
  consume(TOKEN.RBRACKET, 'Expected "]" to close the array.');
@@ -2172,7 +2887,8 @@ function parse(tokens) {
2172
2887
  }
2173
2888
 
2174
2889
  // v1.2 — Inline object literal: { key: value, ... }
2175
- function parseInlineObjectLiteral() {
2890
+ // If `isPattern` is true, allows shorthand { x, y } for destructuring
2891
+ function parseInlineObjectLiteral(isPattern) {
2176
2892
  consume(TOKEN.LBRACE);
2177
2893
  const properties = [];
2178
2894
  while (peek().type !== TOKEN.RBRACE) {
@@ -2182,8 +2898,16 @@ function parse(tokens) {
2182
2898
  peek()
2183
2899
  ));
2184
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
+ }
2185
2908
  const keyToken = peek();
2186
- 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) {
2187
2911
  throw new Error(makeError(
2188
2912
  'Expected a property name inside the inline object.\n\nExample:\n { text: "hi" }',
2189
2913
  keyToken
@@ -2191,8 +2915,15 @@ function parse(tokens) {
2191
2915
  }
2192
2916
  advance();
2193
2917
  const key = keyToken.value;
2194
- consume(TOKEN.COLON, `Expected ":" after property name "${key}".\n\nExample:\n { ${key}: "hi" }`);
2195
- 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
+ }
2196
2927
  properties.push({ key, value });
2197
2928
  if (peek().type === TOKEN.COMMA) advance();
2198
2929
  }
@@ -2210,8 +2941,19 @@ function parse(tokens) {
2210
2941
  peek()
2211
2942
  ));
2212
2943
  }
2213
- const key = consume(TOKEN.IDENTIFIER, 'Expected a property name.').value;
2214
- 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
+ }
2215
2957
  const value = parseExpression();
2216
2958
  properties.push({ key, value });
2217
2959
  }
@@ -2230,7 +2972,19 @@ function parse(tokens) {
2230
2972
  peek()
2231
2973
  ));
2232
2974
  }
2233
- 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;
2234
2988
  consume(TOKEN.IS, `Expected "is" after property name "${key}".\n\nExample:\n ${key} is "value"`);
2235
2989
  const value = parseExpression();
2236
2990
  properties.push({ key, value });
@@ -2679,9 +3433,10 @@ function parse(tokens) {
2679
3433
  args.push(parseExpression());
2680
3434
  }
2681
3435
  // v1.1 — collection expressions: add(item to list) / remove(item from list) / write(data to "file")
2682
- if (args.length === 1 && peek().type === TOKEN.IDENTIFIER &&
2683
- (peek().value === 'to' || peek().value === 'from')) {
2684
- 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;
2685
3440
  advance();
2686
3441
  if (peek().type === TOKEN.EOF) {
2687
3442
  throw new Error(makeError(`Expected a value after "${separator}".`, peek()));
@@ -2708,6 +3463,94 @@ function parse(tokens) {
2708
3463
  ));
2709
3464
  }
2710
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
+
2711
3554
  // ── Program ────────────────────────────────────────────────────────────────
2712
3555
 
2713
3556
  const body = [];