plainscript-lang 1.0.362 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +394 -54
  2. package/compiler/bundler.js +78 -3
  3. package/compiler/cli.js +239 -30
  4. package/compiler/formatter.js +21 -1
  5. package/compiler/generator.js +453 -107
  6. package/compiler/ir.js +62 -0
  7. package/compiler/lexer.js +42 -7
  8. package/compiler/lsp.js +290 -0
  9. package/compiler/parser.js +820 -113
  10. package/compiler/type-checker.js +440 -0
  11. package/compiler/version.js +1 -1
  12. package/docs/CAPABILITY_GAP_AUDIT.md +19 -3
  13. package/docs/GAME-PROMPT.md +3 -3
  14. package/docs/PLAINSCRIPT-GRAMMAR.md +317 -0
  15. package/docs/PLAINSCRIPT-SPEC.md +264 -5
  16. package/docs/V1.1-TYPED-COLLECTIONS-DESIGN.md +220 -0
  17. package/docs/index.html +5 -5
  18. package/docs/website/script.js +1 -1
  19. package/examples/ai-memory-cli.pln +221 -0
  20. package/examples/ai-memory.json +1 -0
  21. package/examples/ai-providers.pln +1 -1
  22. package/examples/arrays.pln +1 -1
  23. package/examples/async-errors.pln +1 -1
  24. package/examples/auth-api.pln +1 -1
  25. package/examples/auth-sessions.pln +1 -1
  26. package/examples/basics.pln +1 -1
  27. package/examples/bots.pln +1 -1
  28. package/examples/browser-interactive/README.md +1 -1
  29. package/examples/browser-interactive/src/interactive.pln +1 -1
  30. package/examples/cache-and-jobs.pln +1 -1
  31. package/examples/cache-schedule.pln +1 -1
  32. package/examples/canvas-game/README.md +1 -1
  33. package/examples/canvas-game/src/game.pln +1 -1
  34. package/examples/collections.pln +1 -1
  35. package/examples/compound-assignments.pln +24 -0
  36. package/examples/concurrency.pln +2 -2
  37. package/examples/conditions.pln +1 -1
  38. package/examples/database.pln +1 -1
  39. package/examples/day2.pln +1 -1
  40. package/examples/day3.pln +1 -1
  41. package/examples/deployment.pln +1 -1
  42. package/examples/email-send.pln +1 -1
  43. package/examples/error-handling.pln +1 -1
  44. package/examples/expressions.pln +1 -1
  45. package/examples/file-manager-cli.pln +51 -0
  46. package/examples/file-uploads.pln +1 -1
  47. package/examples/files-and-config.pln +1 -1
  48. package/examples/files.pln +1 -1
  49. package/examples/football-backend/app.pln +1 -1
  50. package/examples/functions.pln +1 -1
  51. package/examples/hello.pln +1 -1
  52. package/examples/http-client.pln +1 -1
  53. package/examples/http.pln +1 -1
  54. package/examples/id-verification/app.pln +1 -1
  55. package/examples/interactive-cli.pln +34 -0
  56. package/examples/javascript-library/README.md +1 -1
  57. package/examples/javascript-library/src/interop.pln +1 -1
  58. package/examples/json.pln +1 -1
  59. package/examples/loops.pln +1 -1
  60. package/examples/memoize-demo.pln +31 -0
  61. package/examples/modules/app.pln +1 -1
  62. package/examples/modules/main.pln +1 -1
  63. package/examples/modules/math.pln +1 -1
  64. package/examples/mongo.pln +1 -1
  65. package/examples/normalization-forms.pln +22 -0
  66. package/examples/objects.pln +1 -1
  67. package/examples/ocr.pln +1 -1
  68. package/examples/packages.pln +1 -1
  69. package/examples/random-cli.pln +32 -0
  70. package/examples/record-kinds.pln +1 -1
  71. package/examples/records.pln +1 -1
  72. package/examples/rest-api-fetch.pln +1 -1
  73. package/examples/rest-api.pln +1 -1
  74. package/examples/run-in-parallel.pln +25 -0
  75. package/examples/scheduled-tasks.pln +1 -1
  76. package/examples/search-and-filter.pln +1 -1
  77. package/examples/server.pln +1 -1
  78. package/examples/sessions-and-cookies.pln +1 -1
  79. package/examples/sqlite.pln +1 -1
  80. package/examples/start.pln +1 -1
  81. package/examples/stats-cli.pln +29 -0
  82. package/examples/stdlib.pln +1 -1
  83. package/examples/string-helpers.pln +23 -0
  84. package/examples/string-verbs.pln +1 -1
  85. package/examples/telegram-ai-bot.pln +1 -1
  86. package/examples/telegram-bot.pln +1 -1
  87. package/examples/terminal-cli.pln +11 -0
  88. package/examples/testing.pln +1 -1
  89. package/examples/three-dimensional/README.md +1 -1
  90. package/examples/three-dimensional/src/scene.pln +1 -1
  91. package/examples/todo-cli.pln +98 -0
  92. package/examples/typed-collections.pln +21 -0
  93. package/examples/web-api.pln +1 -1
  94. package/examples/web-app.pln +1 -1
  95. package/examples/websocket-server.pln +1 -1
  96. package/examples/websocket.pln +1 -1
  97. package/examples/whatsapp-bot/pairing.pln +1 -1
  98. package/examples/whatsapp-bot/qr.pln +1 -1
  99. package/package.json +13 -4
