plainscript-lang 1.0.362 → 1.0.363

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 (97) hide show
  1. package/README.md +382 -54
  2. package/compiler/bundler.js +78 -3
  3. package/compiler/cli.js +224 -30
  4. package/compiler/formatter.js +21 -1
  5. package/compiler/generator.js +453 -107
  6. package/compiler/ir.js +61 -0
  7. package/compiler/lexer.js +42 -7
  8. package/compiler/lsp.js +234 -0
  9. package/compiler/parser.js +780 -110
  10. package/compiler/type-checker.js +246 -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 +308 -0
  15. package/docs/PLAINSCRIPT-SPEC.md +231 -5
  16. package/docs/index.html +5 -5
  17. package/docs/website/script.js +1 -1
  18. package/examples/ai-memory-cli.pln +221 -0
  19. package/examples/ai-memory.json +1 -0
  20. package/examples/ai-providers.pln +1 -1
  21. package/examples/arrays.pln +1 -1
  22. package/examples/async-errors.pln +1 -1
  23. package/examples/auth-api.pln +1 -1
  24. package/examples/auth-sessions.pln +1 -1
  25. package/examples/basics.pln +1 -1
  26. package/examples/bots.pln +1 -1
  27. package/examples/browser-interactive/README.md +1 -1
  28. package/examples/browser-interactive/src/interactive.pln +1 -1
  29. package/examples/cache-and-jobs.pln +1 -1
  30. package/examples/cache-schedule.pln +1 -1
  31. package/examples/canvas-game/README.md +1 -1
  32. package/examples/canvas-game/src/game.pln +1 -1
  33. package/examples/collections.pln +1 -1
  34. package/examples/compound-assignments.pln +24 -0
  35. package/examples/concurrency.pln +2 -2
  36. package/examples/conditions.pln +1 -1
  37. package/examples/database.pln +1 -1
  38. package/examples/day2.pln +1 -1
  39. package/examples/day3.pln +1 -1
  40. package/examples/deployment.pln +1 -1
  41. package/examples/email-send.pln +1 -1
  42. package/examples/error-handling.pln +1 -1
  43. package/examples/expressions.pln +1 -1
  44. package/examples/file-manager-cli.pln +51 -0
  45. package/examples/file-uploads.pln +1 -1
  46. package/examples/files-and-config.pln +1 -1
  47. package/examples/files.pln +1 -1
  48. package/examples/football-backend/app.pln +1 -1
  49. package/examples/functions.pln +1 -1
  50. package/examples/hello.pln +1 -1
  51. package/examples/http-client.pln +1 -1
  52. package/examples/http.pln +1 -1
  53. package/examples/id-verification/app.pln +1 -1
  54. package/examples/interactive-cli.pln +34 -0
  55. package/examples/javascript-library/README.md +1 -1
  56. package/examples/javascript-library/src/interop.pln +1 -1
  57. package/examples/json.pln +1 -1
  58. package/examples/loops.pln +1 -1
  59. package/examples/memoize-demo.pln +31 -0
  60. package/examples/modules/app.pln +1 -1
  61. package/examples/modules/main.pln +1 -1
  62. package/examples/modules/math.pln +1 -1
  63. package/examples/mongo.pln +1 -1
  64. package/examples/normalization-forms.pln +22 -0
  65. package/examples/objects.pln +1 -1
  66. package/examples/ocr.pln +1 -1
  67. package/examples/packages.pln +1 -1
  68. package/examples/random-cli.pln +32 -0
  69. package/examples/record-kinds.pln +1 -1
  70. package/examples/records.pln +1 -1
  71. package/examples/rest-api-fetch.pln +1 -1
  72. package/examples/rest-api.pln +1 -1
  73. package/examples/run-in-parallel.pln +25 -0
  74. package/examples/scheduled-tasks.pln +1 -1
  75. package/examples/search-and-filter.pln +1 -1
  76. package/examples/server.pln +1 -1
  77. package/examples/sessions-and-cookies.pln +1 -1
  78. package/examples/sqlite.pln +1 -1
  79. package/examples/start.pln +1 -1
  80. package/examples/stats-cli.pln +29 -0
  81. package/examples/stdlib.pln +1 -1
  82. package/examples/string-helpers.pln +23 -0
  83. package/examples/string-verbs.pln +1 -1
  84. package/examples/telegram-ai-bot.pln +1 -1
  85. package/examples/telegram-bot.pln +1 -1
  86. package/examples/terminal-cli.pln +11 -0
  87. package/examples/testing.pln +1 -1
  88. package/examples/three-dimensional/README.md +1 -1
  89. package/examples/three-dimensional/src/scene.pln +1 -1
  90. package/examples/todo-cli.pln +98 -0
  91. package/examples/web-api.pln +1 -1
  92. package/examples/web-app.pln +1 -1
  93. package/examples/websocket-server.pln +1 -1
  94. package/examples/websocket.pln +1 -1
  95. package/examples/whatsapp-bot/pairing.pln +1 -1
  96. package/examples/whatsapp-bot/qr.pln +1 -1
  97. package/package.json +13 -4
