plainscript-lang 1.0.0 → 1.0.2

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 (52) hide show
  1. package/README.md +157 -150
  2. package/compiler/bundler.js +2 -2
  3. package/compiler/cli.js +172 -65
  4. package/compiler/formatter.js +1 -1
  5. package/compiler/generator.js +905 -184
  6. package/compiler/lexer.js +128 -54
  7. package/compiler/parser.js +1075 -155
  8. package/compiler/version.js +1 -1
  9. package/docs/CAPABILITY_GAP_AUDIT.md +131 -30
  10. package/docs/PLAINSCRIPT-SPEC.md +584 -0
  11. package/docs/index.html +48 -52
  12. package/docs/website/script.js +110 -24
  13. package/docs/website/style.css +4 -4
  14. package/examples/arrays.pln +12 -0
  15. package/examples/{auth-api.ps → auth-api.pln} +3 -3
  16. package/examples/{cache-and-jobs.ps → cache-and-jobs.pln} +1 -1
  17. package/examples/{concurrency.ps → concurrency.pln} +8 -8
  18. package/examples/{database.ps → database.pln} +1 -1
  19. package/examples/{deployment.ps → deployment.pln} +2 -2
  20. package/examples/{email-send.ps → email-send.pln} +1 -1
  21. package/examples/{error-handling.ps → error-handling.pln} +8 -7
  22. package/examples/{expressions.ps → expressions.pln} +1 -1
  23. package/examples/{file-uploads.ps → file-uploads.pln} +4 -4
  24. package/examples/{files-and-config.ps → files-and-config.pln} +4 -4
  25. package/examples/football-backend/{app.ps → app.pln} +2 -2
  26. package/examples/{http-client.ps → http-client.pln} +18 -18
  27. package/examples/id-verification/{app.ps → app.pln} +1 -1
  28. package/examples/{loops.ps → loops.pln} +2 -3
  29. package/examples/modules/{app.ps → app.pln} +4 -4
  30. package/examples/modules/{math.ps → math.pln} +1 -1
  31. package/examples/{record-kinds.ps → record-kinds.pln} +4 -4
  32. package/examples/{rest-api-fetch.ps → rest-api-fetch.pln} +1 -1
  33. package/examples/{rest-api.ps → rest-api.pln} +5 -5
  34. package/examples/{scheduled-tasks.ps → scheduled-tasks.pln} +2 -2
  35. package/examples/{search-and-filter.ps → search-and-filter.pln} +5 -5
  36. package/examples/{sessions-and-cookies.ps → sessions-and-cookies.pln} +2 -2
  37. package/examples/start.pln +2 -0
  38. package/examples/{stdlib.ps → stdlib.pln} +2 -2
  39. package/examples/{telegram-bot.ps → telegram-bot.pln} +2 -2
  40. package/examples/{websocket-server.ps → websocket-server.pln} +1 -1
  41. package/package.json +2 -2
  42. package/docs/PLINJS_SPEC.md +0 -1151
  43. package/examples/arrays.ps +0 -13
  44. package/examples/start.ps +0 -2
  45. /package/examples/{day2.ps → day2.pln} +0 -0
  46. /package/examples/{day3.ps → day3.pln} +0 -0
  47. /package/examples/{hello.ps → hello.pln} +0 -0
  48. /package/examples/{objects.ps → objects.pln} +0 -0
  49. /package/examples/{server.ps → server.pln} +0 -0
  50. /package/examples/{web-app.ps → web-app.pln} +0 -0
  51. /package/examples/whatsapp-bot/{pairing.ps → pairing.pln} +0 -0
  52. /package/examples/whatsapp-bot/{qr.ps → qr.pln} +0 -0