package/README.md CHANGED
@@ -29,6 +29,7 @@ Describe *what* you want. The compiler decides *how* to implement it in JavaScri
29
29
  - [CLI Reference](#cli-reference)
30
30
  - [Building & Configuration](#building--configuration)
31
31
  - [Language Tour](#language-tour)
32
+ - [Closing blocks with `end`](#closing-blocks-with-end)
32
33
  - [Variables](#variables)
33
34
  - [String Templates](#string-templates)
34
35
  - [Conditions](#conditions)
@@ -40,8 +41,11 @@ Describe *what* you want. The compiler decides *how* to implement it in JavaScri
40
41
  - [Loops](#loops)
41
42
  - [Natural-Language Expressions](#natural-language-expressions)
42
43
  - [Logical Assignment](#logical-assignment)
44
+ - [Compound Assignment](#compound-assignment)
45
+ - [Assignment aliases](#assignment-aliases)
43
46
  - [Error handling, async, and events](#error-handling-async-and-events)
44
47
  - [Record Kinds, Concurrency & More](#record-kinds-concurrency--more)
48
+ - [Concurrency: `run in parallel`](#concurrency-run-in-parallel)
45
49
  - [Backend Services](#backend-services)
46
50
  - [Databases](#databases)
47
51
  - [HTTP Client](#http-client)
@@ -52,6 +56,10 @@ Describe *what* you want. The compiler decides *how* to implement it in JavaScri
52
56
  - [Google OAuth](#google-oauth)
53
57
  - [Error Handling & Retries](#error-handling--retries)
54
58
  - [Runtime Standard Library](#runtime-standard-library)
59
+ - [Interactive Terminal & CLI Primitives](#interactive-terminal--cli-primitives)
60
+ - [Statistics & Vectors](#statistics--vectors)
61
+ - [Randomness](#randomness)
62
+ - [Memoization & Parsing Helpers](#memoization--parsing-helpers)
55
63
  - [Web Applications](#web-applications)
56
64
  - [Browser games and interactive apps](#browser-games-and-interactive-apps)
57
65
  - [Additional Backend Capabilities](#additional-backend-capabilities)
@@ -63,6 +71,7 @@ Describe *what* you want. The compiler decides *how* to implement it in JavaScri
63
71
  - [Cache](#cache)
64
72
  - [AI / ML](#ai--ml)
65
73
  - [Pagination](#pagination)
74
+ - [AI-Readiness: On-Device Intelligence](#ai-readiness-on-device-intelligence)
66
75
  - [Multi-File Projects](#multi-file-projects)
67
76
  - [Express Integration](#express-integration)
68
77
  - [WhatsApp Bots](#whatsapp-bots)
@@ -122,7 +131,7 @@ done
122
131
  </tr>
123
132
  </table>
124
133
 
125
- **Current version:** `v1.0.362` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
134
+ **Current version:** `v1.1.0` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
126
135
 
127
136
  ---
128
137
 
@@ -172,7 +181,7 @@ whatsapp bot
172
181
  auth "session"
173
182
  login qr
174
183
  done
175
- ```
184
+ ```plainscript
176
185
 
177
186
  For a local adapter, install it from the project directory (for example,
178
187
  `npm install ./vendor/baileys`) and ensure it exposes the Baileys default
@@ -187,8 +196,11 @@ socket export plus `useMultiFileAuthState`, `makeCacheableSignalKeyStore`, and
187
196
  | Command | Description |
188
197
  |---|---|
189
198
  | `plainscript run <file.pln>` | Installs missing dependencies, compiles, and executes. Runs from a scratch directory - nothing is written into your project. |
199
+ | `plainscript test [target]` | Runs a PlainScript test file or all `*.test.pln` / `*.spec.pln` files under `tests/` (or `test/`). |
200
+ | `plainscript ir <file.pln>` | Emits the stable, backend-neutral compiler IR as JSON for tooling and diagnostics. |
201
+ | `plainscript-lsp` | Runs the stdio Language Server Protocol service for editor diagnostics, hover, completion, definitions, and symbols. |
190
202
  | `plainscript build [file.pln]` | Compiles to `dist/`. With no argument, builds every `.pln` file under the source root, preserving names and folder structure. |
191
- | `plainscript check <file.pln>` | Checks syntax only. No output, no execution. |
203
+ | `plainscript check <file.pln>` | Resolves imports, runs static contract/type checking, validates generated JavaScript, and reports a per-file `✓` line (or an error). Never executes your program. |
192
204
  | `plainscript fmt <file.pln>` | Formats a PlainScript file in place. |
193
205
  | `plainscript new [name]` | Creates a new PlainScript project, npm-ready. |
194
206
  | `plainscript install` | Installs dependencies detected across the project's sources. |
@@ -199,6 +211,18 @@ socket export plus `useMultiFileAuthState`, `makeCacheableSignalKeyStore`, and
199
211
  | `plainscript update` | Updates all installed npm packages. |
200
212
  | `plainscript version` | Prints the compiler version. |
201
213
  | `plainscript help` | Prints help text. |
214
+ | `--quiet` | Global flag for `run` / `build` / `check`: suppresses progress banners and per-file summary lines, printing only errors and output. |
215
+ | `--verbose` | Global flag for `run` / `build` / `check`: prints each compile stage with its timing detail. |
216
+
217
+ `--quiet` and `--verbose` are recognized anywhere in the argument list and
218
+ apply to `run`, `build`, and `check`, e.g. `plainscript build --quiet` or
219
+ `plainscript check src/app.pln --verbose`.
220
+
221
+ `run` keeps project-local `node_modules` first. Because generated JavaScript is
222
+ executed from a temporary directory, the CLI then falls back to the
223
+ PlainScript installation's own dependencies (for example, `sql.js` or a
224
+ usable `better-sqlite3`) rather than requiring generated files to be written
225
+ into the project.
202
226
 
203
227
  ---
204
228
 
@@ -237,7 +261,7 @@ For projects that need custom output or source directories, add a `plainscript.c
237
261
  "build": "plainscript build",
238
262
  "prepare": "plainscript build"
239
263
  },
240
- "devDependencies": { "plainscript-lang": "^1.0.362" }
264
+ "devDependencies": { "plainscript-lang": "^1.1.0" }
241
265
  }
242
266
  ```
243
267
 
@@ -248,23 +272,43 @@ For projects that need custom output or source directories, add a `plainscript.c
248
272
  ## Language Tour
249
273
 
250
274
  PlainScript is a fixed vocabulary of English verbs compiled to JavaScript. Every
251
- construct follows the same rhythm: a word opens a block, `done` closes it, and
252
- `give` returns a value - a sentence you could say to a colleague ("if the score
253
- is at least 80, show accepted, otherwise review") is valid source. The sections
254
- below keep the code first, with a short note on what each construct is *for* and
255
- the constraint that matters when you use it.
275
+ construct follows the same rhythm: a word opens a block, `done` — or its synonym
276
+ `end` — closes it, and `give` returns a value - a sentence you could say to a
277
+ colleague ("if the score is at least 80, show accepted, otherwise review") is
278
+ valid source. The sections below keep the code first, with a short note on what
279
+ each construct is *for* and the constraint that matters when you use it.
256
280
 
257
- ### Variables
281
+ ### Closing blocks with `end`
282
+
283
+ Every block can be closed with either `done` or its synonym `end`; the compiler
284
+ treats them identically, so the two spellings mix freely in one file:
258
285
 
286
+ ```plainscript
287
+ to greet name together
288
+ show "hello, " + name
289
+ end
290
+ greet("Ada")
291
+
292
+ when 1 is 1
293
+ show "math still works"
294
+ end
259
295
  ```
296
+
297
+ `end` is accepted wherever `done` is - functions, `if` / `when` /
298
+ `otherwise`, loops, `list with` / `record with`, and every other block.
299
+
300
+ ### Variables
301
+
302
+ ```plainscript
260
303
  let name be "Ayokunle"
261
304
  let age be 16
262
305
  set age to 17
263
306
  ```
264
307
 
265
308
  `remember name as "Ada"` and `let name be "Ada"` are two spellings of the same
266
- declaration; `set name to ...`, `name becomes ...`, and `name is now ...` all
267
- reassign it. Numbers, strings, and booleans behave like JavaScript primitives;
309
+ declaration; `set name to ...`, `change name to ...`, `name becomes ...`, and
310
+ `name is now ...` all reassign it (the full family of assignment aliases is
311
+ listed below). Numbers, strings, and booleans behave like JavaScript primitives;
268
312
  lists, records, dictionaries, and sets are *references*, so pointing two names
269
313
  at the same list means they see the same data.
270
314
 
@@ -272,7 +316,7 @@ at the same list means they see the same data.
272
316
 
273
317
  Backtick-delimited strings preserve whitespace and support `${expression}` interpolation:
274
318
 
275
- ```
319
+ ```plainscript
276
320
  let name be "World"
277
321
  let greeting be `Hello ${name}!`
278
322
  show greeting
@@ -296,8 +340,8 @@ comparison is itself a value: `score is at least 80` is `true` or `false`, so it
296
340
  can be stored, printed, passed to a function, or joined with `and` / `or` /
297
341
  `not`. When you need a *value* rather than a block, use `choosing` (below).
298
342
 
299
- ```
300
- when age is at least 18
343
+ ```plainscript
344
+ if age is at least 18
301
345
  show "Adult"
302
346
  otherwise
303
347
  show "Teenager"
@@ -341,7 +385,7 @@ All comparison operators:
341
385
  `choosing` is the value form of `if`: pick between two expressions and keep the
342
386
  whole thing inline - in an argument, a `give`, or a list element.
343
387
 
344
- ```
388
+ ```plainscript
345
389
  remember verdict as choosing score is at least 90 then "A" otherwise "B"
346
390
  show choosing score is below 60 then "low" otherwise "ok"
347
391
  ```
@@ -351,7 +395,7 @@ condition is true and `<b>` otherwise.
351
395
 
352
396
  ### Functions
353
397
 
354
- ```
398
+ ```plainscript
355
399
  to add a and b together
356
400
  give back a + b
357
401
  done
@@ -369,6 +413,74 @@ function is a value like any other, so it can be stored with `remember`, passed
369
413
  as an argument, or returned from another function. Arguments are optional with
370
414
  defaults: `make label(name as "guest")`.
371
415
 
416
+ ### Typed data contracts
417
+
418
+ PlainScript supports contextual `type` declarations for records and typed
419
+ function parameters. The compiler records the contract in the AST and emitted
420
+ programs validate typed arguments at runtime with clear field-level errors.
421
+ Primitive types are `number`, `text`, `boolean`, `object`, and `null`; contracts
422
+ also support `optional`, `list of`, `dictionary of`, and `or` unions.
423
+
424
+ ```plainscript
425
+ type User
426
+ id is number
427
+ name is text
428
+ active is optional boolean
429
+ done
430
+
431
+ make greet(user as User)
432
+ give `Hello ${user.name}`
433
+ done
434
+
435
+ show greet({ id: 1, name: "Ada" })
436
+ ```
437
+
438
+ Missing required fields and incompatible values fail before the function body
439
+ runs. Functions and intents can declare return contracts with `returns` or
440
+ `returning`; the checker validates returned values and reports missing returns.
441
+ Collection contracts can be used on mutable bindings:
442
+
443
+ ```text
444
+ let users as list of User is [{ id: 1, name: "Ada" }]
445
+ let usersById as dictionary of User is { first: { id: 1, name: "Ada" } }
446
+ ```
447
+
448
+ List elements, dictionary values, and nested record fields are checked
449
+ recursively. Optional and union element types are supported. The static checker
450
+ reports unknown fields, missing required fields, incompatible literal values,
451
+ unknown contract names, arity errors, invalid assignments, unsafe optional
452
+ member access, and invalid member access to editor tooling. Whole-program
453
+ inference and exhaustiveness checking remain future work.
454
+
455
+ ### Language-server tooling
456
+
457
+ The compiler IR and static checker are available through a stdio LSP server:
458
+
459
+ ```bash
460
+ plainscript-lsp
461
+ ```
462
+
463
+ The server implements `initialize`, document open/change/close notifications,
464
+ `textDocument/publishDiagnostics`, type-rich hover, completion, definition,
465
+ references, rename, signature help, and document-symbol requests. Editors
466
+ should launch it as a standard LSP process and send JSON-RPC messages using the
467
+ normal `Content-Length` framing.
468
+
469
+ ### Intent declarations
470
+
471
+ `intend` declares a callable function while preserving the author's semantic
472
+ intent in the AST and compiler IR. It currently has the same execution rules
473
+ as `make`, making it safe to use today while leaving room for contract,
474
+ documentation, and semantic-analysis tooling.
475
+
476
+ ```plainscript
477
+ intend greet(name)
478
+ give `Hello ${name}`
479
+ done
480
+
481
+ show greet("Ada")
482
+ ```
483
+
372
484
  ### Lambdas
373
485
 
374
486
  A lambda is a function without a name, written where a value is expected -
@@ -376,7 +488,7 @@ A lambda is a function without a name, written where a value is expected -
376
488
  one-expression body and the `do ... done` form when the body has several
377
489
  statements:
378
490
 
379
- ```
491
+ ```plainscript
380
492
  remember add as (a, b) -> a + b
381
493
  show add(2, 3)
382
494
 
@@ -402,7 +514,7 @@ is a plain object. Both are ordinary values, so lists hold records, records
402
514
  hold lists, and lambdas can live anywhere a value can. Read and write them with
403
515
  `.name`, `[index]`, or the natural-language forms later in this tour.
404
516
 
405
- ```
517
+ ```plainscript
406
518
  let players be list with "Haaland", "Foden", "Rodri"
407
519
  show players[0]
408
520
  set players[1] to "Palmer"
@@ -419,7 +531,7 @@ show user.name
419
531
  JavaScript's `Map` and `Set` have direct spellings, and tuples are fixed-size
420
532
  arrays you usually unpack all at once:
421
533
 
422
- ```
534
+ ```plainscript
423
535
  remember lookup as dictionary with "alpha" is 1 and "beta" is 2 done
424
536
  show lookup.get("beta") // 2
425
537
 
@@ -440,7 +552,7 @@ and JSON data arrives as nested lists and records.
440
552
  <condition> ... done` repeats until the condition is false. Counted loops come
441
553
  in sentence form too:
442
554
 
443
- ```
555
+ ```plainscript
444
556
  repeat 5 times
445
557
  show "tick"
446
558
  done
@@ -455,7 +567,7 @@ done
455
567
  flips the `while` sense, and `for index i from 0 to 9` gives a zero-based
456
568
  counter when you need positions.
457
569
 
458
- ```
570
+ ```plainscript
459
571
  for each player in players
460
572
  show player
461
573
  done
@@ -475,7 +587,7 @@ Collections, properties, and files read like sentences.
475
587
 
476
588
  **Items**
477
589
 
478
- ```
590
+ ```plainscript
479
591
  let players be list with "Haaland", "Foden", "Rodri"
480
592
 
481
593
  show first player from players // players[0]
@@ -488,7 +600,7 @@ Number words from `one` to `twenty` map to one-based positions - `player one`
488
600
 
489
601
  **Collections**
490
602
 
491
- ```
603
+ ```plainscript
492
604
  show players length // players.length
493
605
  add("Palmer" to players) // players.push("Palmer")
494
606
  remove("Rodri" from players) // players.splice(players.indexOf("Rodri"), 1)
@@ -500,7 +612,7 @@ done
500
612
 
501
613
  **Properties**
502
614
 
503
- ```
615
+ ```plainscript
504
616
  show name of user // user.name
505
617
  show city of address of customer // customer.address.city
506
618
  name of user is now "Ayo" // user.name = "Ayo"
@@ -510,7 +622,7 @@ name of user is now "Ayo" // user.name = "Ayo"
510
622
 
511
623
  **Files**
512
624
 
513
- ```
625
+ ```plainscript
514
626
  let data be read("users.txt") // fs.readFileSync("users.txt", 'utf8')
515
627
  write(data to "users.txt") // fs.writeFileSync(data, "users.txt", 'utf8')
516
628
  ```
@@ -523,16 +635,70 @@ The word-style assignment operators keep the common "fill the empty value"
523
635
  pattern on one line - PlainScript for `flag = flag || true` and
524
636
  `val = val ?? "default"`:
525
637
 
638
+ ```plainscript
639
+ let flag be false
640
+ flag or becomes true
641
+ show flag
642
+
643
+ let val be null
644
+ val nullish becomes "default"
645
+ show val
646
+ ```
647
+
648
+ ### Compound Assignment
649
+
650
+ The arithmetic compound operators map straight to their JavaScript
651
+ counterparts. `+=`, `-=`, `*=`, `/=`, and `%=` all work, and the legacy `++=`
652
+ spelling is still accepted as `+=`:
653
+
654
+ ```plainscript
655
+ let score be 10
656
+ score += 5 // 15
657
+ score -= 3 // 12
658
+ score *= 2 // 24
659
+ score /= 4 // 6
660
+ score %= 7 // 6
661
+ show score
662
+
663
+ let counter be 0
664
+ counter ++= 1 // legacy spelling of +=
665
+ show counter
526
666
  ```
667
+
668
+ The word-style logical forms join them and compile to the same JavaScript as
669
+ their symbols: `or becomes` is `||=`, `and becomes` is `&&=`, and `nullish
670
+ becomes` is `??=` (the symbolic spellings work too):
671
+
672
+ ```plainscript
527
673
  let flag be false
528
- flag or is now true
674
+ flag or becomes true // flag = flag || true
529
675
  show flag
530
676
 
677
+ let tally be 5
678
+ tally and becomes 2 // tally = tally && 2
679
+ show tally
680
+
531
681
  let val be null
532
- val nullish is now "default"
682
+ val nullish becomes "default" // val = val ?? "default"
533
683
  show val
534
684
  ```
535
685
 
686
+ ### Assignment aliases
687
+
688
+ `becomes` has a full family of synonyms in both orders. The prefix forms
689
+ `set name to 17` and `change name to 17`, the postfix forms `name set to 17` and
690
+ `name change to 17`, plus the existing `name is now 17` all compile to the same
691
+ reassignment as `name becomes 17`:
692
+
693
+ ```plainscript
694
+ let name be "Ada"
695
+ change name to "Ada Lovelace"
696
+ name set to "A. L."
697
+ name change to "AL"
698
+ set name to "Ada"
699
+ show name
700
+ ```
701
+
536
702
  ### Error handling, async, and events
537
703
 
538
704
  Programs that fail should say so. `raise <value>` throws an error, `try` /
@@ -587,9 +753,15 @@ PlainScript 1.0.2 closes most of the gap with TypeScript-class languages using i
587
753
 
588
754
  | Category | Features |
589
755
  |---|---|
590
- | Record kinds (classes) | `to define a kind called "Person" with name "" end`, then `create a Person with name "Ada" and age 17`. Plain-object instances; unknown fields throw. |
591
- | Concurrency | `all of [...]`, `any of [...]`, `settled of [...]`, `withTimeout(promise, ms)` |
592
- | Generators | `yield` inside `define ... end`; consumed with `for each` or `spread of` |
756
+ | Record kinds (classes) | `define a kind called "Person" with name "" and age 0 done`, then `create a Person with name "Ada" and age 17`. Plain-object instances; unknown fields throw. |
757
+ | Concurrency | `all of [...]`, `any of [...]`, `settled of [...]`, `withTimeout(promise, ms)`, `run in parallel ... done as <name>` |
758
+ | Compound assignment | `+= -= *= /= %=` plus legacy `++=`, and the word forms `or becomes` (||=), `and becomes` (&&=), `nullish becomes` (??=) |
759
+ | Assignment aliases | prefix `set name to` / `change name to`, postfix `name set to` / `name change to`, plus `name becomes` / `name is now` |
760
+ | Interactive CLI | `ask`, `confirm`, `choose`, `clearTerminal`, `terminalWidth`, `terminalHeight`, `stderr` |
761
+ | Statistics &amp; vectors | `mean`, `median`, `variance`, `deviation`, `dotProduct`, `magnitude`, `normalize` |
762
+ | Randomness | `randomInteger`, `randomChoice`, `weightedChoice`, `shuffle`, `sample` |
763
+ | Memoization &amp; parsing | `memoize`, `parseBoolean`, `characters` |
764
+ | Generators | `yield` inside `make name(...) ... done`; consumed with `for each` or `spread of` |
593
765
  | Reflection | `typeOf`, `fieldsOf`, `valueOf`, `hasField`, `sizeOf` |
594
766
  | Binary | `base64Encode/Decode`, `textToBytes/bytesToText`, `sha256/sha1/md5` |
595
767
  | Config | `yamlDecode/yamlEncode`, `load env file ".env"` |
@@ -598,11 +770,36 @@ PlainScript 1.0.2 closes most of the gap with TypeScript-class languages using i
598
770
  | Streams | `writeLine`, `appendLine` |
599
771
  | Collections | `keyMap/mapSet/mapGet/mapHas/mapDelete`, `newSet/addToSet` |
600
772
  | Dynamic modules | `loadModule("./m")` |
601
- | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check <expr> raises "msg"` |
773
+ | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check <expr> raises "msg"`; run files with `plainscript test` |
602
774
  | Exports | `export <name>` |
603
775
 
604
776
  </details>
605
777
 
778
+ ### Concurrency: `run in parallel`
779
+
780
+ `run in parallel ... done as <name>` runs the block's statements concurrently
781
+ and collects each statement's value in order into the named list - the
782
+ statement-level equivalent of `all of [...]`:
783
+
784
+ ```plainscript
785
+ make square(n)
786
+ give n * n
787
+ end
788
+
789
+ run in parallel
790
+ square(3)
791
+ square(4)
792
+ done as results
793
+
794
+ show join(results, ", ") // 9, 4
795
+ ```
796
+
797
+ Each statement in the block becomes one concurrent task; the collected list has
798
+ one entry per statement in body order, so expression statements (typically
799
+ calls) contribute their return values. This is a single-process, promise-based
800
+ concurrency feature (implemented with `Promise.all`) - it runs concurrent
801
+ tasks, not worker threads.
802
+
606
803
  **How the pieces fit together.** PlainScript is deliberately small: a handful
607
804
  of verbs (`remember`, `give`, `if` / `otherwise`, `done`) plus the collections
608
805
  and functions you just met. Everything is a value - numbers and strings,
@@ -624,13 +821,13 @@ Everything in this section is compiled by the deterministic compiler - no rule
624
821
 
625
822
  Portable databases (SQLite native or WebAssembly):
626
823
 
627
- ```
824
+ ```plainscript
628
825
  database "app.db" // probes better-sqlite3, falls back to sql.js
629
826
  ```
630
827
 
631
- `plainscript install` verifies that `better-sqlite3` actually loads. Since 1.0.362 the native engine ships as an **optional dependency**: installing `plainscript-lang` can never fail because a native binary is missing for the platform (e.g. Android/Termux), and programs that never open a database start without it. If the native module cannot be used, PlainScript warns and continues on the pure-JavaScript WebAssembly engine (`sql.js`) - the same program runs unchanged. An engine can be forced explicitly:
828
+ `plainscript install` verifies that `better-sqlite3` actually loads. The native engine ships as an **optional dependency**: installing `plainscript-lang` can never fail because a native binary is missing for the platform (e.g. Android/Termux), and programs that never open a database start without it. If the native module cannot be used, PlainScript warns and continues on the pure-JavaScript WebAssembly engine (`sql.js`) - the same program runs unchanged. An engine can be forced explicitly:
632
829
 
633
- ```
830
+ ```plainscript
634
831
  database "app.db" using "native" // hard requirement: better-sqlite3
635
832
  database "app.db" using "wasm" // hard requirement: sql.js
636
833
  ```
@@ -639,7 +836,7 @@ The WebAssembly engine persists the whole database to disk after every write, so
639
836
 
640
837
  ### HTTP Client
641
838
 
642
- ```
839
+ ```plainscript
643
840
  let r be get "https://api.example.com/users"
644
841
  when ok of r
645
842
  show status of r
@@ -655,7 +852,7 @@ Methods: `get`, `post … with <body>`, `put`, `patch`, `delete "<url>"`. Respon
655
852
 
656
853
  ### Authentication
657
854
 
658
- ```
855
+ ```plainscript
659
856
  let hash be hashPassword("correct horse")
660
857
  when checkPassword(password of body of request, hash)
661
858
  let token be createToken(user, env("TOKEN_SECRET"), 3600)
@@ -668,12 +865,12 @@ let payload be readToken(token, env("TOKEN_SECRET"))
668
865
 
669
866
  ### Sessions &amp; Cookies
670
867
 
671
- ```
868
+ ```plainscript
672
869
  web app
673
870
  enable sessions "a-long-random-secret"
674
871
 
675
872
  route post "/login"
676
- user of session of request is username of body of request
873
+ user of session of request becomes username of body of request
677
874
  show "welcome"
678
875
  done
679
876
 
@@ -689,15 +886,18 @@ done
689
886
 
690
887
  Sessions ride an HMAC-signed `HttpOnly` cookie (`plainscript.sid`). The store is in-memory: restarting the server signs everyone out.
691
888
 
692
- ```
693
- set cookie "theme" to "dark" expires in 7 days
694
- show cookie("theme")
695
- clear cookie "theme"
889
+ ```plainscript
890
+ web app
891
+ route get "/theme"
892
+ set cookie "theme" to "dark" expires in 7 days
893
+ show cookie("theme")
894
+ clear cookie "theme"
895
+ done
696
896
  ```
697
897
 
698
898
  ### File Uploads
699
899
 
700
- ```
900
+ ```plainscript
701
901
  accept uploads limit "5 MB" allow list with "image/png", "image/jpeg" folder "uploads"
702
902
 
703
903
  route post "/scan"
@@ -711,15 +911,15 @@ Files arrive as records with `name`, `type`, `size`, `data` (buffer), and `path`
711
911
 
712
912
  ### Rate Limiting
713
913
 
714
- ```
715
- rate limit 100 requests per minute
914
+ ```plainscript
915
+ limit requests to 100 per minute
716
916
  ```
717
917
 
718
918
  Sliding window per client IP; the quota-exceeded response is HTTP 429.
719
919
 
720
920
  ### Google OAuth
721
921
 
722
- ```
922
+ ```plainscript
723
923
  google oauth
724
924
  id is env("GOOGLE_ID")
725
925
  secret is env("GOOGLE_SECRET")
@@ -732,7 +932,7 @@ Registers `/auth/google` (redirect) and `/auth/google/callback` (code-for-token
732
932
 
733
933
  ### Error Handling &amp; Retries
734
934
 
735
- ```
935
+ ```plainscript
736
936
  try
737
937
  let data be jsonDecode(raw)
738
938
  recover as err
@@ -746,10 +946,10 @@ done
746
946
 
747
947
  Custom 404 handling:
748
948
 
749
- ```
949
+ ```plainscript
750
950
  when nothing matches
751
951
  status 404
752
- show json
952
+ reply json
753
953
  error is "No such road"
754
954
  done
755
955
  done
@@ -770,7 +970,7 @@ first version of a program usually needs no dependency at all:
770
970
  | `writeFile("path", data)` | Write text to a file |
771
971
  | `read("path")` | Read a file as UTF-8 text |
772
972
  | `fileExists("path")` | Check if a file exists |
773
- | `sleep(ms)` | Sleep synchronously |
973
+ | `sleep(ms)` | Pause asynchronously; awaited when used as a bare statement, and composes concurrently inside `all of [...]` / `wait for sleep(...)` |
774
974
  | `time()` | Current Unix timestamp (`Date.now()`) |
775
975
  | `date()` | ISO date string |
776
976
  | `jsonEncode(value)` | `JSON.stringify` |
@@ -786,6 +986,115 @@ first version of a program usually needs no dependency at all:
786
986
 
787
987
  ---
788
988
 
989
+ ## Interactive Terminal &amp; CLI Primitives
990
+
991
+ PlainScript programs are first-class CLI citizens. `ask` reads a line, `confirm`
992
+ asks a yes/no question, and `choose` offers an option list - each takes an
993
+ optional prompt. `confirm` returns a boolean and `choose` returns the selected
994
+ option; both are async prompts, so a program that uses them compiles to async
995
+ JavaScript and can be driven non-interactively when answers are piped in:
996
+
997
+ ```plainscript
998
+ ask "What is your name? " as guest
999
+ show "hello, " + guest
1000
+
1001
+ remember ok as confirm("Shall we continue")
1002
+ if ok is true
1003
+ show "choice: " + choose("Drink?", list with "tea", "coffee", "juice")
1004
+ end
1005
+ ```
1006
+
1007
+ `clearTerminal()` clears the screen, `terminalWidth()` and `terminalHeight()`
1008
+ report the terminal size, and `stderr(...)` prints to standard error so a
1009
+ program's real output on stdout stays clean:
1010
+
1011
+ ```plainscript
1012
+ stderr("starting terminal census")
1013
+ show "width: " + terminalWidth()
1014
+ show "height: " + terminalHeight()
1015
+ clearTerminal()
1016
+ show "screen cleared"
1017
+ ```
1018
+
1019
+ ---
1020
+
1021
+ ## Statistics &amp; Vectors
1022
+
1023
+ Numeric arrays get the usual statistical summaries, and equal-length numeric
1024
+ arrays become vectors for the linear-algebra primitives behind the AI-style
1025
+ helpers (see [AI-Readiness](#ai-readiness-on-device-intelligence)):
1026
+
1027
+ ```plainscript
1028
+ remember data as [2, 4, 4, 4, 5, 5, 7, 9]
1029
+ show "mean: " + mean(data)
1030
+ show "median: " + median(data)
1031
+ show "variance: " + round(variance(data) * 100) / 100
1032
+ show "deviation: " + round(deviation(data) * 100) / 100
1033
+ ```
1034
+
1035
+ `mean`, `median`, `variance`, and `deviation` each take one list. The vector
1036
+ helpers are `dotProduct(a, b)` (how aligned two lists are), `magnitude(v)` (the
1037
+ Euclidean length), and `normalize(v)` (scales a list to unit length):
1038
+
1039
+ ```plainscript
1040
+ remember a as [1, 2, 3]
1041
+ remember b as [4, 5, 6]
1042
+ show dotProduct(a, b) // 32
1043
+ show magnitude(a) // 3.7416573867739413
1044
+ show join(normalize(a), ", ")
1045
+ ```
1046
+
1047
+ ---
1048
+
1049
+ ## Randomness
1050
+
1051
+ Deterministic programs are the default, but games, simulations, and sampling
1052
+ reach for the random family when they need variety:
1053
+
1054
+ ```plainscript
1055
+ show randomInteger(1, 6) // a die roll
1056
+ let suits be list with "hearts", "spades", "clubs", "diamonds"
1057
+ show randomChoice(suits) // one random suit
1058
+ show weightedChoice(["common", "rare", "legendary"], [0.7, 0.25, 0.05])
1059
+ show join(shuffle(suits), " ") // shuffled copy
1060
+ show join(sample(suits, 2), " ") // two random suits, no repeats
1061
+ ```
1062
+
1063
+ `randomInteger(min, max)` is inclusive on both ends; `randomChoice(list)` picks
1064
+ one element; `weightedChoice(items, weights)` picks according to a parallel
1065
+ list of weights; `shuffle(list)` returns a shuffled copy; and `sample(list, n)`
1066
+ returns `n` distinct elements.
1067
+
1068
+ ---
1069
+
1070
+ ## Memoization &amp; Parsing Helpers
1071
+
1072
+ `memoize` wraps a function so repeated calls with the same arguments hit a
1073
+ cache - handy for expensive pure functions and for memoized inference in the
1074
+ AI-style patterns below:
1075
+
1076
+ ```plainscript
1077
+ make slowSquare(n)
1078
+ give n * n
1079
+ end
1080
+
1081
+ remember fastSquare as memoize(slowSquare)
1082
+ show fastSquare(9)
1083
+ show fastSquare(9) // served from the cache
1084
+ ```
1085
+
1086
+ `parseBoolean` normalizes `"true"`, `"yes"`, `"1"`, and `"on"` (case- and
1087
+ whitespace-insensitive) to `true` and everything else to `false`, and
1088
+ `characters` splits a string into its individual characters:
1089
+
1090
+ ```plainscript
1091
+ show parseBoolean("yes") // true
1092
+ show parseBoolean("off") // false
1093
+ show join(characters("abc"), "-") // a-b-c
1094
+ ```
1095
+
1096
+ ---
1097
+
789
1098
  ## Web Applications
790
1099
 
791
1100
  `web app` starts the HTTP stack available to every program. `route <method>
@@ -802,7 +1111,7 @@ route "/"
802
1111
  done
803
1112
 
804
1113
  route "/api/status"
805
- show json
1114
+ reply json
806
1115
  status is "ok"
807
1116
  version is "2.0"
808
1117
  done
@@ -991,6 +1300,37 @@ show page.hasNext # true if another page exists
991
1300
 
992
1301
  ---
993
1302
 
1303
+ ## AI-Readiness: On-Device Intelligence
1304
+
1305
+ The statistics, vector, randomness, memoization, and persistent-JSON primitives
1306
+ in this release compose into AI-style systems - retrieval scoring, ranking,
1307
+ weighted sampling, memoized inference, and durable memory - built entirely
1308
+ with the deterministic compiler and **no external AI provider, no API key, and
1309
+ no network call**. `examples/ai-memory-cli.pln` is a walking example: it stores
1310
+ "facts" as a JSON file, vectorizes a query with `dotProduct` / `magnitude` /
1311
+ `normalize`, and retrieves the best-matching fact by cosine similarity.
1312
+ `examples/stats-cli.pln` exercises the statistical side over an arbitrary
1313
+ sample from the command line:
1314
+
1315
+ ```plainscript
1316
+ let a be [1, 0, 1] // bag-of-words vector for a stored fact
1317
+ let b be [1, 1, 0] // bag-of-words vector for the query
1318
+ show "raw overlap: " + dotProduct(a, b)
1319
+ let unit be normalize(a) // unit vector: magnitude becomes 1
1320
+ show "unit norm: " + round(magnitude(unit) * 100) / 100
1321
+ ```
1322
+
1323
+ The CLI helpers keep these tools scriptable - for example, storing and
1324
+ querying the memory file:
1325
+
1326
+ ```bash
1327
+ plainscript run examples/ai-memory-cli.pln remember "Ada loves math and jazz"
1328
+ plainscript run examples/ai-memory-cli.pln query "who likes math"
1329
+ plainscript run examples/ai-memory-cli.pln list
1330
+ ```
1331
+
1332
+ ---
1333
+
994
1334
  ## Multi-File Projects
995
1335
 
996
1336
  Programs grow into files. `import "./math.pln"` pulls a whole file into the
@@ -1035,7 +1375,7 @@ when someone visits "/"
1035
1375
  done
1036
1376
 
1037
1377
  when someone visits "/api/status"
1038
- show json
1378
+ reply json
1039
1379
  status is "ok"
1040
1380
  version is "0.3"
1041
1381
  done
@@ -1192,4 +1532,4 @@ Released under the [MIT License](./LICENSE).
1192
1532
 
1193
1533
  <sub>"When even a simple sentence can be code."</sub>
1194
1534
 
1195
- </div>
1535
+ </div>