@@ -0,0 +1,246 @@
1
+ // Static type-checking foundation for PlainScript contracts.
2
+ //
3
+ // This checker is intentionally conservative: untyped programs remain valid,
4
+ // while declared contracts, typed parameters, known fields, and literal call
5
+ // arguments receive useful diagnostics before code generation.
6
+
7
+ const { lowerToIR } = require('./ir');
8
+
9
+ function diagnostic(message, node, code = 'PLN-TYPE') {
10
+ const line = node && node.line ? node.line : 1;
11
+ const column = node && node.col ? node.col : 1;
12
+ return {
13
+ severity: 1,
14
+ source: 'plainscript',
15
+ code,
16
+ message,
17
+ range: {
18
+ start: { line: line - 1, character: column - 1 },
19
+ end: { line: line - 1, character: column },
20
+ },
21
+ };
22
+ }
23
+
24
+ function typeName(spec) {
25
+ if (!spec) return 'any';
26
+ if (spec.kind === 'name') return spec.name;
27
+ if (spec.kind === 'optional') return `optional ${typeName(spec.value)}`;
28
+ if (spec.kind === 'list') return `list of ${typeName(spec.value)}`;
29
+ if (spec.kind === 'dictionary') return `dictionary of ${typeName(spec.value)}`;
30
+ if (spec.kind === 'union') return spec.values.map(typeName).join(' or ');
31
+ return 'any';
32
+ }
33
+
34
+ function isNullSpec(spec) {
35
+ return spec && spec.kind === 'name' && spec.name === 'null';
36
+ }
37
+
38
+ function isOptionalSpec(spec) {
39
+ return spec && (spec.kind === 'optional' || (spec.kind === 'union' && spec.values.some(isNullSpec)));
40
+ }
41
+
42
+ function specMatches(actual, expected, schemas) {
43
+ if (!expected || expected.kind === 'name' && expected.name === 'any' || !actual) return true;
44
+ if (expected.kind === 'optional') return actual === 'null' || specMatches(actual, expected.value, schemas);
45
+ if (expected.kind === 'union') return expected.values.some(item => specMatches(actual, item, schemas));
46
+ if (expected.kind === 'name') {
47
+ if (expected.name === 'null') return actual === 'null';
48
+ if (expected.name === 'object') return actual === 'object' || typeof actual === 'object';
49
+ if (expected.name === actual) return true;
50
+ if (schemas.has(expected.name) && actual === 'object') return true;
51
+ return false;
52
+ }
53
+ if (expected.kind === 'list') return actual === 'list' || actual === 'any';
54
+ if (expected.kind === 'dictionary') return actual === 'dictionary' || actual === 'object' || actual === 'any';
55
+ return true;
56
+ }
57
+
58
+ function literalType(node) {
59
+ if (!node) return 'any';
60
+ switch (node.type) {
61
+ case 'NumberLiteral': return 'number';
62
+ case 'StringLiteral':
63
+ case 'TemplateLiteral': return 'text';
64
+ case 'BooleanLiteral': return 'boolean';
65
+ case 'NullLiteral': return 'null';
66
+ case 'ArrayLiteral': return 'list';
67
+ case 'InlineObjectLiteral':
68
+ case 'ObjectLiteral': return 'object';
69
+ default: return null;
70
+ }
71
+ }
72
+
73
+ function checkTypes(ast, options = {}) {
74
+ const ir = options.ir || lowerToIR(ast);
75
+ const diagnostics = [];
76
+ const schemas = new Map();
77
+ const functions = new Map();
78
+ const symbols = new Map();
79
+
80
+ function addTypeSpecErrors(spec, node) {
81
+ if (!spec) return;
82
+ if (spec.kind === 'name') {
83
+ const primitives = new Set(['any', 'number', 'text', 'boolean', 'null', 'object']);
84
+ if (!primitives.has(spec.name) && !schemas.has(spec.name)) {
85
+ diagnostics.push(diagnostic(`Unknown type "${spec.name}". Declare it with type ${spec.name} ... done.`, node, 'PLN-TYPE-UNKNOWN'));
86
+ }
87
+ } else if (spec.kind === 'optional' || spec.kind === 'list' || spec.kind === 'dictionary') {
88
+ addTypeSpecErrors(spec.value, node);
89
+ } else if (spec.kind === 'union') {
90
+ spec.values.forEach(value => addTypeSpecErrors(value, node));
91
+ }
92
+ }
93
+
94
+ for (const node of ast.body || []) {
95
+ if (node.type === 'TypeDeclaration') {
96
+ if (schemas.has(node.name)) diagnostics.push(diagnostic(`Type "${node.name}" is declared more than once.`, node, 'PLN-TYPE-DUPLICATE'));
97
+ schemas.set(node.name, node);
98
+ }
99
+ if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
100
+ functions.set(node.name, node);
101
+ symbols.set(node.name, { kind: node.type === 'IntentDeclaration' ? 'intent' : 'function', node });
102
+ }
103
+ if (node.type === 'RememberStatement' && typeof node.name === 'string') symbols.set(node.name, { kind: 'variable', node });
104
+ }
105
+
106
+ for (const node of ast.body || []) {
107
+ if (node.type === 'TypeDeclaration') {
108
+ for (const field of node.fields || []) addTypeSpecErrors(field.type, field);
109
+ }
110
+ if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
111
+ for (const param of node.params || []) {
112
+ if (param.typeAnnotation) addTypeSpecErrors(param.typeAnnotation, node);
113
+ }
114
+ }
115
+ }
116
+
117
+ function fieldSpec(schemaName, fieldName) {
118
+ const schema = schemas.get(schemaName);
119
+ const field = schema && (schema.fields || []).find(item => item.key === fieldName);
120
+ return field ? field.type : null;
121
+ }
122
+
123
+ function infer(node, env, origin = node) {
124
+ if (!node) return 'any';
125
+ const literal = literalType(node);
126
+ if (literal) return literal;
127
+ if (node.type === 'Identifier') {
128
+ const entry = env.get(node.name) || symbols.get(node.name);
129
+ return entry && entry.type ? entry.type : 'any';
130
+ }
131
+ if (node.type === 'MemberExpression') {
132
+ const objectType = infer(node.object, env, origin);
133
+ if (objectType && schemas.has(objectType)) {
134
+ const field = fieldSpec(objectType, node.property);
135
+ if (!field) diagnostics.push(diagnostic(`Type "${objectType}" has no field named "${node.property}".`, origin, 'PLN-TYPE-FIELD'));
136
+ return field ? typeName(field) : 'any';
137
+ }
138
+ return 'any';
139
+ }
140
+ if (node.type === 'CallExpression') {
141
+ const fn = functions.get(node.name);
142
+ if (fn) return 'any';
143
+ return 'any';
144
+ }
145
+ return 'any';
146
+ }
147
+
148
+ function checkExpression(node, env, origin = node) {
149
+ if (!node || typeof node !== 'object') return;
150
+ if (node.type === 'MemberExpression') {
151
+ infer(node, env, origin);
152
+ checkExpression(node.object, env, origin);
153
+ return;
154
+ }
155
+ if (node.type === 'CallExpression') {
156
+ const fn = functions.get(node.name);
157
+ if (fn) {
158
+ const params = (fn.params || []).filter(param => param.name);
159
+ if (node.args.length !== params.length && !params.some(param => param.type === 'RestElement')) {
160
+ diagnostics.push(diagnostic(`Intent/function "${node.name}" expects ${params.length} argument(s), received ${node.args.length}.`, origin, 'PLN-TYPE-ARITY'));
161
+ }
162
+ node.args.forEach((arg, index) => {
163
+ const param = params[index];
164
+ if (!param || !param.typeAnnotation) return;
165
+ const actual = infer(arg, env, origin);
166
+ if (!specMatches(actual, param.typeAnnotation, schemas)) {
167
+ diagnostics.push(diagnostic(`Argument ${index + 1} of "${node.name}" expects ${typeName(param.typeAnnotation)}, received ${actual}.`, origin, 'PLN-TYPE-ARG'));
168
+ }
169
+ validateLiteralAgainstSpec(arg, param.typeAnnotation, origin);
170
+ });
171
+ }
172
+ node.args.forEach(arg => checkExpression(arg, env, origin));
173
+ return;
174
+ }
175
+ for (const value of Object.values(node)) {
176
+ if (value && typeof value === 'object') {
177
+ if (Array.isArray(value)) value.forEach(item => checkExpression(item, env, origin));
178
+ else if (value.type) checkExpression(value, env, origin);
179
+ }
180
+ }
181
+ }
182
+
183
+ function validateLiteralAgainstSpec(node, expected, origin) {
184
+ if (!node || !expected) return;
185
+ if (expected.kind === 'optional') {
186
+ if (node.type !== 'NullLiteral') validateLiteralAgainstSpec(node, expected.value, origin);
187
+ return;
188
+ }
189
+ if (expected.kind === 'union') {
190
+ const actual = literalType(node);
191
+ if (!expected.values.some(item => specMatches(actual, item, schemas))) {
192
+ diagnostics.push(diagnostic(`Expected ${typeName(expected)}, received ${actual || 'an expression'}.`, origin, 'PLN-TYPE-ARG'));
193
+ }
194
+ return;
195
+ }
196
+ if (expected.kind !== 'name' || !schemas.has(expected.name) || node.type !== 'InlineObjectLiteral') return;
197
+ const schema = schemas.get(expected.name);
198
+ const properties = new Map((node.properties || []).map(property => [property.key, property]));
199
+ for (const field of schema.fields || []) {
200
+ const property = properties.get(field.key);
201
+ if (!property) {
202
+ if (!isOptionalSpec(field.type)) diagnostics.push(diagnostic(`Argument is missing required field "${field.key}" for type "${expected.name}".`, origin, 'PLN-TYPE-FIELD'));
203
+ continue;
204
+ }
205
+ const actual = literalType(property.value);
206
+ if (actual && !specMatches(actual, field.type, schemas)) {
207
+ diagnostics.push(diagnostic(`Field "${field.key}" expects ${typeName(field.type)}, received ${actual}.`, origin, 'PLN-TYPE-FIELD'));
208
+ }
209
+ validateLiteralAgainstSpec(property.value, field.type, origin);
210
+ }
211
+ for (const property of node.properties || []) {
212
+ if (!(schema.fields || []).some(field => field.key === property.key)) {
213
+ diagnostics.push(diagnostic(`Type "${expected.name}" has no field named "${property.key}".`, origin, 'PLN-TYPE-FIELD'));
214
+ }
215
+ }
216
+ }
217
+
218
+ function checkStatements(statements, env) {
219
+ for (const node of statements || []) {
220
+ if (!node) continue;
221
+ if (node.type === 'RememberStatement' && typeof node.name === 'string') {
222
+ const type = literalType(node.value);
223
+ env.set(node.name, { type: type || 'any', node });
224
+ checkExpression(node.value, env, node);
225
+ } else if (node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration') {
226
+ const nested = new Map(env);
227
+ for (const param of node.params || []) {
228
+ if (param.name) nested.set(param.name, { type: param.typeAnnotation && param.typeAnnotation.kind === 'name' ? param.typeAnnotation.name : 'any', node: param });
229
+ }
230
+ checkStatements(node.body, nested);
231
+ } else {
232
+ for (const value of Object.values(node)) {
233
+ if (value && typeof value === 'object') {
234
+ if (Array.isArray(value)) value.forEach(item => item && (item.type ? checkExpression(item, env, node) : checkStatements([item], env)));
235
+ else if (value.type && value.type !== 'TypeDeclaration') checkExpression(value, env, node);
236
+ }
237
+ }
238
+ }
239
+ }
240
+ }
241
+
242
+ checkStatements(ast.body, new Map());
243
+ return { diagnostics, ir };
244
+ }
245
+
246
+ module.exports = { checkTypes, typeName };
@@ -1,6 +1,6 @@
1
1
  // Single source of truth for the compiler version.