@@ -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).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
@@ -494,7 +654,7 @@ function parse(tokens) {
494
654
 
495
655
  // v2.2.0 — redirect to "<url>": sends an HTTP redirect from a route
496
656
  // handler. "redirect(...)" calls and "redirect becomes x" stay ordinary.
497
- if (token.value === 'redirect' && peekAt(1).value === 'to') {
657
+ if (token.value === 'redirect' && (peekAt(1).value === 'to' || peekAt(1).type === TOKEN.TO)) {
498
658
  advance(); // redirect
499
659
  advance(); // to
500
660
  const url = parseExpression();
@@ -578,16 +738,16 @@ function parse(tokens) {
578
738
  return { type: 'GoogleOAuthStatement', options: parsePropertyList('"google oauth" block') };
579
739
  }
580
740
 
581
- // ── v1.0.0 — capability-gap features (all contextual, IOPL-native) ──
741
+ // ── v1.0.1 — capability-gap features (all contextual, IOPL-native) ──
582
742
 
583
743
  // define a kind called "Person" with … done → record schema (classes)
584
- if (token.value === 'define' &&
744
+ if ((token.type === TOKEN.DEFINE || (token.type === TOKEN.IDENTIFIER && token.value === 'define')) &&
585
745
  peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'a') {
586
746
  return parseDefineKind();
587
747
  }
588
748
 
589
749
  // load env file "<path>" → apply .env KEY=VALUE pairs to process.env
590
- if (token.value === 'load' &&
750
+ if ((token.type === TOKEN.LOAD || (token.type === TOKEN.IDENTIFIER && token.value === 'load')) &&
591
751
  peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'env' &&
592
752
  peekAt(2).type === TOKEN.IDENTIFIER && peekAt(2).value === 'file') {
593
753
  advance(); // load
@@ -617,12 +777,70 @@ function parse(tokens) {
617
777
  return { type: 'ExportStatement', name };
618
778
  }
619
779
 
780
+ // throw <value> → raise an error for the caller's try/recover to catch.
781
+ // "throw(...)" calls and "throw becomes x" keep their ordinary meaning.
782
+ if (token.value === 'throw' &&
783
+ peekAt(1).type !== TOKEN.LPAREN && peekAt(1).type !== TOKEN.BECOMES) {
784
+ advance(); // throw
785
+ const value = parseExpression();
786
+ return { type: 'ThrowStatement', value };
787
+ }
788
+
789
+ // break / continue → loop control flow. Contextual keywords: a variable
790
+ // literally named break/continue is rejected by the teaching guard in
791
+ // generateStatement when not inside a loop.
792
+ if (token.value === 'break' &&
793
+ peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
794
+ advance(); // break
795
+ return { type: 'BreakStatement' };
796
+ }
797
+ if (token.value === 'continue' &&
798
+ peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
799
+ advance(); // continue
800
+ return { type: 'ContinueStatement' };
801
+ }
802
+
803
+ // debugger statement
804
+ if (token.value === 'debugger' &&
805
+ peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
806
+ advance(); // debugger
807
+ return { type: 'DebuggerStatement' };
808
+ }
809
+
620
810
  const expr = parsePrimary();
621
811
 
622
- if (peek().type === TOKEN.BECOMES) {
623
- advance();
812
+ // Assignment operators: becomes, is now, set to, change to, or becomes (||=), and becomes (&&=), nullish becomes (??=)
813
+ let becomeOp = null;
814
+ if (peek().type === TOKEN.OR && peekAt(1).type === TOKEN.BECOMES) {
815
+ advance(); // or
816
+ advance(); // becomes
817
+ becomeOp = '||=';
818
+ } else if (peek().type === TOKEN.AND && peekAt(1).type === TOKEN.BECOMES) {
819
+ advance(); // and
820
+ advance(); // becomes
821
+ becomeOp = '&&=';
822
+ } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'nullish' && peekAt(1).type === TOKEN.BECOMES) {
823
+ advance(); // nullish
824
+ advance(); // becomes
825
+ becomeOp = '??=';
826
+ } else if (peek().type === TOKEN.BECOMES) {
827
+ advance(); // becomes
828
+ becomeOp = '=';
829
+ } else if (peek().type === TOKEN.IS && peekAt(1).type === TOKEN.NOW) {
830
+ advance(); // is
831
+ advance(); // now
832
+ becomeOp = '=';
833
+ } else if (peek().type === TOKEN.SET_TO) {
834
+ advance(); // set to
835
+ becomeOp = '=';
836
+ } else if (peek().type === TOKEN.CHANGE_TO) {
837
+ advance(); // change to
838
+ becomeOp = '=';
839
+ }
840
+
841
+ if (becomeOp !== null) {
624
842
  const value = parseExpression();
625
- return { type: 'BecomeStatement', target: expr, value };
843
+ return { type: 'BecomeStatement', target: expr, value, op: becomeOp };
626
844
  }
627
845
 
628
846
  if (expr.type === 'CallExpression' ||
@@ -651,33 +869,53 @@ function parse(tokens) {
651
869
  throw new Error(makeError(`Unexpected keyword "${token.value}".`, token));
652
870
  }
653
871
 
654
- // remember <name> as <value>
872
+ // remember <name> as <value> / let <name> is <value>
655
873
  // 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)
874
+ // remember [a, b] as array (array destructuring)
875
+ // remember {x, y} as obj (object destructuring)
657
876
  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;
877
+ const isLet = peek().type === TOKEN.LET;
878
+ if (isLet) {
879
+ consume(TOKEN.LET);
880
+ } else {
881
+ consume(TOKEN.REMEMBER);
882
+ }
883
+
884
+ // Check for destructuring patterns: [ ... ] or { ... }
885
+ let target;
886
+ if (peek().type === TOKEN.LBRACKET) {
887
+ target = parseArrayLiteral(); // returns ArrayLiteral with elements
888
+ target.type = 'ArrayPattern';
889
+ } else if (peek().type === TOKEN.LBRACE) {
890
+ target = parseInlineObjectLiteral(true); // returns InlineObjectLiteral with properties, destructuring mode
891
+ target.type = 'ObjectPattern';
892
+ } else {
893
+ // Allow "back" (TOKEN.BACK) as a variable name (it's a keyword for "give back" but valid as identifier)
894
+ let nameToken = peek();
895
+ if (nameToken.type === TOKEN.BACK) {
896
+ advance();
897
+ target = nameToken.value;
898
+ } else {
899
+ target = consume(
900
+ TOKEN.IDENTIFIER,
901
+ `Expected a variable name after "${isLet ? 'let' : 'remember'}".\n\nExample:\n ${isLet ? 'let age is 16' : 'remember age as 16'}`
902
+ ).value;
903
+ }
904
+ }
905
+
906
+ // "let" uses "is" or "be" for simple vars, but also accepts "as" for both simple and destructuring
907
+ // "remember" always uses "as"
908
+ const isDestructuring = target && typeof target === 'object' && (target.type === 'ArrayPattern' || target.type === 'ObjectPattern');
909
+ const assignToken = isLet ? ((peek().type === TOKEN.IS || peek().type === TOKEN.BE) ? peek().type : TOKEN.AS) : TOKEN.AS;
910
+ const expectedKeyword = (isLet && (peek().type === TOKEN.IS || peek().type === TOKEN.BE)) ? (peek().type === TOKEN.BE ? 'be' : 'is') : 'as';
663
911
  consume(
664
- TOKEN.AS,
665
- 'Expected keyword "as" after the variable name.\n\nExample:\n remember age as 16'
912
+ assignToken,
913
+ `Expected keyword "${expectedKeyword}" after the variable name.\n\nExample:\n ${isLet ? 'let age is 16' : 'remember age as 16'}`
666
914
  );
667
915
 
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 };
916
+ // Object literal: next token is IDENTIFIER followed by IS or BE
917
+ if (peek().type === TOKEN.IDENTIFIER && (peekAt(1).type === TOKEN.IS || peekAt(1).type === TOKEN.BE)) {
918
+ return { type: 'RememberStatement', name: target, value: parseObjectLiteral() };
681
919
  }
682
920
 
683
921
  // v2.1.0 — remember <name> as query|insert|update|delete … done
@@ -692,22 +930,22 @@ function parse(tokens) {
692
930
  const kind = kindToken.value;
693
931
  const sql = advance().value; // consume SQL_BODY
694
932
  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() };
933
+ return { type: 'RememberSqlStatement', name: target, kind, ...extractSqlParams(sql) };
701
934
  }
702
935
 
703
936
  const value = parseExpression();
704
- return { type: 'RememberStatement', name, value };
937
+ return { type: 'RememberStatement', name: target, value };
705
938
  }
706
939
 
707
940
  // ask <variable>
708
941
  // ask "<prompt>" as <variable>
709
- function parseAsk() {
710
- consume(TOKEN.ASK);
942
+ function parseAsk() {
943
+ const isPrompt = peek().type === TOKEN.PROMPT;
944
+ if (isPrompt) {
945
+ consume(TOKEN.PROMPT);
946
+ } else {
947
+ consume(TOKEN.ASK);
948
+ }
711
949
  if (peek().type === TOKEN.STRING) {
712
950
  const prompt = advance().value;
713
951
  consume(TOKEN.AS,
@@ -717,26 +955,10 @@ function parse(tokens) {
717
955
  return { type: 'AskStatement', prompt, variable };
718
956
  }
719
957
  const variable = consume(TOKEN.IDENTIFIER,
720
- 'Expected a variable name after "ask".\n\nExample:\n ask name').value;
958
+ 'Expected a variable name after "as".\n\nExample:\n ask "What is your name?" as name').value;
721
959
  return { type: 'AskStatement', variable };
722
960
  }
723
961
 
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
962
  // v2.0.1 — OCR capability.
741
963
  //
742
964
  // ocr "<image>" as <variable>
@@ -765,7 +987,15 @@ function parse(tokens) {
765
987
  }
766
988
 
767
989
  function parseShow() {
768
- consume(TOKEN.SHOW);
990
+ const isPrint = peek().type === TOKEN.PRINT;
991
+ const isDisplay = peek().type === TOKEN.DISPLAY;
992
+ if (isPrint) {
993
+ consume(TOKEN.PRINT);
994
+ } else if (isDisplay) {
995
+ consume(TOKEN.DISPLAY);
996
+ } else {
997
+ consume(TOKEN.SHOW);
998
+ }
769
999
  // Support both keyword form (show "text") and call form (show("text")).
770
1000
  // A "(" after "show" only means a call when the matching ")" ends the
771
1001
  // expression; otherwise it is a grouped value like show (2 + 3) * 4.
@@ -797,6 +1027,8 @@ function parse(tokens) {
797
1027
  after.type === TOKEN.PERCENT || after.type === TOKEN.PLUS ||
798
1028
  after.type === TOKEN.MINUS || after.type === TOKEN.LBRACKET ||
799
1029
  after.type === TOKEN.DOT ||
1030
+ after.type === TOKEN.TIMES_WORD || after.type === TOKEN.DIVIDED_BY_WORD ||
1031
+ after.type === TOKEN.PLUS_WORD || after.type === TOKEN.MINUS_WORD ||
800
1032
  (after.type === TOKEN.IDENTIFIER &&
801
1033
  ['of', 'length', 'above', 'below', 'contains', 'matches', 'becomes'].includes(after.value))
802
1034
  );
@@ -806,13 +1038,27 @@ function parse(tokens) {
806
1038
  return false;
807
1039
  }
808
1040
 
809
- // make name(params) ... done
1041
+ // make name(params) ... done / define name(params) ... done / function name(params) ... done
810
1042
  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;
1043
+ const isDefine = peek().type === TOKEN.DEFINE;
1044
+ const isFunction = peek().type === TOKEN.FUNCTION;
1045
+ if (isDefine) {
1046
+ consume(TOKEN.DEFINE);
1047
+ } else if (isFunction) {
1048
+ consume(TOKEN.FUNCTION);
1049
+ } else {
1050
+ consume(TOKEN.MAKE);
1051
+ }
1052
+ const keyword = isDefine ? 'define' : isFunction ? 'function' : 'make';
1053
+ // Allow "load" as a function name (it's also a keyword for "load env file")
1054
+ const nameToken = peek();
1055
+ if (nameToken.type !== TOKEN.IDENTIFIER && nameToken.type !== TOKEN.LOAD) {
1056
+ throw new Error(makeError(
1057
+ `Expected a function name after "${keyword}".\n\nExample:\n ${keyword} greet()\n show "Hello"\n done`,
1058
+ nameToken
1059
+ ));
1060
+ }
1061
+ const name = advance().value;
816
1062
  consume(TOKEN.LPAREN, `Expected "(" after function name "${name}".`);
817
1063
  const params = parseParamList();
818
1064
  consume(TOKEN.RPAREN, 'Expected ")" to close the parameter list.');
@@ -820,27 +1066,156 @@ function parse(tokens) {
820
1066
  return { type: 'FunctionDeclaration', name, params, body };
821
1067
  }
822
1068
 
1069
+ // v2.3 — English-like function declaration: "to <name> <a> and <b> together ... done"
1070
+ // Parameters are identifiers joined by "and". Body ends with "together" or "done".
1071
+ function parseToFunction() {
1072
+ consume(TOKEN.TO);
1073
+ const nameToken = peek();
1074
+ if (nameToken.type !== TOKEN.IDENTIFIER) {
1075
+ throw new Error(makeError(
1076
+ 'Expected a function name after "to".\n\nExample:\n to add a and b together\n give a + b\n together',
1077
+ nameToken
1078
+ ));
1079
+ }
1080
+ const name = advance().value;
1081
+ const params = [];
1082
+ // Parameters are identifiers joined by "and"
1083
+ while (peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.DONE) {
1084
+ if (peek().type === TOKEN.AND) {
1085
+ advance(); // skip "and" between parameters
1086
+ continue;
1087
+ }
1088
+ if (peek().type === TOKEN.EOF) {
1089
+ throw new Error(makeError(
1090
+ `Expected "together" or "done" to close function "${name}" before end of file.`,
1091
+ peek()
1092
+ ));
1093
+ }
1094
+ const paramToken = peek();
1095
+ if (paramToken.type !== TOKEN.IDENTIFIER) {
1096
+ throw new Error(makeError(
1097
+ `Expected a parameter name or "together"/"done" in function "${name}".`,
1098
+ paramToken
1099
+ ));
1100
+ }
1101
+ params.push({ name: advance().value });
1102
+ }
1103
+ const body = parseBody(`function "${name}"`);
1104
+ return { type: 'FunctionDeclaration', name, params, body };
1105
+ }
1106
+
1107
+ // v2.3 — English-like array literal: "list with 1, 2, 3"
1108
+ // Parse comma-separated elements for "list with" (shared helper)
1109
+ function parseListWithElements() {
1110
+ const elements = [];
1111
+ if (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.EOF &&
1112
+ peek().type !== TOKEN.FOLDER &&
1113
+ !(peek().type === TOKEN.IDENTIFIER && (peek().value === 'folder' || peek().value === 'done' || peek().value === 'together'))) {
1114
+ elements.push(parseExpression());
1115
+ while (peek().type === TOKEN.COMMA) {
1116
+ advance(); // consume comma
1117
+ elements.push(parseExpression());
1118
+ }
1119
+ }
1120
+ return elements;
1121
+ }
1122
+
1123
+ function parseListWith() {
1124
+ // Accept both "list_with" keyword and contextual "list" + "with"
1125
+ if (peek().type === TOKEN.LIST_WITH) {
1126
+ consume(TOKEN.LIST_WITH);
1127
+ } else {
1128
+ advance(); // "list"
1129
+ consume(TOKEN.WITH, 'Expected "with" after "list".');
1130
+ }
1131
+ const elements = parseListWithElements();
1132
+ return { type: 'ArrayLiteral', elements };
1133
+ }
1134
+
1135
+ // v2.3 — English-like object literal: "record with name 'Alice' and age 30"
1136
+ // consumeTerminator: true when used as expression (done closes record), false when standalone statement
1137
+ function parseRecordWith(consumeTerminator) {
1138
+ // Accept both "record_with" keyword and contextual "record" + "with"
1139
+ if (peek().type === TOKEN.RECORD_WITH) {
1140
+ consume(TOKEN.RECORD_WITH);
1141
+ } else {
1142
+ advance(); // "record"
1143
+ consume(TOKEN.WITH, 'Expected "with" after "record".');
1144
+ }
1145
+ const properties = [];
1146
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.EOF) {
1147
+ const keyToken = peek();
1148
+ if (keyToken.type !== TOKEN.IDENTIFIER) {
1149
+ throw new Error(makeError(
1150
+ 'Expected a property name after "record with".\n\nExample:\n record with name "Alice" and age 30',
1151
+ keyToken
1152
+ ));
1153
+ }
1154
+ advance(); // consume key
1155
+ const key = keyToken.value;
1156
+ if (peek().type === TOKEN.DONE || peek().type === TOKEN.TOGETHER || peek().type === TOKEN.EOF || peek().type === TOKEN.AND) {
1157
+ properties.push({ key, value: { type: 'UndefinedLiteral' } });
1158
+ } else {
1159
+ const value = parseNullish();
1160
+ properties.push({ key, value });
1161
+ }
1162
+ if (peek().type === TOKEN.AND) {
1163
+ advance(); // consume "and"
1164
+ }
1165
+ }
1166
+ if (consumeTerminator && (peek().type === TOKEN.DONE || peek().type === TOKEN.TOGETHER)) {
1167
+ advance(); // consume done/together when used as expression
1168
+ }
1169
+ return { type: 'InlineObjectLiteral', properties };
1170
+ }
1171
+
823
1172
  function parseParamList() {
824
1173
  const params = [];
825
1174
  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 };
1175
+
1176
+ function parseParam() {
1177
+ // Rest parameter: ...args
1178
+ if (peek().type === TOKEN.SPREAD) {
1179
+ advance();
1180
+ const name = consume(TOKEN.IDENTIFIER, 'Expected a parameter name after "...".').value;
1181
+ return { type: 'RestElement', name };
1182
+ }
1183
+ // Destructuring: [a, b] or {x, y}
1184
+ if (peek().type === TOKEN.LBRACKET) {
1185
+ const pattern = parseArrayLiteral();
1186
+ pattern.type = 'ArrayPattern';
1187
+ if (peek().type === TOKEN.AS) {
1188
+ advance();
1189
+ const dv = parseDefaultValue();
1190
+ if (dv) pattern.defaultValue = dv;
1191
+ }
1192
+ return pattern;
1193
+ }
1194
+ if (peek().type === TOKEN.LBRACE) {
1195
+ const pattern = parseInlineObjectLiteral();
1196
+ pattern.type = 'ObjectPattern';
1197
+ if (peek().type === TOKEN.AS) {
1198
+ advance();
1199
+ const dv = parseDefaultValue();
1200
+ if (dv) pattern.defaultValue = dv;
1201
+ }
1202
+ return pattern;
1203
+ }
1204
+ // Regular parameter
1205
+ const name = consume(TOKEN.IDENTIFIER, 'Expected a parameter name.').value;
1206
+ const param = { name };
838
1207
  if (peek().type === TOKEN.AS) {
839
1208
  advance(); // as
840
1209
  const dv = parseDefaultValue();
841
1210
  if (dv) param.defaultValue = dv;
842
1211
  }
843
- params.push(param);
1212
+ return param;
1213
+ }
1214
+
1215
+ params.push(parseParam());
1216
+ while (peek().type === TOKEN.COMMA) {
1217
+ advance();
1218
+ params.push(parseParam());
844
1219
  }
845
1220
  return params;
846
1221
  }
@@ -871,12 +1246,24 @@ function parse(tokens) {
871
1246
  }
872
1247
 
873
1248
  function parseGive() {
874
- consume(TOKEN.GIVE);
1249
+ const isReturn = peek().type === TOKEN.RETURN;
1250
+ const isGiveBack = peek().type === TOKEN.GIVE_BACK;
1251
+ const isGive = peek().type === TOKEN.GIVE;
1252
+ if (isReturn) {
1253
+ consume(TOKEN.RETURN);
1254
+ } else if (isGiveBack) {
1255
+ consume(TOKEN.GIVE_BACK);
1256
+ } else if (isGive && peekAt(1).type === TOKEN.BACK) {
1257
+ consume(TOKEN.GIVE);
1258
+ consume(TOKEN.BACK);
1259
+ } else {
1260
+ consume(TOKEN.GIVE);
1261
+ }
875
1262
  const value = parseExpression();
876
1263
  return { type: 'GiveStatement', value };
877
1264
  }
878
1265
 
879
- // v1.0.0 — generators: `yield <expr>` (optionally bare `yield`).
1266
+ // v1.0.1 — generators: `yield <expr>` (optionally bare `yield`).
880
1267
  function parseYield() {
881
1268
  consume(TOKEN.YIELD);
882
1269
  let value = null;
@@ -886,7 +1273,7 @@ function parse(tokens) {
886
1273
  return { type: 'YieldStatement', value };
887
1274
  }
888
1275
 
889
- // v1.0.0 — record kinds: `define a kind called "Person" with … done`
1276
+ // v1.0.1 — record kinds: `define a kind called "Person" with … done`
890
1277
  // The field block reuses the property-list grammar (`age is 0`), so each
891
1278
  // field gets a default expression just like an object literal.
892
1279
  function parseDefineKind() {
@@ -918,12 +1305,21 @@ function parse(tokens) {
918
1305
  const t = consume(TOKEN.IDENTIFIER, 'Expected a kind name after "kind called".');
919
1306
  name = t.value;
920
1307
  }
1308
+ let extendsKind = null;
1309
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'extends') {
1310
+ advance();
1311
+ if (peek().type === TOKEN.STRING) {
1312
+ extendsKind = advance().value;
1313
+ } else {
1314
+ extendsKind = consume(TOKEN.IDENTIFIER, 'Expected a kind name after "extends".').value;
1315
+ }
1316
+ }
921
1317
  consume(TOKEN.WITH, 'Expected "with" after the kind name.\n\nExample:\n define a kind called "Person" with\n name is ""\n done');
922
1318
  const fields = parsePropertyList('kind "' + name + '" definition');
923
- return { type: 'DefineKindStatement', name, fields };
1319
+ return { type: 'DefineKindStatement', name, fields, extends: extendsKind };
924
1320
  }
925
1321
 
926
- // v1.0.0 — record constructor (expression): `create a Person with name "Ada" and age 17`
1322
+ // v1.0.1 — record constructor (expression): `create a Person with name "Ada" and age 17`
927
1323
  function parseCreateKind() {
928
1324
  advance(); // create
929
1325
  advance(); // a / an
@@ -943,7 +1339,7 @@ function parse(tokens) {
943
1339
  return { type: 'CreateKindExpression', kind, pairs };
944
1340
  }
945
1341
 
946
- // v1.0.0 — native test DSL: `test "name" … done`
1342
+ // v1.0.1 — native test DSL: `test "name" … done`
947
1343
  function parseTestStatement() {
948
1344
  advance(); // test
949
1345
  const name = consume(TOKEN.STRING, 'Expected a test name string after "test".').value;
@@ -951,7 +1347,7 @@ function parse(tokens) {
951
1347
  return { type: 'TestStatement', name, body };
952
1348
  }
953
1349
 
954
- // v1.0.0 — assertions: `check <a> (equals|is|contains|raises) <b>`
1350
+ // v1.0.1 — assertions: `check <a> (equals|is|contains|raises) <b>`
955
1351
  function parseCheckStatement() {
956
1352
  advance(); // check
957
1353
  const a = parseExpression();
@@ -971,8 +1367,53 @@ function parse(tokens) {
971
1367
  // for every <item> in <collection> ... done (alias — "every" maps to EACH token)
972
1368
  function parseForEach() {
973
1369
  consume(TOKEN.FOR);
1370
+
1371
+ // for index <name> from <start> to <end> [by <step>] ... done
1372
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'index') {
1373
+ advance(); // index
1374
+ const name = consume(
1375
+ TOKEN.IDENTIFIER,
1376
+ 'Expected an index name after "for index".\n\nExample:\n for index i from 0 to 9\n show i\n done'
1377
+ ).value;
1378
+ if (peek().type === TOKEN.IN || (peek().type === TOKEN.IDENTIFIER && peek().value === 'in')) {
1379
+ // for index <name> in <collection> — zero-based index over a list.
1380
+ advance(); // in
1381
+ const collection = parseExpression();
1382
+ const body = parseBody('"for index" loop');
1383
+ return { type: 'ForIndexStatement', name, start: null, end: collection, step: null, over: collection, body };
1384
+ }
1385
+ if (peek().type !== TOKEN.IDENTIFIER || peek().value !== 'from') {
1386
+ throw new Error(makeError(
1387
+ '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',
1388
+ peek()
1389
+ ));
1390
+ }
1391
+ advance(); // from
1392
+ const start = parseExpression();
1393
+ if (peek().type === TOKEN.TO || (peek().type === TOKEN.IDENTIFIER && peek().value === 'to')) {
1394
+ advance(); // to
1395
+ } else {
1396
+ throw new Error(makeError(
1397
+ 'Expected "to" between the start and end of a "for index" loop.\n\nExample:\n for index i from 0 to 9',
1398
+ peek()
1399
+ ));
1400
+ }
1401
+ const end = parseExpression();
1402
+ let step = null;
1403
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'by') {
1404
+ advance(); // by
1405
+ step = parseExpression();
1406
+ }
1407
+ const body = parseBody('"for index" loop');
1408
+ return { type: 'ForIndexStatement', name, start, end, step, over: null, body };
1409
+ }
1410
+
974
1411
  consume(TOKEN.EACH,
975
- 'Expected "each" or "every" after "for".\n\nExample:\n for each item in players\n show item\n done');
1412
+ 'Expected "each", "every" or "index" after "for".\n\nExample:\n for each item in players\n show item\n done');
1413
+ // Also accept "every" (TOKEN.EACH with value "every") as an alias for "each"
1414
+ if (peek().type === TOKEN.EACH && peek().value === 'every') {
1415
+ advance(); // consume "every"
1416
+ }
976
1417
  const item = consume(TOKEN.IDENTIFIER, 'Expected an item name after "each" or "every".').value;
977
1418
  consume(TOKEN.IN, `Expected "in" after "${item}".\n\nExample:\n for each item in players`);
978
1419
  const collection = parseExpression();
@@ -988,12 +1429,43 @@ function parse(tokens) {
988
1429
  return { type: 'WhileStatement', condition, body };
989
1430
  }
990
1431
 
991
- // import "./file.ps"
1432
+ // import "./file.pln"
1433
+ // import { name1, name2 } from "./file.pln" (named imports — binds only the
1434
+ // listed symbols; the whole file is still bundled as a dependency)
992
1435
  function parseImport() {
993
1436
  consume(TOKEN.IMPORT);
1437
+
1438
+ // Named-import form: import { a, b } from "./file.pln"
1439
+ if (peek().type === TOKEN.LBRACE) {
1440
+ advance(); // {
1441
+ const names = [];
1442
+ while (true) {
1443
+ names.push(consume(
1444
+ TOKEN.IDENTIFIER,
1445
+ 'Expected an exported name inside the import braces.\n\nExample:\n import { helper } from "./util.pln"'
1446
+ ).value);
1447
+ if (peek().type === TOKEN.COMMA) { advance(); continue; }
1448
+ break;
1449
+ }
1450
+ consume(TOKEN.RBRACE,
1451
+ 'Expected "}" to close the import braces.\n\nExample:\n import { helper } from "./util.pln"');
1452
+ // The "from" is a plain identifier; tolerate its optional presence so
1453
+ // both "import { x } from "./f.pln"" and "import { x } "./f.pln"" read
1454
+ // naturally, but require it for the documented form.
1455
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'from') {
1456
+ advance(); // from
1457
+ }
1458
+ const filePath = consume(
1459
+ TOKEN.STRING,
1460
+ 'Expected a file path string after the import.\n\nExample:\n import { helper } from "./util.pln"'
1461
+ ).value;
1462
+ return { type: 'ImportStatement', path: filePath, names };
1463
+ }
1464
+
1465
+ // Whole-module form: import "./file.pln"
994
1466
  const filePath = consume(
995
1467
  TOKEN.STRING,
996
- 'Expected a file path string after "import".\n\nExample:\n import "./math.ps"'
1468
+ 'Expected a file path string after "import".\n\nExample:\n import "./math.pln"'
997
1469
  ).value;
998
1470
  return { type: 'ImportStatement', path: filePath };
999
1471
  }
@@ -1029,6 +1501,38 @@ function parse(tokens) {
1029
1501
  function parseWhen() {
1030
1502
  consume(TOKEN.WHEN);
1031
1503
 
1504
+ // v2.3 — "when <condition> ... done": English-like if statement.
1505
+ // Detect: when <expr> is ... / when <expr> above ... etc.
1506
+ // Must come after existing "when" event-handler checks.
1507
+ // Check if next token starts a condition (not someone, not "nothing", not socket,
1508
+ // not a string followed by "happens")
1509
+ const nextToken = peek();
1510
+ const isEventWhen =
1511
+ (nextToken.type === TOKEN.STRING && peekAt(1).type === TOKEN.HAPPENS) ||
1512
+ nextToken.type === TOKEN.SOMEONE ||
1513
+ (nextToken.type === TOKEN.IDENTIFIER && (nextToken.value === 'nothing' || nextToken.value === 'socket'));
1514
+
1515
+ if (!isEventWhen) {
1516
+ const condition = parseCondition();
1517
+ // Optional "then" keyword
1518
+ if (peek().type === TOKEN.THEN) {
1519
+ advance(); // consume "then"
1520
+ }
1521
+ const consequent = [];
1522
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1523
+ if (peek().type === TOKEN.EOF) {
1524
+ throw new Error(makeError(
1525
+ 'Expected keyword "done" to close the "when" block before end of file.',
1526
+ peek()
1527
+ ));
1528
+ }
1529
+ const stmt = parseStatement();
1530
+ if (stmt) consequent.push(stmt);
1531
+ }
1532
+ advance(); // consume DONE or TOGETHER
1533
+ return { type: 'IfStatement', condition, consequent, alternate: null };
1534
+ }
1535
+
1032
1536
  // v2.1.1 — "when nothing matches … done" registers the 404 catch-all.
1033
1537
  // It must appear after every route in the source; the generated handler
1034
1538
  // keeps that position.
@@ -1162,20 +1666,36 @@ function parse(tokens) {
1162
1666
  return { type: 'TelegramCallbackStatement', data, body };
1163
1667
  }
1164
1668
 
1165
- // listen on <port> ... done
1669
+ // listen on <port> ... done / start on <port> ... done / serve on <port> ... done
1166
1670
  function parseListen() {
1167
- consume(TOKEN.LISTEN);
1671
+ const isStartOn = peek().type === TOKEN.START_ON;
1672
+ const isServeOn = peek().type === TOKEN.SERVE_ON;
1673
+ if (isStartOn) {
1674
+ consume(TOKEN.START_ON);
1675
+ } else if (isServeOn) {
1676
+ consume(TOKEN.SERVE_ON);
1677
+ } else {
1678
+ consume(TOKEN.LISTEN);
1679
+ }
1168
1680
  consume(TOKEN.ON,
1169
- 'Expected "on" after "listen".\n\nExample:\n listen on 3000\n show "Running"\n done');
1681
+ 'Expected "on" after "listen" / "start on" / "serve on".\n\nExample:\n listen on 3000\n show "Running"\n done');
1170
1682
  const port = parseExpression();
1171
1683
  const body = parseBody('"listen" block');
1172
1684
  return { type: 'ListenStatement', port, body };
1173
1685
  }
1174
1686
 
1175
- // reply <expr>
1176
- // reply json\n <key> is <val>\n...\ndone
1687
+ // reply <expr> / respond <expr> / send back <expr>
1688
+ // reply json\n <key> is <val>\n...\ndone
1177
1689
  function parseReply() {
1178
- consume(TOKEN.REPLY);
1690
+ const isRespond = peek().type === TOKEN.RESPOND;
1691
+ const isSendBack = peek().type === TOKEN.SEND_BACK;
1692
+ if (isRespond) {
1693
+ consume(TOKEN.RESPOND);
1694
+ } else if (isSendBack) {
1695
+ consume(TOKEN.SEND_BACK);
1696
+ } else {
1697
+ consume(TOKEN.REPLY);
1698
+ }
1179
1699
  if (peek().type === TOKEN.JSON_KW) {
1180
1700
  advance(); // consume json
1181
1701
  const properties = [];
@@ -1241,11 +1761,19 @@ function parse(tokens) {
1241
1761
  return rows;
1242
1762
  }
1243
1763
 
1244
- // serve folder "<path>"
1764
+ // serve folder "<path>" / serve static "<path>" / serve public "<path>"
1245
1765
  function parseServeFolder() {
1246
- consume(TOKEN.SERVE);
1766
+ const isStatic = peek().type === TOKEN.SERVE_STATIC;
1767
+ const isPublic = peek().type === TOKEN.SERVE_PUBLIC;
1768
+ if (isStatic) {
1769
+ consume(TOKEN.SERVE_STATIC);
1770
+ } else if (isPublic) {
1771
+ consume(TOKEN.SERVE_PUBLIC);
1772
+ } else {
1773
+ consume(TOKEN.SERVE);
1774
+ }
1247
1775
  consume(TOKEN.FOLDER,
1248
- 'Expected "folder" after "serve".\n\nExample:\n serve folder "public"');
1776
+ 'Expected "folder" after "serve" / "serve static" / "serve public".\n\nExample:\n serve folder "public"');
1249
1777
  const folder = consume(TOKEN.STRING,
1250
1778
  'Expected a folder path string after "serve folder".\n\nExample:\n serve folder "public"').value;
1251
1779
  return { type: 'ServeFolderStatement', folder };
@@ -1303,11 +1831,16 @@ function parse(tokens) {
1303
1831
  return { type: 'ExpressionStatement', expression: { type: 'CallExpression', name: 'bot', args: [token] } };
1304
1832
  }
1305
1833
 
1306
- // start <port>
1834
+ // start <port> / run on <port>
1307
1835
  // start telegram bot — explicit Telegram startup marker. Polling keeps
1308
1836
  // the bot alive, so this form is only for documentation/intent.
1309
1837
  function parseStart() {
1310
- consume(TOKEN.START_KW);
1838
+ const isRunOn = peek().type === TOKEN.RUN_ON;
1839
+ if (isRunOn) {
1840
+ consume(TOKEN.RUN_ON);
1841
+ } else {
1842
+ consume(TOKEN.START_KW);
1843
+ }
1311
1844
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'telegram') {
1312
1845
  advance();
1313
1846
  const botToken = peek();
@@ -1326,7 +1859,7 @@ function parse(tokens) {
1326
1859
 
1327
1860
  // ── v0.6 — SQLite DX ───────────────────────────────────────────────────────
1328
1861
 
1329
- // database "<file>" [using "<driver>"]
1862
+ // database "<file>" [using "<driver>"] / connect database "<file>" [using "<driver>"] / use database "<file>" [using "<driver>"]
1330
1863
  //
1331
1864
  // v2.1.1 — the optional driver selects the SQLite engine without changing
1332
1865
  // any other PlainScript database semantics:
@@ -1335,9 +1868,28 @@ function parse(tokens) {
1335
1868
  // The default ("auto") tries native first and falls back to the wasm
1336
1869
  // engine when the native binding is unavailable on this platform.
1337
1870
  function parseDatabase() {
1338
- consume(TOKEN.DATABASE_KW);
1871
+ const isConnect = peek().type === TOKEN.CONNECT_DB;
1872
+ const isUse = peek().type === TOKEN.USE_DATABASE;
1873
+ let keyword, example;
1874
+ if (isConnect) {
1875
+ keyword = 'connect database';
1876
+ example = 'connect database "app.db"';
1877
+ } else if (isUse) {
1878
+ keyword = 'use database';
1879
+ example = 'use database "app.db"';
1880
+ } else {
1881
+ keyword = 'database';
1882
+ example = 'database "app.db"';
1883
+ }
1884
+ if (isConnect) {
1885
+ consume(TOKEN.CONNECT_DB);
1886
+ } else if (isUse) {
1887
+ consume(TOKEN.USE_DATABASE);
1888
+ } else {
1889
+ consume(TOKEN.DATABASE_KW);
1890
+ }
1339
1891
  const file = consume(TOKEN.STRING,
1340
- 'Expected a database file path after "database".\n\nExample:\n database "app.db"').value;
1892
+ `Expected a database file path after "${keyword}".\n\nExample:\n ${example}`).value;
1341
1893
  let driver = null;
1342
1894
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'using') {
1343
1895
  advance(); // using
@@ -1385,12 +1937,20 @@ function parse(tokens) {
1385
1937
 
1386
1938
  // ── v2.1.1 — error handling, retries and backend middleware ───────────────
1387
1939
 
1388
- // try … [recover [when <err> catches "<ErrorType>"]] … done
1940
+ function isHandledBy() {
1941
+ return peek().type === TOKEN.IDENTIFIER && peek().value === 'handled' &&
1942
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'by';
1943
+ }
1944
+
1945
+ // try … [recover [when <err> catches "<ErrorType>"]] [finally …] … done
1946
+ // also: try … done handled by … done (v2.4 English alternative)
1389
1947
  function parseTryStatement() {
1390
1948
  advance(); // try
1391
1949
  const tryBody = [];
1950
+ // Parse try body - stop at "done", "recover", "finally", or "handled by"
1392
1951
  while (!(peek().type === TOKEN.DONE ||
1393
- (peek().type === TOKEN.IDENTIFIER && peek().value === 'recover'))) {
1952
+ (peek().type === TOKEN.IDENTIFIER && (peek().value === 'recover' || peek().value === 'finally')) ||
1953
+ isHandledBy())) {
1394
1954
  if (peek().type === TOKEN.EOF) {
1395
1955
  throw new Error(makeError(
1396
1956
  'Expected keyword "done" to close the "try" block before end of file.',
@@ -1400,15 +1960,20 @@ function parse(tokens) {
1400
1960
  const stmt = parseStatement();
1401
1961
  if (stmt) tryBody.push(stmt);
1402
1962
  }
1963
+ // Consume the "done" that closes the try body (if present)
1964
+ // "handled by" before done means recover is inline (no done separator)
1965
+ if (peek().type === TOKEN.DONE) {
1966
+ advance(); // consume "done" that closes try body
1967
+ }
1403
1968
  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
- ));
1969
+ // Check for recover/handled-by/finally sections (may be multiple recover blocks)
1970
+ while ((peek().type === TOKEN.IDENTIFIER && peek().value === 'recover') || isHandledBy()) {
1971
+ if (isHandledBy()) {
1972
+ advance(); // handled
1973
+ advance(); // by
1974
+ } else {
1975
+ advance(); // recover
1410
1976
  }
1411
- advance(); // recover
1412
1977
  let paramName = null;
1413
1978
  let errorType = null;
1414
1979
  if (peek().type === TOKEN.AS) {
@@ -1427,7 +1992,8 @@ function parse(tokens) {
1427
1992
  }
1428
1993
  const recoverBody = [];
1429
1994
  while (peek().type !== TOKEN.DONE &&
1430
- !(peek().type === TOKEN.IDENTIFIER && peek().value === 'recover')) {
1995
+ !(peek().type === TOKEN.IDENTIFIER && (peek().value === 'recover' || peek().value === 'finally')) &&
1996
+ !isHandledBy()) {
1431
1997
  if (peek().type === TOKEN.EOF) {
1432
1998
  throw new Error(makeError(
1433
1999
  'Expected keyword "done" to close the "recover" block before end of file.',
@@ -1437,10 +2003,27 @@ function parse(tokens) {
1437
2003
  const stmt = parseStatement();
1438
2004
  if (stmt) recoverBody.push(stmt);
1439
2005
  }
2006
+ advance(); // consume "done" that closes recover body
1440
2007
  catches.push({ param: paramName, errorType, body: recoverBody });
1441
2008
  }
1442
- advance(); // done
1443
- return { type: 'TryStatement', body: tryBody, catches };
2009
+ let finallyBody = null;
2010
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'finally') {
2011
+ advance(); // finally
2012
+ finallyBody = [];
2013
+ while (peek().type !== TOKEN.DONE) {
2014
+ if (peek().type === TOKEN.EOF) {
2015
+ throw new Error(makeError(
2016
+ 'Expected keyword "done" to close the "finally" block before end of file.',
2017
+ peek()
2018
+ ));
2019
+ }
2020
+ const stmt = parseStatement();
2021
+ if (stmt) finallyBody.push(stmt);
2022
+ }
2023
+ advance(); // consume "done" that closes the finally block
2024
+ }
2025
+ // No final "done" advance here — the enclosing parseBody() consumes it
2026
+ return { type: 'TryStatement', body: tryBody, catches, finallyBody };
1444
2027
  }
1445
2028
 
1446
2029
  // retry <n> times [every <n> seconds] … done
@@ -1454,7 +2037,8 @@ function parse(tokens) {
1454
2037
  ));
1455
2038
  }
1456
2039
  const timesToken = peek();
1457
- if (timesToken.type !== TOKEN.IDENTIFIER || timesToken.value !== 'times') {
2040
+ if (!((timesToken.type === TOKEN.IDENTIFIER && timesToken.value === 'times') ||
2041
+ timesToken.type === TOKEN.TIMES_WORD)) {
1458
2042
  throw new Error(makeError(
1459
2043
  'Expected "times" after the number of retries.\n\nExample:\n retry 3 times',
1460
2044
  timesToken
@@ -1511,16 +2095,25 @@ function parse(tokens) {
1511
2095
  }
1512
2096
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'allow' && mimes === null) {
1513
2097
  advance(); // allow
1514
- const list = parseArrayLiteral();
1515
- for (const element of list.elements) {
2098
+ let elements;
2099
+ // v2.4 — accept "list with" as alternative to bracket syntax
2100
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'list' &&
2101
+ peekAt(1).type === TOKEN.WITH) {
2102
+ advance(); // "list"
2103
+ advance(); // "with"
2104
+ elements = parseListWithElements();
2105
+ } else {
2106
+ elements = parseArrayLiteral().elements;
2107
+ }
2108
+ for (const element of elements) {
1516
2109
  if (element.type !== 'StringLiteral') {
1517
2110
  throw new Error(makeError(
1518
- 'MIME types in "accept uploads allow [...]" must be strings.\n\nExample:\n accept uploads allow ["image/png", "image/jpeg"]',
2111
+ 'MIME types in "accept uploads allow" must be strings.\n\nExample:\n accept uploads allow list with "image/png", "image/jpeg"',
1519
2112
  peek()
1520
2113
  ));
1521
2114
  }
1522
2115
  }
1523
- mimes = list.elements.map(element => element.value);
2116
+ mimes = elements.map(element => element.value);
1524
2117
  continue;
1525
2118
  }
1526
2119
  // ("folder" lexes as the FOLDER keyword, so both token shapes count.)
@@ -1570,7 +2163,7 @@ function parse(tokens) {
1570
2163
  const name = consume(TOKEN.STRING,
1571
2164
  'Expected a cookie name string after "set cookie".\n\nExample:\n set cookie "theme" to "dark"').value;
1572
2165
  const toToken = peek();
1573
- if (toToken.type !== TOKEN.IDENTIFIER || toToken.value !== 'to') {
2166
+ if (toToken.type !== TOKEN.IDENTIFIER && toToken.type !== TOKEN.TO) {
1574
2167
  throw new Error(makeError(
1575
2168
  'Expected "to" after the cookie name.\n\nExample:\n set cookie "theme" to "dark"',
1576
2169
  toToken
@@ -1615,7 +2208,7 @@ function parse(tokens) {
1615
2208
  advance(); // limit
1616
2209
  advance(); // requests
1617
2210
  const toToken = peek();
1618
- if (toToken.type !== TOKEN.IDENTIFIER || toToken.value !== 'to') {
2211
+ if (toToken.type !== TOKEN.IDENTIFIER && toToken.type !== TOKEN.TO) {
1619
2212
  throw new Error(makeError(
1620
2213
  'Expected "to" after "limit requests".\n\nExample:\n limit requests to 100 per minute',
1621
2214
  toToken
@@ -1655,7 +2248,7 @@ function parse(tokens) {
1655
2248
  const condition = parseCondition();
1656
2249
 
1657
2250
  const consequent = [];
1658
- while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE) {
2251
+ while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1659
2252
  if (peek().type === TOKEN.EOF) {
1660
2253
  throw new Error(makeError(
1661
2254
  'Expected keyword "done" before end of file to close the "if" block.',
@@ -1677,7 +2270,7 @@ function parse(tokens) {
1677
2270
  alternate = [parseElseIfChain()];
1678
2271
  } else {
1679
2272
  alternate = [];
1680
- while (peek().type !== TOKEN.DONE) {
2273
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1681
2274
  if (peek().type === TOKEN.EOF) {
1682
2275
  throw new Error(makeError(
1683
2276
  'Expected keyword "done" before end of file to close the "otherwise" block.',
@@ -1690,7 +2283,7 @@ function parse(tokens) {
1690
2283
  }
1691
2284
  }
1692
2285
 
1693
- advance(); // consume DONE
2286
+ advance(); // consume DONE or TOGETHER
1694
2287
  return { type: 'IfStatement', condition, consequent, alternate };
1695
2288
  }
1696
2289
 
@@ -1703,7 +2296,7 @@ function parse(tokens) {
1703
2296
  const condition = parseCondition();
1704
2297
 
1705
2298
  const consequent = [];
1706
- while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE) {
2299
+ while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1707
2300
  if (peek().type === TOKEN.EOF) {
1708
2301
  throw new Error(makeError(
1709
2302
  'Expected keyword "done" before end of file to close the "otherwise if" block.',
@@ -1722,7 +2315,7 @@ function parse(tokens) {
1722
2315
  alternate = [parseElseIfChain()];
1723
2316
  } else {
1724
2317
  alternate = [];
1725
- while (peek().type !== TOKEN.DONE) {
2318
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1726
2319
  if (peek().type === TOKEN.EOF) {
1727
2320
  throw new Error(makeError(
1728
2321
  'Expected keyword "done" before end of file to close the "otherwise" block.',
@@ -1742,7 +2335,7 @@ function parse(tokens) {
1742
2335
 
1743
2336
  function parseBody(context) {
1744
2337
  const body = [];
1745
- while (peek().type !== TOKEN.DONE) {
2338
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.TOGETHER) {
1746
2339
  if (peek().type === TOKEN.EOF) {
1747
2340
  throw new Error(makeError(
1748
2341
  `Expected keyword "done" to close the ${context} before end of file.`,
@@ -1752,37 +2345,83 @@ function parse(tokens) {
1752
2345
  const stmt = parseStatement();
1753
2346
  if (stmt) body.push(stmt);
1754
2347
  }
1755
- advance(); // consume DONE
2348
+ advance(); // consume DONE or TOGETHER
1756
2349
  return body;
1757
2350
  }
1758
2351
 
1759
2352
  // ── Expressions ────────────────────────────────────────────────────────────
1760
2353
 
1761
2354
  // v2.1.1 — full arithmetic precedence:
2355
+ // nullish := additive ("??" additive)*
1762
2356
  // additive := term (("+" | "-") term)*
1763
- // multiplicative ("term") := unary (("*" | "/" | "%") unary)*
2357
+ // multiplicative ("term") := power (("*" | "/" | "%") power)*
2358
+ // power := unary ("**" power)*
1764
2359
  // unary := "-" unary | "wait for" unary | primary
1765
- // primary := atom with postfix chains (indexing, members, of, length)
2360
+ // primary := atom with postfix chains (indexing, members, of, length, optional chaining)
1766
2361
  function parseExpression() {
2362
+ if (peek().type === TOKEN.CHOOSING) {
2363
+ advance();
2364
+ const condition = parseCondition();
2365
+ if (peek().type === TOKEN.THEN) advance();
2366
+ const consequent = parseExpression();
2367
+ if (peek().type === TOKEN.OTHERWISE) advance();
2368
+ const alternate = parseExpression();
2369
+ return { type: 'ConditionalExpression', condition, consequent, alternate };
2370
+ }
2371
+ let left = parseNullish();
2372
+ return left;
2373
+ }
2374
+
2375
+ function parseNullish() {
2376
+ let left = parseAdditive();
2377
+ while (peek().type === TOKEN.NULLISH_COALESCE) {
2378
+ advance();
2379
+ const right = parseAdditive();
2380
+ left = { type: 'NullishCoalesceExpression', left, right };
2381
+ }
2382
+ return left;
2383
+ }
2384
+
2385
+ function parseAdditive() {
1767
2386
  let left = parseTerm();
1768
- while (peek().type === TOKEN.PLUS || peek().type === TOKEN.MINUS) {
1769
- const operator = advance().value;
2387
+ while (peek().type === TOKEN.PLUS || peek().type === TOKEN.MINUS ||
2388
+ peek().type === TOKEN.PLUS_WORD || peek().type === TOKEN.MINUS_WORD) {
2389
+ const opToken = advance();
2390
+ const op = opToken.type === TOKEN.PLUS_WORD ? '+' :
2391
+ opToken.type === TOKEN.MINUS_WORD ? '-' :
2392
+ opToken.value;
1770
2393
  const right = parseTerm();
1771
- left = { type: 'BinaryExpression', operator, left, right };
2394
+ left = { type: 'BinaryExpression', operator: op, left, right };
1772
2395
  }
1773
2396
  return left;
1774
2397
  }
1775
2398
 
1776
2399
  function parseTerm() {
1777
- let left = parseUnary();
2400
+ let left = parsePower();
1778
2401
  while (
1779
2402
  peek().type === TOKEN.STAR ||
1780
2403
  peek().type === TOKEN.SLASH ||
1781
- peek().type === TOKEN.PERCENT
2404
+ peek().type === TOKEN.PERCENT ||
2405
+ peek().type === TOKEN.TIMES_WORD ||
2406
+ peek().type === TOKEN.DIVIDED_BY_WORD
1782
2407
  ) {
1783
- const operator = advance().value;
1784
- const right = parseUnary();
1785
- left = { type: 'BinaryExpression', operator, left, right };
2408
+ const opToken = advance();
2409
+ const op = opToken.type === TOKEN.TIMES_WORD ? '*' :
2410
+ opToken.type === TOKEN.DIVIDED_BY_WORD ? '/' :
2411
+ opToken.value;
2412
+ const right = parsePower();
2413
+ left = { type: 'BinaryExpression', operator: op, left, right };
2414
+ }
2415
+ return left;
2416
+ }
2417
+
2418
+ // Exponentiation is right-associative: 2 ** 3 ** 2 = 2 ** (3 ** 2) = 512
2419
+ function parsePower() {
2420
+ let left = parseUnary();
2421
+ if (peek().type === TOKEN.POWER) {
2422
+ advance();
2423
+ const right = parsePower(); // right-associative
2424
+ left = { type: 'BinaryExpression', operator: '**', left, right };
1786
2425
  }
1787
2426
  return left;
1788
2427
  }
@@ -1792,6 +2431,16 @@ function parse(tokens) {
1792
2431
  advance();
1793
2432
  return { type: 'UnaryExpression', operator: '-', operand: parseUnary() };
1794
2433
  }
2434
+ // Spread operator (...) - used for array/object spreading
2435
+ if (peek().type === TOKEN.SPREAD) {
2436
+ advance();
2437
+ return { type: 'SpreadExpression', argument: parseUnary() };
2438
+ }
2439
+ // await expression (native, in addition to "wait for")
2440
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'await') {
2441
+ advance();
2442
+ return { type: 'AwaitExpression', value: parseUnary() };
2443
+ }
1795
2444
  // v2.1.1 — await semantics: "wait for <value>" awaits an async operation.
1796
2445
  // The operand binds tightly (a full postfix chain), so
1797
2446
  // "wait for loadUser(id) + 1" means "(await loadUser(id)) + 1".
@@ -1802,12 +2451,37 @@ function parse(tokens) {
1802
2451
  advance(); // for
1803
2452
  return { type: 'AwaitExpression', value: parseUnary() };
1804
2453
  }
2454
+ // typeof operator
2455
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'typeof') {
2456
+ advance();
2457
+ return { type: 'UnaryExpression', operator: 'typeof', operand: parseUnary() };
2458
+ }
2459
+ // void operator
2460
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'void') {
2461
+ advance();
2462
+ return { type: 'UnaryExpression', operator: 'void', operand: parseUnary() };
2463
+ }
2464
+ // delete operator
2465
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'delete') {
2466
+ advance();
2467
+ return { type: 'UnaryExpression', operator: 'delete', operand: parseUnary() };
2468
+ }
1805
2469
  return parsePrimary();
1806
2470
  }
1807
2471
 
1808
2472
  // primary → itemExpr | atom (postfix)*
1809
2473
  function parsePrimary() {
1810
- // v1.0.0 — record constructor: `create a Person with name "Ada" and age 17`.
2474
+ // v2.4 — "record with" and "list with" as expressions (contextual)
2475
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'record' &&
2476
+ peekAt(1).type === TOKEN.WITH) {
2477
+ return parseRecordWith(true);
2478
+ }
2479
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'list' &&
2480
+ peekAt(1).type === TOKEN.WITH) {
2481
+ return parseListWith();
2482
+ }
2483
+
2484
+ // v1.0.1 — record constructor: `create a Person with name "Ada" and age 17`.
1811
2485
  // `create` then an article ("a"/"an") then a kind name then "with" pairs.
1812
2486
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'create') {
1813
2487
  const a1 = peekAt(1);
@@ -1821,7 +2495,7 @@ function parse(tokens) {
1821
2495
  }
1822
2496
  }
1823
2497
 
1824
- // v1.0.0 — concurrency combinators: `all of [a(), b()]`, `any of [...]`,
2498
+ // v1.0.1 — concurrency combinators: `all of [a(), b()]`, `any of [...]`,
1825
2499
  // `settled of [...]`. Guard on the identifier + "of" lookahead so plain
1826
2500
  // property reads like `all of the_list` still work as well as prose.
1827
2501
  if (peek().type === TOKEN.IDENTIFIER &&
@@ -1833,7 +2507,7 @@ function parse(tokens) {
1833
2507
  return { type: 'ConcurrencyExpression', combo: comboKw, items };
1834
2508
  }
1835
2509
 
1836
- // v1.0.0 — `spread of <collection>` unfolds an iterable into a new array.
2510
+ // v1.0.1 — `spread of <collection>` unfolds an iterable into a new array.
1837
2511
  if (peek().type === TOKEN.IDENTIFIER && peek().value === 'spread' &&
1838
2512
  peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'of') {
1839
2513
  advance(); // spread
@@ -1853,8 +2527,54 @@ function parse(tokens) {
1853
2527
  node = { type: 'IndexExpression', object: node, index };
1854
2528
  } else if (peek().type === TOKEN.DOT) {
1855
2529
  advance();
1856
- const property = consume(TOKEN.IDENTIFIER, 'Expected a property name after ".".').value;
2530
+ // After ".", any word is a valid JS property/method name — including
2531
+ // words that are PlainScript keywords in other contexts (e.g. crypto
2532
+ // .update(...), obj .delete()). So accept any word token, not just an
2533
+ // identifier.
2534
+ const propToken = peek();
2535
+ if (propToken.type === TOKEN.EOF || !/^[A-Za-z_$]/.test(propToken.value)) {
2536
+ throw new Error(makeError('Expected a property name after ".".', propToken));
2537
+ }
2538
+ advance();
2539
+ const property = propToken.value;
1857
2540
  node = { type: 'MemberExpression', object: node, property };
2541
+ // Method call: object.method(args). Only member access may introduce
2542
+ // a call here; plain `name(args)` is handled in parseAtom.
2543
+ if (peek().type === TOKEN.LPAREN) {
2544
+ advance(); // (
2545
+ const { separator, args } = parseArgList();
2546
+ consume(TOKEN.RPAREN, 'Expected ")" to close the method call.');
2547
+ if (separator) {
2548
+ throw new Error(makeError(
2549
+ 'Method calls cannot use "to"/"from" arguments.\n\nExample:\n mrz.parse(line)',
2550
+ peek()
2551
+ ));
2552
+ }
2553
+ node = { type: 'CallExpression', callee: node, args };
2554
+ }
2555
+ } else if (peek().type === TOKEN.OPTIONAL_CHAIN) {
2556
+ // Optional chaining: obj?.prop or obj?.method()
2557
+ advance(); // consume ?.
2558
+ const propToken = peek();
2559
+ if (propToken.type === TOKEN.EOF || !/^[A-Za-z_$]/.test(propToken.value)) {
2560
+ throw new Error(makeError('Expected a property name after "?.".', propToken));
2561
+ }
2562
+ advance();
2563
+ const property = propToken.value;
2564
+ node = { type: 'OptionalChainExpression', object: node, property };
2565
+ // Optional method call: obj?.method()
2566
+ if (peek().type === TOKEN.LPAREN) {
2567
+ advance(); // (
2568
+ const { separator, args } = parseArgList();
2569
+ consume(TOKEN.RPAREN, 'Expected ")" to close the method call.');
2570
+ if (separator) {
2571
+ throw new Error(makeError(
2572
+ 'Method calls cannot use "to"/"from" arguments.\n\nExample:\n obj?.method()',
2573
+ peek()
2574
+ ));
2575
+ }
2576
+ node = { type: 'OptionalCallExpression', callee: node, args };
2577
+ }
1858
2578
  } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') {
1859
2579
  if (node.type !== 'Identifier') {
1860
2580
  throw new Error(makeError(
@@ -1868,6 +2588,11 @@ function parse(tokens) {
1868
2588
  } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'length') {
1869
2589
  advance();
1870
2590
  node = { type: 'LengthExpression', object: node };
2591
+ } else if (peek().type === TOKEN.AT && peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'position') {
2592
+ advance(); // at
2593
+ advance(); // position
2594
+ const idx = consume(TOKEN.NUMBER, 'Expected a number after "at position".').value;
2595
+ node = { type: 'IndexExpression', object: node, index: { type: 'NumberLiteral', value: idx } };
1871
2596
  } else {
1872
2597
  break;
1873
2598
  }
@@ -1888,6 +2613,9 @@ function parse(tokens) {
1888
2613
  if (second.type !== TOKEN.IDENTIFIER) return null;
1889
2614
  if (third.type !== TOKEN.IDENTIFIER) return null;
1890
2615
 
2616
+ // v2.4 — skip "different from" which is a comparison, not an item expression
2617
+ if (second.value === 'different' && third.value === 'from') return null;
2618
+
1891
2619
  // "first from players" / "last from players" — missing noun
1892
2620
  if ((first.value === 'first' || first.value === 'last') && second.value === 'from') {
1893
2621
  throw new Error(makeError(
@@ -1929,7 +2657,7 @@ function parse(tokens) {
1929
2657
  ));
1930
2658
  }
1931
2659
 
1932
- // atom → STRING | NUMBER | true | false | null | '(' expr ')' |
2660
+ // atom → STRING | NUMBER | true | false | null | undefined | BigInt | '(' expr ')' |
1933
2661
  // '[' ... ']' | '{' ... '}' | httpCall | IDENTIFIER '(' args ')' | IDENTIFIER
1934
2662
  function parseAtom() {
1935
2663
  const token = peek();
@@ -1937,10 +2665,30 @@ function parse(tokens) {
1937
2665
  if (token.type === TOKEN.STRING) { advance(); return { type: 'StringLiteral', value: token.value }; }
1938
2666
  if (token.type === TOKEN.TEMPLATE_STRING) { advance(); return { type: 'TemplateLiteral', value: token.value }; }
1939
2667
  if (token.type === TOKEN.NUMBER) { advance(); return { type: 'NumberLiteral', value: token.value }; }
2668
+ if (token.type === TOKEN.BIGINT) { advance(); return { type: 'BigIntLiteral', value: token.value }; }
1940
2669
  // v2.1.1 — boolean and null literals
1941
2670
  if (token.type === TOKEN.TRUE_KW) { advance(); return { type: 'BooleanLiteral', value: true }; }
1942
2671
  if (token.type === TOKEN.FALSE_KW) { advance(); return { type: 'BooleanLiteral', value: false }; }
1943
2672
  if (token.type === TOKEN.NULL_KW) { advance(); return { type: 'NullLiteral' }; }
2673
+ if (token.type === TOKEN.UNDEFINED_KW) { advance(); return { type: 'UndefinedLiteral' }; }
2674
+ // symbol keyword - parse as Symbol() call
2675
+ if (token.type === TOKEN.SYMBOL_KW) {
2676
+ advance();
2677
+ if (peek().type === TOKEN.LPAREN) {
2678
+ advance(); // consume (
2679
+ const { separator, args } = parseArgList();
2680
+ consume(TOKEN.RPAREN, 'Expected ")" to close the symbol call.');
2681
+ if (separator) {
2682
+ throw new Error(makeError(
2683
+ 'Symbol calls cannot use "to"/"from" arguments.\n\nExample:\n symbol("desc")',
2684
+ peek()
2685
+ ));
2686
+ }
2687
+ return { type: 'CallExpression', name: 'Symbol', args };
2688
+ }
2689
+ // Bare symbol keyword - treat as Symbol() with no args
2690
+ return { type: 'CallExpression', name: 'Symbol', args: [] };
2691
+ }
1944
2692
  // v2.1.1 — parenthesised grouping: (a + b) * c
1945
2693
  if (token.type === TOKEN.LPAREN) {
1946
2694
  advance();
@@ -1960,8 +2708,46 @@ function parse(tokens) {
1960
2708
  return parseHttpCall(httpMethod);
1961
2709
  }
1962
2710
 
1963
- if (token.type === TOKEN.IDENTIFIER) {
2711
+ // Handle import.meta (IMPORT token followed by .meta)
2712
+ if (token.type === TOKEN.IMPORT && peekAt(1).type === TOKEN.DOT && peekAt(2).type === TOKEN.IDENTIFIER && peekAt(2).value === 'meta') {
2713
+ advance(); // import
2714
+ advance(); // .
2715
+ advance(); // meta
2716
+ return { type: 'ImportMetaExpression' };
2717
+ }
2718
+
2719
+ if (token.type === TOKEN.IDENTIFIER || token.type === TOKEN.BACK) {
2720
+ if (peekAt(1).type === TOKEN.USES || peekAt(1).type === TOKEN.FILLS) {
2721
+ const callee = { type: 'Identifier', name: token.value };
2722
+ advance();
2723
+ advance(); // uses/fills
2724
+ const args = [];
2725
+ while (peek().type !== TOKEN.TOGETHER && peek().type !== TOKEN.DONE && peek().type !== TOKEN.EOF) {
2726
+ if (peek().type === TOKEN.COMMA) { advance(); continue; }
2727
+ args.push(parseExpression());
2728
+ }
2729
+ if (peek().type === TOKEN.TOGETHER) advance();
2730
+ return { type: 'CallExpression', callee, args };
2731
+ }
1964
2732
  if (peekAt(1).type === TOKEN.LPAREN) return parseCallExpression();
2733
+ // Handle 'this' and 'super' as special identifiers
2734
+ if (token.value === 'this') {
2735
+ advance();
2736
+ return { type: 'ThisExpression' };
2737
+ }
2738
+ if (token.value === 'super') {
2739
+ advance();
2740
+ // super.property or super(args)
2741
+ if (peek().type === TOKEN.DOT) {
2742
+ advance(); // .
2743
+ const prop = consume(TOKEN.IDENTIFIER, 'Expected property name after "super."').value;
2744
+ return { type: 'SuperProperty', property: prop };
2745
+ }
2746
+ if (peek().type === TOKEN.LPAREN) {
2747
+ return parseCallExpression(); // super() call
2748
+ }
2749
+ return { type: 'SuperExpression' };
2750
+ }
1965
2751
  advance();
1966
2752
  return { type: 'Identifier', name: token.value };
1967
2753
  }
@@ -2046,7 +2832,13 @@ function parse(tokens) {
2046
2832
  if (peek().type === TOKEN.EOF) {
2047
2833
  throw new Error(makeError('Expected "]" to close the array before end of file.', peek()));
2048
2834
  }
2049
- elements.push(parseExpression());
2835
+ // Support spread elements: [...arr, ...other]
2836
+ if (peek().type === TOKEN.SPREAD) {
2837
+ advance();
2838
+ elements.push({ type: 'SpreadElement', argument: parseExpression() });
2839
+ } else {
2840
+ elements.push(parseExpression());
2841
+ }
2050
2842
  if (peek().type === TOKEN.COMMA) advance();
2051
2843
  }
2052
2844
  consume(TOKEN.RBRACKET, 'Expected "]" to close the array.');
@@ -2054,7 +2846,8 @@ function parse(tokens) {
2054
2846
  }
2055
2847
 
2056
2848
  // v1.2 — Inline object literal: { key: value, ... }
2057
- function parseInlineObjectLiteral() {
2849
+ // If `isPattern` is true, allows shorthand { x, y } for destructuring
2850
+ function parseInlineObjectLiteral(isPattern) {
2058
2851
  consume(TOKEN.LBRACE);
2059
2852
  const properties = [];
2060
2853
  while (peek().type !== TOKEN.RBRACE) {
@@ -2064,8 +2857,16 @@ function parse(tokens) {
2064
2857
  peek()
2065
2858
  ));
2066
2859
  }
2860
+ // Support spread properties: { ...obj, key: value }
2861
+ if (peek().type === TOKEN.SPREAD) {
2862
+ advance();
2863
+ properties.push({ type: 'SpreadProperty', argument: parseExpression() });
2864
+ if (peek().type === TOKEN.COMMA) advance();
2865
+ continue;
2866
+ }
2067
2867
  const keyToken = peek();
2068
- if (keyToken.type !== TOKEN.IDENTIFIER && keyToken.type !== TOKEN.STRING) {
2868
+ // Allow keywords that are valid JS identifiers as property names (e.g., "back" from "give back")
2869
+ if (keyToken.type !== TOKEN.IDENTIFIER && keyToken.type !== TOKEN.STRING && keyToken.type !== TOKEN.BACK) {
2069
2870
  throw new Error(makeError(
2070
2871
  'Expected a property name inside the inline object.\n\nExample:\n { text: "hi" }',
2071
2872
  keyToken
@@ -2073,8 +2874,15 @@ function parse(tokens) {
2073
2874
  }
2074
2875
  advance();
2075
2876
  const key = keyToken.value;
2076
- consume(TOKEN.COLON, `Expected ":" after property name "${key}".\n\nExample:\n { ${key}: "hi" }`);
2077
- const value = parseExpression();
2877
+ let value = null;
2878
+ if (!isPattern && peek().type === TOKEN.COLON) {
2879
+ consume(TOKEN.COLON, `Expected ":" after property name "${key}".\n\nExample:\n { ${key}: "hi" }`);
2880
+ value = parseExpression();
2881
+ } else if (isPattern && peek().type === TOKEN.COLON) {
2882
+ // Allow explicit key: value in patterns too
2883
+ consume(TOKEN.COLON, `Expected ":" after property name "${key}".\n\nExample:\n { ${key}: "hi" }`);
2884
+ value = parseExpression();
2885
+ }
2078
2886
  properties.push({ key, value });
2079
2887
  if (peek().type === TOKEN.COMMA) advance();
2080
2888
  }
@@ -2092,8 +2900,19 @@ function parse(tokens) {
2092
2900
  peek()
2093
2901
  ));
2094
2902
  }
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"`);
2903
+ // Allow "back" (TOKEN.BACK) as a property name (it's a keyword for "give back" but valid in object literals)
2904
+ let key;
2905
+ if (peek().type === TOKEN.BACK) {
2906
+ key = advance().value;
2907
+ } else {
2908
+ key = consume(TOKEN.IDENTIFIER, 'Expected a property name.').value;
2909
+ }
2910
+ // Accept both "is" and "be" as the property separator
2911
+ if (peek().type === TOKEN.BE) {
2912
+ advance(); // consume "be"
2913
+ } else {
2914
+ consume(TOKEN.IS, `Expected "is" after property name "${key}".\n\nExample:\n name is "Ayokunle"`);
2915
+ }
2097
2916
  const value = parseExpression();
2098
2917
  properties.push({ key, value });
2099
2918
  }
@@ -2112,7 +2931,19 @@ function parse(tokens) {
2112
2931
  peek()
2113
2932
  ));
2114
2933
  }
2115
- const key = consume(TOKEN.IDENTIFIER, 'Expected a property name.').value;
2934
+ // v2.4 — accept keyword tokens as property names (e.g., "to" in mail transport)
2935
+ const keyToken = peek();
2936
+ if (keyToken.type === TOKEN.IDENTIFIER || keyToken.type === TOKEN.TO ||
2937
+ keyToken.type === TOKEN.FROM || keyToken.type === TOKEN.AND ||
2938
+ keyToken.type === TOKEN.OR || keyToken.type === TOKEN.NOT ||
2939
+ keyToken.type === TOKEN.IN || keyToken.type === TOKEN.WITH ||
2940
+ keyToken.type === TOKEN.AS || keyToken.type === TOKEN.IF ||
2941
+ keyToken.type === TOKEN.OTHERWISE) {
2942
+ advance();
2943
+ } else {
2944
+ throw new Error(makeError('Expected a property name.', keyToken));
2945
+ }
2946
+ const key = keyToken.value;
2116
2947
  consume(TOKEN.IS, `Expected "is" after property name "${key}".\n\nExample:\n ${key} is "value"`);
2117
2948
  const value = parseExpression();
2118
2949
  properties.push({ key, value });
@@ -2561,9 +3392,10 @@ function parse(tokens) {
2561
3392
  args.push(parseExpression());
2562
3393
  }
2563
3394
  // 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;
3395
+ if (args.length === 1 && (
3396
+ (peek().type === TOKEN.IDENTIFIER && (peek().value === 'to' || peek().value === 'from')) ||
3397
+ peek().type === TOKEN.TO)) {
3398
+ separator = peek().value === 'to' ? 'to' : peek().value;
2567
3399
  advance();
2568
3400
  if (peek().type === TOKEN.EOF) {
2569
3401
  throw new Error(makeError(`Expected a value after "${separator}".`, peek()));
@@ -2590,6 +3422,94 @@ function parse(tokens) {
2590
3422
  ));
2591
3423
  }
2592
3424
 
3425
+ // switch <expr> against ... done
3426
+ function parseSwitchStatement() {
3427
+ advance(); // switch
3428
+ const discriminant = parseExpression();
3429
+ 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');
3430
+ const cases = [];
3431
+ let defaultCase = null;
3432
+ while (peek().type !== TOKEN.DONE) {
3433
+ if (peek().type === TOKEN.EOF) {
3434
+ throw new Error(makeError(
3435
+ 'Expected keyword "done" to close the "switch" block before end of file.',
3436
+ peek()
3437
+ ));
3438
+ }
3439
+ // otherwise → body
3440
+ if (peek().type === TOKEN.OTHERWISE) {
3441
+ advance(); // otherwise
3442
+ consume(TOKEN.ARROW, 'Expected "->" after "otherwise".\n\nExample:\n otherwise → show "other"');
3443
+ defaultCase = [];
3444
+ while (peek().type !== TOKEN.DONE) {
3445
+ if (peek().type === TOKEN.EOF) {
3446
+ throw new Error(makeError(
3447
+ 'Expected keyword "done" to close the "switch" block before end of file.',
3448
+ peek()
3449
+ ));
3450
+ }
3451
+ const stmt = parseStatement();
3452
+ if (stmt) defaultCase.push(stmt);
3453
+ }
3454
+ break;
3455
+ }
3456
+ const test = parseExpression();
3457
+ consume(TOKEN.ARROW, 'Expected "->" after the case expression.\n\nExample:\n "red" → show "stop"');
3458
+ const caseBody = [];
3459
+ while (peek().type !== TOKEN.DONE && peek().type !== TOKEN.OTHERWISE &&
3460
+ !(peek().type === TOKEN.STRING || peek().type === TOKEN.NUMBER ||
3461
+ peek().type === TOKEN.TRUE_KW || peek().type === TOKEN.FALSE_KW ||
3462
+ peek().type === TOKEN.NULL_KW)) {
3463
+ if (peek().type === TOKEN.EOF) {
3464
+ throw new Error(makeError(
3465
+ 'Expected keyword "done" to close the "switch" block before end of file.',
3466
+ peek()
3467
+ ));
3468
+ }
3469
+ const stmt = parseStatement();
3470
+ if (stmt) caseBody.push(stmt);
3471
+ }
3472
+ cases.push({ test, body: caseBody });
3473
+ }
3474
+ advance(); // done
3475
+ return { type: 'SwitchStatement', discriminant, cases, defaultCase };
3476
+ }
3477
+
3478
+ // class Name { ... }
3479
+ function parseClassDeclaration() {
3480
+ advance(); // class
3481
+ const name = consume(TOKEN.IDENTIFIER, 'Expected a class name after "class".').value;
3482
+ let superClass = null;
3483
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'extends') {
3484
+ advance();
3485
+ superClass = parseExpression();
3486
+ }
3487
+ // Class body: methods and properties
3488
+ // For now, we'll use a simplified approach - class body is a block of statements
3489
+ // In JavaScript, class body contains method definitions
3490
+ consume(TOKEN.LBRACE, 'Expected "{" after class name.');
3491
+ const body = [];
3492
+ while (peek().type !== TOKEN.RBRACE && peek().type !== TOKEN.EOF) {
3493
+ const stmt = parseStatement();
3494
+ if (stmt) body.push(stmt);
3495
+ }
3496
+ consume(TOKEN.RBRACE, 'Expected "}" to close the class body.');
3497
+ return { type: 'ClassDeclaration', name, superClass, body };
3498
+ }
3499
+
3500
+ // new ClassName(args)
3501
+ function parseNewExpression() {
3502
+ advance(); // new
3503
+ const callee = parsePrimary();
3504
+ if (peek().type === TOKEN.LPAREN) {
3505
+ advance(); // (
3506
+ const { separator, args } = parseArgList();
3507
+ consume(TOKEN.RPAREN, 'Expected ")" to close the constructor call.');
3508
+ return { type: 'NewExpression', callee, args };
3509
+ }
3510
+ return { type: 'NewExpression', callee, args: [] };
3511
+ }
3512
+
2593
3513
  // ── Program ────────────────────────────────────────────────────────────────
2594
3514
 
2595
3515
  const body = [];