2
2
  // Consumed by cli.js help/version output.
3
3
 
4
- const VERSION = '1.0.362';
4
+ const VERSION = '1.0.363';
5
5
 
6
6
  module.exports = { VERSION };
@@ -1,4 +1,4 @@
1
- # PlainScript 1.0.362 Capability Audit
1
+ # PlainScript 1.0.363 Capability Audit
2
2
 
3
3
  This audit is based on what the compiler actually supports right now.
4
4
  If `plainscript check` validates it, it's listed here.
@@ -14,12 +14,23 @@ If `plainscript check` validates it, it's listed here.
14
14
  | Records and record kinds | Implemented | `define a kind called "User" with ... done` |
15
15
  | Conditions | Implemented | `if ... otherwise ... done` |
16
16
  | Functions | Implemented | `make add(a, b) ... done` |
17
+ | Intent declarations | Implemented | `intend greet(name) ... done`; preserved in AST and IR |
18
+ | Runtime data contracts | Implemented | `type User ... done`, typed parameters, unions and collections |
19
+ | Static contract diagnostics | Implemented | AST/IR checker reports field, arity, literal-value, and unknown-type errors |
17
20
  | Generators | Implemented | `yield value` |
18
21
  | For and while loops | Implemented | `for each ... done`, `while ... done` |
19
22
  | Match and switch | Implemented | `match value against ... done` |
20
23
  | Loop control | Implemented | `break`, `continue` |
21
24
  | String verbs | Implemented | `lowercase`, `uppercase`, `split`, `join`, `trim`, `capitalize words` |
22
25
  | Classes and `new` | Implemented | JavaScript-compatible class forms |
26
+ | Compound assignment | Implemented | `+=`, `-=`, `*=`, `/=`, `%=`, `++=`, `or becomes`, `and becomes`, `nullish becomes` |
27
+ | `set` / `change` assignment | Implemented | `set x to 1`, `change x to 1`, `x set to 1`, `x change to 1` |
28
+ | Statistics | Implemented | `mean`, `median`, `variance`, `deviation` |
29
+ | Vector math | Implemented | `dotProduct`, `magnitude`, `normalize` |
30
+ | Randomness | Implemented | `randomInteger`, `randomChoice`, `weightedChoice`, `shuffle`, `sample` |
31
+ | Memoization | Implemented | `memoize(fn)`, `parseBoolean`, `characters` |
32
+ | Regex capture | Implemented | `match pattern "^(\\d+)$" in "4061" as digits` |
33
+ | Collection size | Implemented | `count of [1, 2, 3]`, `count of "hello"` |
23
34
 
24
35
  ## Modules and Runtime
25
36
 
@@ -32,9 +43,14 @@ If `plainscript check` validates it, it's listed here.
32
43
  | Files and paths | Implemented | Read/write, bytes, folders, path helpers |
33
44
  | Crypto and auth helpers | Implemented | Hashes, passwords, tokens |
34
45
  | Async/await | Implemented | `wait for`, `await`, async propagation |
35
- | Concurrency | Implemented | `allOf`, `anyOf`, `settledOf`, `withTimeout` |
46
+ | Concurrency | Implemented | `all of`, `any of`, `settled of`, `withTimeout`, `run in parallel ... done as name` |
36
47
  | Errors and retries | Implemented | `try`, `recover`, `finally`, `retry` |
37
48
  | Native tests | Implemented | `test` and `check` assertions |
49
+ | Terminal I/O | Implemented | `confirm("...")`, `choose("...", [...])`, `stderr(...)` |
50
+ | Terminal query | Implemented | `clearTerminal()`, `terminalWidth()`, `terminalHeight()` |
51
+ | CLI flags | Implemented | `--quiet`, `--verbose` |
52
+ | Compiler IR inspection | Implemented | `plainscript ir file.pln` emits versioned JSON |
53
+ | Language-server protocol | Implemented | `plainscript-lsp` stdio server with diagnostics, hover, completion, definitions, symbols |
38
54
 
39
55
  ## Web and Services
40
56
 
@@ -126,6 +142,6 @@ find examples -name '*.pln' -exec node compiler/cli.js check {} \;
126
142
 
127
143
  ## Version Info
128
144
 
129
- The release label for this repo is `1.0.362`. It covers the compiler,
145
+ The release label for this repo is `1.0.363`. It covers the compiler,
130
146
  package metadata, website, editor tooling, and browser/game documentation.
131
147
  Third-party dependency versions are not tied to this label.
@@ -1,4 +1,4 @@
1
- # PlainScript Game Development Prompt Guide (v1.0.362)
1
+ # PlainScript Game Development Prompt Guide (v1.0.363)
2
2
 
3
3
  The standing instruction sheet for AI agents asked to build games and
4
4
  interactive browser apps in PlainScript.
@@ -29,7 +29,7 @@ Every PlainScript block you show a user must compile - check it first.
29
29
 
30
30
  PlainScript is intent-oriented: you describe *what* the game should do and the
31
31
  compiler generates JavaScript. One hard rule - **game logic lives in
32
- PlainScript**. v1.0.362 reaches into any JS API from `.pln`, which makes
32
+ PlainScript**. v1.0.363 reaches into any JS API from `.pln`, which makes
33
33
  dropping to JS tempting; do not. Every browser capability below stays
34
34
  reachable without leaving PlainScript.
35
35
 
@@ -237,7 +237,7 @@ done
237
237
  requestAnimationFrame(loop)
238
238
  ```
239
239
 
240
- v1.0.362 adds hex literals (`0xRRGGBB`): numeric colors use `0xffffff` instead
240
+ v1.0.363 adds hex literals (`0xRRGGBB`): numeric colors use `0xffffff` instead
241
241
  of magic decimals, and a `"#ffffff"` string works too - THREE accepts all
242
242
  three.
243
243
 
@@ -0,0 +1,308 @@
1
+ # PlainScript Grammar Reference
2
+
3
+ This document is the single source of truth for the PlainScript language
4
+ surface. Compiler behavior (`compiler/lexer.js`, `compiler/parser.js`,
5
+ `compiler/generator.js`) overrides any prose in this or other docs.
6
+
7
+ Version: 1.0.363
8
+
9
+ ---
10
+
11
+ ## 1. Files and encoding
12
+
13
+ A `.pln` file is UTF-8 text. Line comments start with `//`. Blank lines are
14
+ ignored. Indentation is conventional and ignored by the lexer; blocks are
15
+ *keyword* delimited, not indentation delimited.
16
+
17
+ ## 2. Tokens and keywords
18
+
19
+ PlainScript is lexed into tokens first. Almost every line begins with a
20
+ keyword; the parser dispatches statements off the first token. The full
21
+ keyword set:
22
+
23
+ ```text
24
+ remember let show print display as is if otherwise else done end
25
+ do greater less than make define function give return give back
26
+ becomes is now set to change to for each every in while use
27
+ import include load when someone visits listen start on serve on
28
+ on reply respond send back json file serve serve static serve public
29
+ folder above below at least most not empty contains starts ends
30
+ with between and or instanceof now back true false null undefined
31
+ web route start run on database connect database use database
32
+ ask prompt ocr gather filter total match against pattern parallel
33
+ stream emit happens catches yield symbol debugger to together be
34
+ then plus minus times divided by list with record with raise raises
35
+ choosing uses fills repeat until log query insert update delete
36
+ execute
37
+ ```
38
+
39
+ Some keywords are contextual: `end` is a universal block terminator (an alias
40
+ for `done`); `most` only forms a comparator as `is at most`.
41
+
42
+ ### Reserved words: names you cannot declare
43
+
44
+ You cannot use a keyword as a variable, function, or parameter name. This
45
+ includes (non-exhaustively): `log`, `start`, `empty`,
46
+ `pattern`, `match`, `filter`, `gather`, `stream`, `emit`, `run`,
47
+ `then`, `to`, `file`*, `load`, `route`, `database`, `raise`, `retry`,
48
+ `between`, `contains`, `with`, `and`, `or`, `not`.
49
+
50
+ \* `file` is accepted as a variable name by `remember` but not as a
51
+ function name. `back`, `total`, `reply`, `respond`, `send` and the SQL words
52
+ (`query`, `insert`, `update`, `delete`, `execute`) are contextual and *are*
53
+ accepted as declaration names where unambiguous.
54
+
55
+ When a reserved word is used as a name, the compiler reports a clean error
56
+ naming the word, e.g.:
57
+
58
+ ```text
59
+ Line 1, Column 10: Expected a variable name after "remember".
60
+
61
+ "log" is a reserved PlainScript word and cannot be used as a name here.
62
+ Pick a different name (see docs/PLAINSCRIPT-GRAMMAR.md).
63
+ ```
64
+
65
+ ### Operators
66
+
67
+ | Token | Meaning |
68
+ |---|---|
69
+ | `+ - * / %` | arithmetic |
70
+ | `**` | exponentiation |
71
+ | `plus`, `minus`, `times`, `divided by` | word-form arithmetic |
72
+ | `->` | case arrow / lambda arrow |
73
+ | `.` `?.` `??` | member access, optional chain, nullish coalesce |
74
+ | `...` | spread |
75
+ | `(` `)` `[` `]` `{` `}` `,` `:` | grouping, literals, comma, object colon |
76
+
77
+ ### Assignment operators
78
+
79
+ | Operator | Meaning |
80
+ |---|---|
81
+ | `=` | never used as a token; assignments are word-formed (see §4) |
82
+ | `+=` | add-assign (lexed as `PLUS_ASSIGN`; the legacy spelling `++=` is accepted and normalized) |
83
+ | `-=` | subtract-assign |
84
+ | `*=` | multiply-assign |
85
+ | `/=` | divide-assign |
86
+ | `%=` | remainder-assign |
87
+ | `\|\|=` | logical-or assign (word form: `or becomes`) |
88
+ | `&&=` | logical-and assign (word form: `and becomes`) |
89
+ | `??=` | nullish assign (word form: `nullish becomes`) |
90
+
91
+ ## 3. Literals
92
+
93
+ ```plainscript
94
+ remember zero as 0
95
+ remember negative as -5
96
+ remember pi as 3.14
97
+ remember hex as 0xFF
98
+ remember big as 1n
99
+ remember quoted as "double-quoted string"
100
+ remember templated as `template ${interpolation}`
101
+ remember truth as true
102
+ remember falsity as false
103
+ remember nothing as null
104
+ remember absent as undefined
105
+ remember arr as [1, 2, 3]
106
+ remember arr2 as list with 1, 2, 3
107
+ remember obj as { name: "Ada", age: 17 }
108
+ remember rec as record with name "Ada" and age 17
109
+ ```
110
+
111
+ Arrays and records come in both a bracket and a word form; the two normalize
112
+ to the same AST.
113
+
114
+ ### Nullish equality (v1.0.364)
115
+
116
+ `is null` is deliberately **nullish**: it matches `null` *and* `undefined`.
117
+ PlainScript builtins intentionally differ — `env()` of a missing variable
118
+ yields `null`, while reading a missing array slot (e.g. `first of []`)
119
+ yields `undefined` — so a guard written as `is null` must never silently
120
+ fail on the other nullish value:
121
+
122
+ ```plainscript
123
+ remember f as first of []
124
+ if f is null // true — catches null AND undefined
125
+ show "missing"
126
+ done
127
+ ```
128
+
129
+ `is undefined` is the strict escape hatch (matches `undefined` only), and
130
+ comparing the two literals to each other keeps JavaScript semantics
131
+ (`null is undefined` is false). `is not null` is nullish the same way.
132
+
133
+ ### Parser limits
134
+
135
+ Expressions may nest up to 300 levels deep and blocks up to 200 levels deep
136
+ (real code never comes close). Beyond the limit compilation fails with a
137
+ clean positional error — never a JavaScript stack trace. Runtime failures of
138
+ common shapes (calling a non-function, reading a property of a missing value,
139
+ invalid JSON) are translated into PlainScript wording with a hint; run with
140
+ `--sourcemap` to also get the source-mapped `.pln` stack line.
141
+
142
+ ## 4. Variables and assignment
143
+
144
+ ## 4. Variables and assignment
145
+
146
+ Declaration — all three are identical and compile to the same JavaScript:
147
+
148
+ ```plainscript
149
+ let x is 5
150
+ let y be 6
151
+ remember z as 7
152
+ ```
153
+
154
+ Reassignment (word-formed; PlainScript has no `=` symbol):
155
+
156
+ ```plainscript
157
+ x becomes 10
158
+ x is now 11
159
+ x set to 12
160
+ x change to 13
161
+ flag or becomes true // flag ||= true
162
+ flag and becomes false // flag &&= false
163
+ val nullish becomes "dflt" // val ??= "dflt"
164
+ ```
165
+
166
+ Prefix aliases (v1.0.363): `set <target> to <value>` and
167
+ `change <target> to <value>` are the prefix forms of the `set to` /
168
+ `change to` assignment above (the target may also be a member or a numbered
169
+ item):
170
+
171
+ ```plainscript
172
+ set x to 10
173
+ change x to 20
174
+ set data at position 0 to 99
175
+ ```
176
+
177
+ Compound arithmetic assignment:
178
+
179
+ ```plainscript
180
+ n += 1 n -= 2 n *= 3 n /= 4 n %= 5
181
+ n ++= 1 // legacy spelling of +=; still accepted and normalized
182
+ ```
183
+
184
+ Destructuring still uses the word form against a bracket/brace pattern:
185
+
186
+ ```plainscript
187
+ remember [a, b] as pair
188
+ remember { x, y } as point
189
+ ```
190
+
191
+ Typed contracts use a contextual `type` declaration. Field annotations are
192
+ required unless they use `optional`; nested collection annotations and simple
193
+ unions are supported.
194
+
195
+ ```plainscript
196
+ type User
197
+ id is number
198
+ name is text
199
+ active is optional boolean
200
+ tags is list of text
201
+ metadata is dictionary of text
202
+ done
203
+
204
+ make greet(user as User)
205
+ give user.name
206
+ done
207
+ ```
208
+
209
+ The generated function validates `user` before entering its body. This slice
210
+ provides runtime contracts; static inference and compile-time field checking
211
+ are not yet implemented.
212
+
213
+ ## 5. Statements and blocks
214
+
215
+ Blocks open with a keyword line and close with `done` **or** `end`. They are
216
+ equivalent; `end` maps to the same terminator as `done` in the lexer.
217
+
218
+ | Statement | Opens | Closes with |
219
+ |---|---|---|
220
+ | `if <cond>` (with optional `otherwise`, `otherwise if`) | body | `done` |
221
+ | `for each <item> in <list>` | body | `done` |
222
+ | `for index <i> from <a> to <b>` | body | `done` |
223
+ | `while <cond>` | body | `done` |
224
+ | `repeat <n> times` / `repeat with <v> [...]` / `repeat while/until <cond>` | body | `done` |
225
+ | `make <name>(<params>)` (also `define <name>(<params>)`) | body | `done` |
226
+ | `intend <name>(<params>)` | body | `done` |
227
+ | `match <value> against` | `->` cases + `otherwise ->` | `done` |
228
+ | `switch <value> against` | `->` cases | `done` |
229
+ | `try` | body with `recover as <err>` / `finally` clauses | `done` |
230
+ | `web app` / `route <method> "<path>"` / `when someone visits "<path>"` / `listen on <port>` blocks | body | `done` |
231
+ | `database "file.db"` SQL blocks (`query`, `insert`, `update`, `delete`, `execute`) | raw SQL | `done` (or `end`) |
232
+ | `run in parallel` | concurrent statements (each statement's value is awaited and resolved with `Promise.all`, collected in body order) | `done as <name>` |
233
+ | `when "<event>" happens` | body | `done` |
234
+ | `every <interval>` / `schedule "<cron>"` | body | `done` |
235
+ | `websocket server`, `bot`, `whatsapp bot`, `mail transport` | body | `done` |
236
+ | `stream "<file>" as <line>` | body | `done` |
237
+ | `test "<name>"` | `check` / `equals` / `raises` | `done` |
238
+
239
+ A `make` body that contains `yield` compiles to a generator function
240
+ (`function*`). SQL block text is passed through verbatim to SQLite.
241
+
242
+ ## 6. Expressions
243
+
244
+ Recursive-descent parsing with precedence. Member access uses `of`:
245
+
246
+ ```plainscript
247
+ remember user as { profile: { name: "Ada" } }
248
+ show profile of user // user.profile
249
+ show name of profile of user // user.profile.name (chains build inside-out)
250
+ remember items as [10, 20, 30]
251
+ show items at position 1 // items[1]
252
+ show count of items // items.length
253
+ ```
254
+
255
+ Call syntax is plain `name(args)`. `to ... together` declares a function
256
+ (modern verb form of `make`/`define`); calling it is plain `add(a, b)` or
257
+ inline `a + b`.
258
+
259
+ Lambda functions: `(n) -> n * 2` (the arrow body is an expression — no
260
+ `give`/`return` inside it). The block-bodied form uses `do` and ends with
261
+ `done`: `(n) do ... done` with `give` inside. Lambdas can reference
262
+ surrounding variables.
263
+
264
+ ## 7. Built-in functions (STDLIB)
265
+
266
+ The runtime dispatches known call names at compile time; each is documented in
267
+ `compiler/generator.js` in the `STDLIB` table. Highlights:
268
+
269
+ - **I/O & console**: output statements `show` / `print` / `display` / `log`
270
+ (all compile to `console.log(...)`); input statements `ask "<prompt>" as
271
+ <name>` (`prompt` is a synonym). STDLIB functions: `stderr(...)`
272
+ (compiles to `console.error`), `confirm("prompt")` (yes/no prompt →
273
+ boolean), `choose("prompt", options)` (numbered picker → chosen option),
274
+ `clearTerminal()`, `terminalWidth()`, `terminalHeight()`
275
+ - **Math**: `abs`, `round`, `floor`, `ceil`, `sqrt`, `pow`, `min`, `max`,
276
+ `random`; `Math.*` member calls pass through to JavaScript. BigInt helpers:
277
+ `bigInt(n)`, `bigIntAsIntN(width, n)`, `bigIntAsUintN(width, n)`.
278
+ - **Statistics & vectors**: `mean`, `median`, `variance`, `deviation`,
279
+ `dotProduct`, `magnitude`, `normalize`
280
+ - **Randomness**: `randomInteger`, `randomChoice`, `shuffle`, `sample`,
281
+ `weightedChoice`
282
+ - **Strings**: `trim`, `substring`, `split`, `join`, `replace`,
283
+ `regexReplace`, `startsWith`, `endsWith`, `parseInt`, `parseFloat`,
284
+ `parseBoolean`, `characters`
285
+ - **Collections**: `first`, `last`, `push`, plus the functional statements
286
+ `gather each <item> in <list> giving <expr>` (maps the list),
287
+ `filter each <item> in <list> when <cond>` (filters the list),
288
+ `total each <item> in <list> giving <expr>` (sums into the variable) —
289
+ each statement reassigns its collection variable
290
+ - **Files**: `readFile`, `writeFile`, `appendFile`, `fileExists`, `copyFile`,
291
+ `moveFile`, `deleteFile`, `makeFolder`, `listFolder`
292
+ - **Network**: HTTP method expressions `get "url" timeout 5000`,
293
+ `post "url" with {...} headers {...}`; process and job helpers
294
+ `runCommand` (returns `{ ok, code, stdout, stderr }`), `sleep`,
295
+ `run background`, `run in parallel`
296
+ - **Data**: `jsonEncode`, `jsonDecode`, `yamlEncode`, `yamlDecode`,
297
+ `base64Encode`, `base64Decode`, `textToBytes`, `bytesToText`
298
+ - **Async**: `all of [...]`, `any of [...]`, `settled of [...]`
299
+ (combinator form — not `allOf`/`anyOf`/`settledOf`), `withTimeout(x, ms)`
300
+ - **AI**: `chat`, `chatWith`, `embedText`, `embedWith`, `similarity` — all
301
+ provider-based; no LLM is embedded in the runtime
302
+ - **Memoization**: `memoize(fn)` returns a cached wrapper
303
+ - **Regex matching**: `match pattern "..." in text as result`
304
+
305
+ ## 8. Assignment of grammar vs. prose
306
+
307
+ This reference is normative. Where a README, SPEC, or knowledge document
308
+ conflicts with the compiler, the compiler (and this file) win.