plainscript-lang 1.0.361 → 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.
- package/README.md +383 -55
- package/compiler/bundler.js +78 -3
- package/compiler/cli.js +224 -30
- package/compiler/formatter.js +21 -1
- package/compiler/generator.js +490 -114
- package/compiler/ir.js +61 -0
- package/compiler/lexer.js +42 -7
- package/compiler/lsp.js +234 -0
- package/compiler/parser.js +780 -110
- package/compiler/type-checker.js +246 -0
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +19 -3
- package/docs/GAME-PROMPT.md +3 -3
- package/docs/PLAINSCRIPT-GRAMMAR.md +308 -0
- package/docs/PLAINSCRIPT-SPEC.md +231 -5
- package/docs/index.html +5 -5
- package/docs/website/script.js +1 -1
- package/examples/ai-memory-cli.pln +221 -0
- package/examples/ai-memory.json +1 -0
- package/examples/ai-providers.pln +1 -1
- package/examples/arrays.pln +1 -1
- package/examples/async-errors.pln +1 -1
- package/examples/auth-api.pln +1 -1
- package/examples/auth-sessions.pln +1 -1
- package/examples/basics.pln +1 -1
- package/examples/bots.pln +1 -1
- package/examples/browser-interactive/README.md +1 -1
- package/examples/browser-interactive/src/interactive.pln +1 -1
- package/examples/cache-and-jobs.pln +1 -1
- package/examples/cache-schedule.pln +1 -1
- package/examples/canvas-game/README.md +1 -1
- package/examples/canvas-game/src/game.pln +1 -1
- package/examples/collections.pln +1 -1
- package/examples/compound-assignments.pln +24 -0
- package/examples/concurrency.pln +2 -2
- package/examples/conditions.pln +1 -1
- package/examples/database.pln +1 -1
- package/examples/day2.pln +1 -1
- package/examples/day3.pln +1 -1
- package/examples/deployment.pln +1 -1
- package/examples/email-send.pln +1 -1
- package/examples/error-handling.pln +1 -1
- package/examples/expressions.pln +1 -1
- package/examples/file-manager-cli.pln +51 -0
- package/examples/file-uploads.pln +1 -1
- package/examples/files-and-config.pln +1 -1
- package/examples/files.pln +1 -1
- package/examples/football-backend/app.pln +1 -1
- package/examples/functions.pln +1 -1
- package/examples/hello.pln +1 -1
- package/examples/http-client.pln +1 -1
- package/examples/http.pln +1 -1
- package/examples/id-verification/app.pln +1 -1
- package/examples/interactive-cli.pln +34 -0
- package/examples/javascript-library/README.md +1 -1
- package/examples/javascript-library/src/interop.pln +1 -1
- package/examples/json.pln +1 -1
- package/examples/loops.pln +1 -1
- package/examples/memoize-demo.pln +31 -0
- package/examples/modules/app.pln +1 -1
- package/examples/modules/main.pln +1 -1
- package/examples/modules/math.pln +1 -1
- package/examples/mongo.pln +1 -1
- package/examples/normalization-forms.pln +22 -0
- package/examples/objects.pln +1 -1
- package/examples/ocr.pln +1 -1
- package/examples/packages.pln +1 -1
- package/examples/random-cli.pln +32 -0
- package/examples/record-kinds.pln +1 -1
- package/examples/records.pln +1 -1
- package/examples/rest-api-fetch.pln +1 -1
- package/examples/rest-api.pln +1 -1
- package/examples/run-in-parallel.pln +25 -0
- package/examples/scheduled-tasks.pln +1 -1
- package/examples/search-and-filter.pln +1 -1
- package/examples/server.pln +1 -1
- package/examples/sessions-and-cookies.pln +1 -1
- package/examples/sqlite.pln +1 -1
- package/examples/start.pln +1 -1
- package/examples/stats-cli.pln +29 -0
- package/examples/stdlib.pln +1 -1
- package/examples/string-helpers.pln +23 -0
- package/examples/string-verbs.pln +1 -1
- package/examples/telegram-ai-bot.pln +1 -1
- package/examples/telegram-bot.pln +1 -1
- package/examples/terminal-cli.pln +11 -0
- package/examples/testing.pln +1 -1
- package/examples/three-dimensional/README.md +1 -1
- package/examples/three-dimensional/src/scene.pln +1 -1
- package/examples/todo-cli.pln +98 -0
- package/examples/web-api.pln +1 -1
- package/examples/web-app.pln +1 -1
- package/examples/websocket-server.pln +1 -1
- package/examples/websocket.pln +1 -1
- package/examples/whatsapp-bot/pairing.pln +1 -1
- package/examples/whatsapp-bot/qr.pln +1 -1
- package/package.json +16 -6
package/compiler/bundler.js
CHANGED
|
@@ -118,10 +118,78 @@ function resolveDependencies(entryPath) {
|
|
|
118
118
|
return order;
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
-
//
|
|
122
|
-
function
|
|
121
|
+
// Collects the names a file's own ExportStatements put on its module surface.
|
|
122
|
+
function getExportNames(ast) {
|
|
123
|
+
const names = [];
|
|
124
|
+
for (const node of ast.body) {
|
|
125
|
+
if (node.type !== 'ExportStatement' || node.fromPath) continue;
|
|
126
|
+
names.push(...(node.names || (node.name ? [node.name] : [])));
|
|
127
|
+
}
|
|
128
|
+
return names;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Builds the export surface map for a resolved dependency graph:
|
|
132
|
+
// local import path (as written) -> exported names of that module. Used by
|
|
133
|
+
// namespace imports ("bring all from X as ns") which need the export surface
|
|
134
|
+
// to build live getter objects, and consumed by the shared generation context.
|
|
135
|
+
function buildSurfaces(files) {
|
|
136
|
+
const surfaces = new Map();
|
|
137
|
+
const astByAbs = new Map(files.map(f => [f.absPath, f.ast]));
|
|
138
|
+
|
|
139
|
+
for (const { absPath, ast } of files) {
|
|
140
|
+
const dir = path.dirname(absPath);
|
|
141
|
+
for (const node of ast.body) {
|
|
142
|
+
if (node.type === 'ImportStatement' && node.path && isLocalImportPath(node.path) && node.namespace) {
|
|
143
|
+
const resolvedAbs = resolveImportPath(dir, node.path);
|
|
144
|
+
const depAst = astByAbs.get(resolvedAbs);
|
|
145
|
+
if (depAst) {
|
|
146
|
+
// Union of explicit exports plus auto-exported function declarations
|
|
147
|
+
const explicit = getExportNames(depAst);
|
|
148
|
+
const funcs = depAst.body
|
|
149
|
+
.filter(n => n.type === 'FunctionDeclaration' && n.name)
|
|
150
|
+
.map(n => n.name);
|
|
151
|
+
const hasExplicit = depAst.body.some(n => n.type === 'ExportStatement');
|
|
152
|
+
const surface = hasExplicit ? explicit : [...new Set([...explicit, ...funcs])];
|
|
153
|
+
if (!surfaces.has(absPath)) surfaces.set(absPath, []);
|
|
154
|
+
surfaces.set(node.path, surface);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Propagate re-exported surfaces (export ... from "...") until fixpoint so
|
|
161
|
+
// chains of re-exports resolve too.
|
|
162
|
+
for (let pass = 0; pass <= files.length; pass += 1) {
|
|
163
|
+
let changed = false;
|
|
164
|
+
for (const { absPath, ast } of files) {
|
|
165
|
+
for (const node of ast.body) {
|
|
166
|
+
if (node.type !== 'ExportStatement' || !node.fromPath || !isLocalImportPath(node.fromPath)) continue;
|
|
167
|
+
const resolvedAbs = resolveImportPath(path.dirname(absPath), node.fromPath);
|
|
168
|
+
if (!astByAbs.has(resolvedAbs)) continue;
|
|
169
|
+
const depSurface = surfaces.get(node.fromPath) || [];
|
|
170
|
+
const own = surfaces.get(absPath) || [];
|
|
171
|
+
const merged = [...new Set([...own, ...depSurface])];
|
|
172
|
+
if (merged.length !== own.length) {
|
|
173
|
+
surfaces.set(absPath, merged);
|
|
174
|
+
changed = true;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (!changed) break;
|
|
179
|
+
}
|
|
180
|
+
return surfaces;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Generates JavaScript for a whole resolved dependency graph with ONE shared
|
|
184
|
+
// generation context. This is the single authoritative multi-file pipeline:
|
|
185
|
+
// `bundle`, the CLI's compile stage, and validateSource all go through it so
|
|
186
|
+
// bundled programs behave identically no matter which command produced them.
|
|
187
|
+
function generateBundle(entryPath, options = {}) {
|
|
123
188
|
const files = resolveDependencies(entryPath);
|
|
124
189
|
const context = createGenerationContext(options);
|
|
190
|
+
context.bundled = true;
|
|
191
|
+
context.importSurfaces = buildSurfaces(files);
|
|
192
|
+
|
|
125
193
|
const parts = files.map(({ absPath, ast }) => {
|
|
126
194
|
const relPath = path.relative(process.cwd(), absPath).replace(/\\/g, '/') || path.basename(absPath);
|
|
127
195
|
context.sourceFile = relPath;
|
|
@@ -134,6 +202,13 @@ function bundle(entryPath, options = {}) {
|
|
|
134
202
|
const res = generate(ast, context);
|
|
135
203
|
return typeof res === 'string' ? res : (res && res.code ? res.code : '');
|
|
136
204
|
}).filter(js => js && js.trim() !== '');
|
|
205
|
+
|
|
206
|
+
return { files, context, parts };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Compile all files in dependency order into one JavaScript string.
|
|
210
|
+
function bundle(entryPath, options = {}) {
|
|
211
|
+
const { context, parts } = generateBundle(entryPath, options);
|
|
137
212
|
let js = parts.join('\n');
|
|
138
213
|
if (context.needsAsync) {
|
|
139
214
|
js = wrapAsync(js);
|
|
@@ -154,4 +229,4 @@ function bundle(entryPath, options = {}) {
|
|
|
154
229
|
return js;
|
|
155
230
|
}
|
|
156
231
|
|
|
157
|
-
module.exports = { bundle, resolveDependencies };
|
|
232
|
+
module.exports = { bundle, generateBundle, buildSurfaces, resolveDependencies };
|
package/compiler/cli.js
CHANGED
|
@@ -25,7 +25,9 @@ const { execFileSync } = require('child_process');
|
|
|
25
25
|
const { tokenize } = require('./lexer');
|
|
26
26
|
const { parse } = require('./parser');
|
|
27
27
|
const { generate, createGenerationContext, wrapAsync } = require('./generator');
|
|
28
|
-
const {
|
|
28
|
+
const { serializeIR } = require('./ir');
|
|
29
|
+
const { checkTypes } = require('./type-checker');
|
|
30
|
+
const { bundle, generateBundle, buildSurfaces, resolveDependencies } = require('./bundler');
|
|
29
31
|
const { format } = require('./formatter');
|
|
30
32
|
const { detectDependencies, PACKAGE_MAP, isBuiltinModule, splitPackageSpec } = require('./dependency-detector');
|
|
31
33
|
|
|
@@ -57,6 +59,7 @@ ${clrBold(`PlainScript v${VERSION}`)} ${clrDim('· .pln compiles to readable Nod
|
|
|
57
59
|
${section('START')}
|
|
58
60
|
plainscript new [name] Scaffold a new project with a working app.pln
|
|
59
61
|
plainscript run <file.pln> Install missing deps, compile, execute
|
|
62
|
+
plainscript test [target] Run PlainScript test files
|
|
60
63
|
plainscript start Build src/app.pln and run it from dist/
|
|
61
64
|
|
|
62
65
|
${section('BUILD & CHECK')}
|
|
@@ -67,6 +70,7 @@ ${section('BUILD & CHECK')}
|
|
|
67
70
|
plainscript check [target] Validate imports + generate + JS output (no writes)
|
|
68
71
|
target: a .pln file, a directory, or none = project scan
|
|
69
72
|
--json emits deterministic machine-readable output
|
|
73
|
+
plainscript ir <file.pln> Print the backend-neutral compiler IR as JSON
|
|
70
74
|
plainscript fmt <file.pln> Format a file in place
|
|
71
75
|
|
|
72
76
|
${section('PACKAGES')}
|
|
@@ -224,6 +228,24 @@ function discoverSources(srcDir, outDir, exclude) {
|
|
|
224
228
|
// Project builds compile many files in one pass; per-file stage logs would
|
|
225
229
|
// drown the useful output. Set before batch compilation, reset after.
|
|
226
230
|
let QUIET_STAGES = false;
|
|
231
|
+
let VERBOSE = false;
|
|
232
|
+
// `--quiet` also disables the post-build per-file summary lines; keep the
|
|
233
|
+
// command-line intent separately so a batch build's internal silencing can be
|
|
234
|
+
// lifted without re-enabling chatter the user explicitly asked to mute.
|
|
235
|
+
let REQUESTED_QUIET = false;
|
|
236
|
+
|
|
237
|
+
// `--quiet` swaps out the banner-printing stage with a no-chatter one;
|
|
238
|
+
// `--verbose` always prints the timing detail.
|
|
239
|
+
function stageQuiet(label, fn) {
|
|
240
|
+
return fn();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function stageVerbose(label, fn) {
|
|
244
|
+
const t0 = Date.now();
|
|
245
|
+
const result = fn();
|
|
246
|
+
console.log(`${clrGreen('✓')} ${label} (${Date.now() - t0}ms)`);
|
|
247
|
+
return result;
|
|
248
|
+
}
|
|
227
249
|
|
|
228
250
|
function stage(label, fn) {
|
|
229
251
|
const t0 = Date.now();
|
|
@@ -381,6 +403,11 @@ function compile(filePath, options = {}) {
|
|
|
381
403
|
});
|
|
382
404
|
stage('Building dependency graph', () => files);
|
|
383
405
|
stage('Checking runtime dependencies', () => ensureDependencies(files, true));
|
|
406
|
+
// Shared bundle pipeline: one context across the whole dependency graph so
|
|
407
|
+
// namespace imports get export surfaces and exports defer to end-of-file,
|
|
408
|
+
// exactly as in `bundle()`.
|
|
409
|
+
generationContext.bundled = true;
|
|
410
|
+
generationContext.importSurfaces = buildSurfaces(files);
|
|
384
411
|
const parts = stage('Generating JavaScript', () =>
|
|
385
412
|
files.map(({ absPath: fileAbs, ast }) => {
|
|
386
413
|
const relPath = path.relative(process.cwd(), fileAbs).replace(/\\/g, '/') || path.basename(fileAbs);
|
|
@@ -404,6 +431,58 @@ function compile(filePath, options = {}) {
|
|
|
404
431
|
}
|
|
405
432
|
}
|
|
406
433
|
|
|
434
|
+
// Clean top-level failure surface: uncaught errors and unhandled rejections
|
|
435
|
+
// print one concise line instead of a Node module-loader stack trace, and the
|
|
436
|
+
// most common raw JavaScript runtime errors are translated into PlainScript
|
|
437
|
+
// wording with an actionable hint (v1.0.364). A raised user error keeps its
|
|
438
|
+
// exact message; only JS-native error shapes are translated. Guarded so
|
|
439
|
+
// browser-target builds (no process) and library consumers are untouched.
|
|
440
|
+
// With --sourcemap/-m the (source-mapped) stack is appended, giving real
|
|
441
|
+
// .pln line numbers for runtime failures.
|
|
442
|
+
const cleanErrorPrelude = [
|
|
443
|
+
`if (typeof process !== 'undefined' && typeof process.on === 'function') {`,
|
|
444
|
+
` const __plainTranslate = (m) => {`,
|
|
445
|
+
` const h = m.match(/^(.+?) is not a function$/);`,
|
|
446
|
+
` if (h) {`,
|
|
447
|
+
` const r = h[1];`,
|
|
448
|
+
` const hint = /^[A-Za-z_$][\\w$]*$/.test(r)`,
|
|
449
|
+
` ? 'check that ' + r + ' is defined with "make ' + r + '(...)" before calling it'`,
|
|
450
|
+
` : 'check that the value is a function before calling it';`,
|
|
451
|
+
` return 'Runtime error: ' + r + ' is not a function.\\n hint: ' + hint;`,
|
|
452
|
+
` }`,
|
|
453
|
+
` const pr = m.match(/^Cannot read propert(?:y|ies) of (undefined|null)(?: \\(reading '([^']*)'\\))?$/);`,
|
|
454
|
+
` const prOld = m.match(/^Cannot read propert(?:y|ies) '([^']*)' of (undefined|null)$/);`,
|
|
455
|
+
` if (pr || prOld) {`,
|
|
456
|
+
` const prop = pr ? pr[2] : prOld[1];`,
|
|
457
|
+
` const missing = (pr ? pr[1] : prOld[2]) === 'null' ? 'null' : 'undefined';`,
|
|
458
|
+
` const access = prop != null && prop !== '' ? (/^\\d+$/.test(prop) ? 'x?.[' + prop + ']' : 'x?.' + prop) : 'x?.prop';`,
|
|
459
|
+
` const where = prop != null && prop !== '' ? " '" + prop + "'" : '';`,
|
|
460
|
+
` return 'Runtime error: tried to read' + where + ' from a missing value (' + missing + ').\\n hint: guard the access first (if x is null) or use optional access (' + access + ')';`,
|
|
461
|
+
` }`,
|
|
462
|
+
` if (m.includes(' is not iterable')) {`,
|
|
463
|
+
` return 'Runtime error: a value is not iterable.\\n hint: loops, spread and destructuring need an array, string, or Map/Set';`,
|
|
464
|
+
` }`,
|
|
465
|
+
` if (m.endsWith('is not valid JSON')) {`,
|
|
466
|
+
` return 'Runtime error: invalid JSON - ' + m + '\\n hint: decode untrusted text inside "try ... recover" to handle bad input';`,
|
|
467
|
+
` }`,
|
|
468
|
+
` return null;`,
|
|
469
|
+
` };`,
|
|
470
|
+
` const __plainReport = (e, rejection) => {`,
|
|
471
|
+
` const m = (e && typeof e === 'object' && e.message != null) ? String(e.message) : String(e);`,
|
|
472
|
+
` const t = __plainTranslate(m);`,
|
|
473
|
+
` const head = rejection ? 'Unhandled rejection: ' : '';`,
|
|
474
|
+
` console.error(head + (t !== null ? t : 'Error: ' + m));`,
|
|
475
|
+
` if (process.execArgv && process.execArgv.includes('--enable-source-maps') && e && e.stack) {`,
|
|
476
|
+
` console.error(e.stack);`,
|
|
477
|
+
` }`,
|
|
478
|
+
` process.exit(1);`,
|
|
479
|
+
` };`,
|
|
480
|
+
` process.on('uncaughtException', (e) => __plainReport(e, false));`,
|
|
481
|
+
` process.on('unhandledRejection', (e) => __plainReport(e, true));`,
|
|
482
|
+
`}`,
|
|
483
|
+
].join('\n');
|
|
484
|
+
js = cleanErrorPrelude + '\n' + js;
|
|
485
|
+
|
|
407
486
|
if (options.sourceMap && generationContext.sourceMapBuilder) {
|
|
408
487
|
return {
|
|
409
488
|
code: js,
|
|
@@ -432,6 +511,14 @@ function nodeModulesSearchPaths(entryDir) {
|
|
|
432
511
|
if (parent === dir) break;
|
|
433
512
|
dir = parent;
|
|
434
513
|
}
|
|
514
|
+
// `plainscript run` executes generated code from an OS temporary directory.
|
|
515
|
+
// A staged file outside the compiler project has no ancestor relationship
|
|
516
|
+
// with the compiler's own dependencies, so keep this installation as a
|
|
517
|
+
// fallback after project-local paths have had priority.
|
|
518
|
+
const compilerModules = path.resolve(__dirname, '..', 'node_modules');
|
|
519
|
+
if (fs.existsSync(compilerModules) && !paths.includes(compilerModules)) {
|
|
520
|
+
paths.push(compilerModules);
|
|
521
|
+
}
|
|
435
522
|
return paths;
|
|
436
523
|
}
|
|
437
524
|
|
|
@@ -440,7 +527,12 @@ async function cmdRun(filePath, extraArgs = []) {
|
|
|
440
527
|
console.error('Usage: plainscript run <file.pln>');
|
|
441
528
|
process.exit(1);
|
|
442
529
|
}
|
|
443
|
-
|
|
530
|
+
// Only recognize sourcemap flags before a `--` separator; anything after it
|
|
531
|
+
// belongs to the program itself.
|
|
532
|
+
const __argv2 = process.argv.slice(2);
|
|
533
|
+
const __sep = __argv2.indexOf('--');
|
|
534
|
+
const __cliOnly = __sep === -1 ? __argv2 : __argv2.slice(0, __sep);
|
|
535
|
+
const isSourcemap = __cliOnly.includes('--sourcemap') || __cliOnly.includes('-m') || process.env.PLAINSCRIPT_SOURCEMAP === 'true';
|
|
444
536
|
let js;
|
|
445
537
|
if (isSourcemap) {
|
|
446
538
|
const res = compile(filePath, { sourceMap: true, outputFile: 'out.js' });
|
|
@@ -448,7 +540,7 @@ async function cmdRun(filePath, extraArgs = []) {
|
|
|
448
540
|
} else {
|
|
449
541
|
js = compile(filePath);
|
|
450
542
|
}
|
|
451
|
-
console.log('');
|
|
543
|
+
if (!QUIET_STAGES) console.log('');
|
|
452
544
|
// Execute from the entry file's directory so relative assets and CWD-based
|
|
453
545
|
// behaviour match a direct `node` invocation.
|
|
454
546
|
const entryDir = path.dirname(path.resolve(filePath));
|
|
@@ -469,7 +561,65 @@ async function cmdRun(filePath, extraArgs = []) {
|
|
|
469
561
|
process.exit(1);
|
|
470
562
|
}
|
|
471
563
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
472
|
-
console.log('\nDone.');
|
|
564
|
+
if (!QUIET_STAGES) console.log('\nDone.');
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function discoverTestFiles(root) {
|
|
568
|
+
const files = [];
|
|
569
|
+
function walk(dir) {
|
|
570
|
+
if (!fs.existsSync(dir)) return;
|
|
571
|
+
for (const name of fs.readdirSync(dir).sort()) {
|
|
572
|
+
if (name.startsWith('.')) continue;
|
|
573
|
+
const full = path.join(dir, name);
|
|
574
|
+
const stat = fs.statSync(full);
|
|
575
|
+
if (stat.isDirectory()) walk(full);
|
|
576
|
+
else if (name.endsWith('.test.pln') || name.endsWith('.spec.pln')) files.push(full);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
walk(root);
|
|
580
|
+
return files;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// Run native PlainScript test files through the same real CLI path as users.
|
|
584
|
+
// Explicit files/directories are supported; with no target, conventional
|
|
585
|
+
// tests/**/*.test.pln and tests/**/*.spec.pln files are discovered.
|
|
586
|
+
function cmdTest(target) {
|
|
587
|
+
let files;
|
|
588
|
+
if (target) {
|
|
589
|
+
const abs = path.resolve(target);
|
|
590
|
+
if (!fs.existsSync(abs)) {
|
|
591
|
+
console.error(`Test target not found: ${target}`);
|
|
592
|
+
process.exit(1);
|
|
593
|
+
}
|
|
594
|
+
files = fs.statSync(abs).isDirectory() ? discoverTestFiles(abs) : [abs];
|
|
595
|
+
} else {
|
|
596
|
+
files = discoverTestFiles(path.resolve('tests'));
|
|
597
|
+
if (files.length === 0) files = discoverTestFiles(path.resolve('test'));
|
|
598
|
+
}
|
|
599
|
+
if (files.length === 0) {
|
|
600
|
+
console.error('No PlainScript test files found. Name files *.test.pln or *.spec.pln, or pass a file explicitly.');
|
|
601
|
+
process.exit(1);
|
|
602
|
+
}
|
|
603
|
+
let failed = 0;
|
|
604
|
+
for (const file of files) {
|
|
605
|
+
const relative = path.relative(process.cwd(), file) || file;
|
|
606
|
+
try {
|
|
607
|
+
execFileSync(process.execPath, [__filename, 'run', file], {
|
|
608
|
+
stdio: 'inherit',
|
|
609
|
+
cwd: process.cwd(),
|
|
610
|
+
env: process.env,
|
|
611
|
+
});
|
|
612
|
+
if (!QUIET_STAGES) console.log(`${clrGreen('✓')} ${relative}`);
|
|
613
|
+
} catch (_) {
|
|
614
|
+
failed++;
|
|
615
|
+
console.error(`${clrRed('✗')} ${relative}`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
if (failed) {
|
|
619
|
+
console.error(`\n${failed} of ${files.length} PlainScript test file(s) failed.`);
|
|
620
|
+
process.exit(1);
|
|
621
|
+
}
|
|
622
|
+
if (!QUIET_STAGES) console.log(`\n${files.length} PlainScript test file(s) passed.`);
|
|
473
623
|
}
|
|
474
624
|
|
|
475
625
|
// Compile one entry and write it to outDir with its source name preserved,
|
|
@@ -506,7 +656,7 @@ function buildOne(filePath, srcDir, outDir, options = {}) {
|
|
|
506
656
|
|
|
507
657
|
// `plainscript build <file.pln> -o <out.js>` - compile one entry to an explicit
|
|
508
658
|
// output path (same compilation pipeline as buildOne, including source maps
|
|
509
|
-
// when requested). Valuable for browser payloads such as the v1.0.
|
|
659
|
+
// when requested). Valuable for browser payloads such as the v1.0.363
|
|
510
660
|
// requestAnimationFrame / addEventListener helpers, which are meant to run as
|
|
511
661
|
// a single script tag.
|
|
512
662
|
function writeOneFile(filePath, outputFile) {
|
|
@@ -517,7 +667,12 @@ function writeOneFile(filePath, outputFile) {
|
|
|
517
667
|
}
|
|
518
668
|
const outPath = path.resolve(outputFile);
|
|
519
669
|
|
|
520
|
-
|
|
670
|
+
// Only recognize sourcemap flags before a `--` separator; anything after it
|
|
671
|
+
// belongs to the program itself.
|
|
672
|
+
const __argv2 = process.argv.slice(2);
|
|
673
|
+
const __sep = __argv2.indexOf('--');
|
|
674
|
+
const __cliOnly = __sep === -1 ? __argv2 : __argv2.slice(0, __sep);
|
|
675
|
+
const isSourcemap = __cliOnly.includes('--sourcemap') || __cliOnly.includes('-m') || process.env.PLAINSCRIPT_SOURCEMAP === 'true';
|
|
521
676
|
|
|
522
677
|
let code, mapObject;
|
|
523
678
|
if (isSourcemap) {
|
|
@@ -580,12 +735,12 @@ async function cmdBuild(filePath, outputPath) {
|
|
|
580
735
|
outPath: buildOne(path.join(path.resolve(srcDir), rel), srcDir, outDir),
|
|
581
736
|
}));
|
|
582
737
|
} finally {
|
|
583
|
-
QUIET_STAGES =
|
|
738
|
+
QUIET_STAGES = REQUESTED_QUIET;
|
|
584
739
|
}
|
|
585
740
|
for (const { source, outPath } of built) {
|
|
586
|
-
console.log(`${clrGreen('✓')} ${source} -> ${outPath}`);
|
|
741
|
+
if (!QUIET_STAGES) console.log(`${clrGreen('✓')} ${source} -> ${outPath}`);
|
|
587
742
|
}
|
|
588
|
-
console.log(`\n${built.length} file(s) compiled to ${outDir}/.`);
|
|
743
|
+
if (!QUIET_STAGES) console.log(`\n${built.length} file(s) compiled to ${outDir}/.`);
|
|
589
744
|
}
|
|
590
745
|
|
|
591
746
|
async function cmdStart(extraArgs = []) {
|
|
@@ -631,7 +786,7 @@ done
|
|
|
631
786
|
route get "/api/status"
|
|
632
787
|
reply json
|
|
633
788
|
status is "ok"
|
|
634
|
-
version is "
|
|
789
|
+
version is "${VERSION}"
|
|
635
790
|
done
|
|
636
791
|
done
|
|
637
792
|
|
|
@@ -851,9 +1006,16 @@ function validateSource(absPath) {
|
|
|
851
1006
|
try {
|
|
852
1007
|
// resolveDependencies parses each file too, so a parse error anywhere in
|
|
853
1008
|
// the import graph surfaces here with a "file.pln - Line:Col" prefix.
|
|
854
|
-
const files =
|
|
855
|
-
const
|
|
856
|
-
|
|
1009
|
+
const { context, parts, files } = generateBundle(absPath);
|
|
1010
|
+
const typedAst = { type: 'Program', body: files.flatMap(file => file.ast ? file.ast.body : []) };
|
|
1011
|
+
const typeResult = checkTypes(typedAst);
|
|
1012
|
+
if (typeResult.diagnostics.length > 0) {
|
|
1013
|
+
const details = typeResult.diagnostics.map(item =>
|
|
1014
|
+
`${rel}:${item.range.start.line + 1}:${item.range.start.character + 1} ${item.code} ${item.message}`
|
|
1015
|
+
).join('\n');
|
|
1016
|
+
throw new Error(`Static type checking failed:\n${details}`);
|
|
1017
|
+
}
|
|
1018
|
+
let js = parts.filter(s => s.trim()).join('\n');
|
|
857
1019
|
if (context.needsAsync) js = wrapAsync(js);
|
|
858
1020
|
|
|
859
1021
|
// The compiler must never emit broken JavaScript. Parsing the output with
|
|
@@ -948,7 +1110,7 @@ function cmdCheck(target, json) {
|
|
|
948
1110
|
|
|
949
1111
|
for (const r of results) {
|
|
950
1112
|
if (r.ok) {
|
|
951
|
-
console.log(`${clrGreen('✓')} ${r.file} - ok${clrDim(` (${r.ms}ms)`)}`);
|
|
1113
|
+
if (!QUIET_STAGES) console.log(`${clrGreen('✓')} ${r.file} - ok${clrDim(` (${r.ms}ms)`)}`);
|
|
952
1114
|
} else {
|
|
953
1115
|
console.log(`${clrRed('✗')} ${r.file}`);
|
|
954
1116
|
console.error(r.error);
|
|
@@ -959,7 +1121,7 @@ function cmdCheck(target, json) {
|
|
|
959
1121
|
console.error(`\n${failed.length} of ${results.length} file(s) failed validation.`);
|
|
960
1122
|
process.exit(1);
|
|
961
1123
|
}
|
|
962
|
-
if (results.length > 0) {
|
|
1124
|
+
if (results.length > 0 && !QUIET_STAGES) {
|
|
963
1125
|
console.log(clrGreen(`\n✓ ${results.length} file(s) validated.`));
|
|
964
1126
|
}
|
|
965
1127
|
}
|
|
@@ -988,7 +1150,20 @@ function cmdFmt(filePath) {
|
|
|
988
1150
|
function cmdVersion() {
|
|
989
1151
|
console.log(`PlainScript v${VERSION}`);
|
|
990
1152
|
}
|
|
991
|
-
|
|
1153
|
+
function cmdIR(filePath) {
|
|
1154
|
+
if (!filePath) {
|
|
1155
|
+
console.error('Usage: plainscript ir <file.pln>');
|
|
1156
|
+
process.exit(1);
|
|
1157
|
+
}
|
|
1158
|
+
const absPath = path.resolve(filePath);
|
|
1159
|
+
if (!fs.existsSync(absPath)) {
|
|
1160
|
+
console.error(`File not found: ${filePath}`);
|
|
1161
|
+
process.exit(1);
|
|
1162
|
+
}
|
|
1163
|
+
const source = fs.readFileSync(absPath, 'utf8');
|
|
1164
|
+
const ast = parse(tokenize(source));
|
|
1165
|
+
process.stdout.write(serializeIR(ast));
|
|
1166
|
+
}
|
|
992
1167
|
function cmdHelp() {
|
|
993
1168
|
console.log(HELP);
|
|
994
1169
|
}
|
|
@@ -998,32 +1173,47 @@ function cmdHelp() {
|
|
|
998
1173
|
async function main() {
|
|
999
1174
|
const args = process.argv.slice(2);
|
|
1000
1175
|
|
|
1001
|
-
//
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1176
|
+
// `--` ends CLI flag parsing: everything after it belongs to the compiled
|
|
1177
|
+
// program (`plainscript run app.pln -- --port 8080`). Without this, programs
|
|
1178
|
+
// could never receive their own dash-prefixed arguments because the CLI
|
|
1179
|
+
// consumed every "--" flag anywhere in the list.
|
|
1180
|
+
const sepIdx = args.indexOf('--');
|
|
1181
|
+
const cliArgs = sepIdx === -1 ? args : args.slice(0, sepIdx);
|
|
1182
|
+
const progArgs = sepIdx === -1 ? [] : args.slice(sepIdx + 1);
|
|
1183
|
+
|
|
1184
|
+
// Global flags - recognized anywhere before `--`.
|
|
1185
|
+
const quiet = cliArgs.includes('--quiet');
|
|
1186
|
+
const verbose = cliArgs.includes('--verbose');
|
|
1187
|
+
const json = cliArgs.includes('--json');
|
|
1005
1188
|
if (quiet) { stage = stageQuiet; QUIET_STAGES = true; }
|
|
1006
1189
|
if (verbose) { stage = stageVerbose; VERBOSE = true; }
|
|
1190
|
+
if (quiet) REQUESTED_QUIET = true;
|
|
1191
|
+
|
|
1192
|
+
// Standard version flags - print and exit before any command dispatch.
|
|
1193
|
+
// `--version` anywhere (it is already filtered from program args); `-v`
|
|
1194
|
+
// only as a standalone command so `run app.pln -v` still passes -v through
|
|
1195
|
+
// to the compiled program.
|
|
1196
|
+
if (cliArgs.includes('--version') || (args.length === 1 && args[0] === '-v')) { cmdVersion(); return; }
|
|
1007
1197
|
|
|
1008
1198
|
// Filter flags out to get the positional arguments.
|
|
1009
|
-
const positional =
|
|
1199
|
+
const positional = cliArgs.filter(a => !a.startsWith('--'));
|
|
1010
1200
|
const [, , command, fileArg] = positional.length >= 2
|
|
1011
1201
|
? ['', '', positional[0], positional[1]]
|
|
1012
1202
|
: ['', '', positional[0] || '', ''];
|
|
1013
1203
|
|
|
1014
1204
|
switch (command) {
|
|
1015
|
-
case 'run': await cmdRun(fileArg, positional.slice(2)); break;
|
|
1205
|
+
case 'run': await cmdRun(fileArg, [...positional.slice(2), ...progArgs]); break;
|
|
1016
1206
|
case 'build': {
|
|
1017
|
-
// v1.0.
|
|
1207
|
+
// v1.0.363 - optional -o/--output <path>. "-o" is a single-dash flag, so
|
|
1018
1208
|
// it survives the "--filtered" positional list; pull it out here before
|
|
1019
1209
|
// building the positional file argument for cmdBuild.
|
|
1020
1210
|
let outputPath = null;
|
|
1021
1211
|
const positionalOnly = [];
|
|
1022
|
-
for (let i = 0; i <
|
|
1023
|
-
const a =
|
|
1212
|
+
for (let i = 0; i < cliArgs.length; i++) {
|
|
1213
|
+
const a = cliArgs[i];
|
|
1024
1214
|
if (a === '-o' || a === '--output') {
|
|
1025
|
-
if (i + 1 <
|
|
1026
|
-
outputPath =
|
|
1215
|
+
if (i + 1 < cliArgs.length && !cliArgs[i + 1].startsWith('-')) {
|
|
1216
|
+
outputPath = cliArgs[++i];
|
|
1027
1217
|
} else {
|
|
1028
1218
|
console.error('Usage: plainscript build <file.pln> -o <output.js>');
|
|
1029
1219
|
process.exit(1);
|
|
@@ -1036,15 +1226,19 @@ async function main() {
|
|
|
1036
1226
|
break;
|
|
1037
1227
|
}
|
|
1038
1228
|
case 'check': cmdCheck(fileArg, json); break;
|
|
1229
|
+
case 'ir': cmdIR(fileArg); break;
|
|
1230
|
+
case 'test': cmdTest(fileArg); break;
|
|
1039
1231
|
case 'fmt': cmdFmt(fileArg); break;
|
|
1040
1232
|
case 'new': cmdNew(fileArg); break;
|
|
1041
1233
|
case 'install': cmdInstall(); break;
|
|
1042
|
-
case 'start': await cmdStart(positional.slice(2)); break;
|
|
1234
|
+
case 'start': await cmdStart([...positional.slice(2), ...progArgs]); break;
|
|
1043
1235
|
case 'doctor': cmdDoctor(); break;
|
|
1044
1236
|
case 'add': cmdAdd(fileArg); break;
|
|
1045
1237
|
case 'remove': cmdRemove(fileArg); break;
|
|
1046
1238
|
case 'update': cmdUpdate(); break;
|
|
1047
|
-
case 'version':
|
|
1239
|
+
case 'version':
|
|
1240
|
+
case '--version':
|
|
1241
|
+
case '-v': cmdVersion(); break;
|
|
1048
1242
|
case 'help': cmdHelp(); break;
|
|
1049
1243
|
default:
|
|
1050
1244
|
// Backwards-compatible: treat the first arg as a file to run directly
|
|
@@ -1060,4 +1254,4 @@ async function main() {
|
|
|
1060
1254
|
main().catch((err) => {
|
|
1061
1255
|
console.error(err.message);
|
|
1062
1256
|
process.exit(1);
|
|
1063
|
-
});
|
|
1257
|
+
});
|
package/compiler/formatter.js
CHANGED
|
@@ -10,15 +10,20 @@
|
|
|
10
10
|
const INDENT = ' '; // 4 spaces
|
|
11
11
|
|
|
12
12
|
// Keywords whose line CLOSES a block (printed at depth - 1).
|
|
13
|
-
const DEDENT_WORDS = new Set(['done', 'otherwise', 'recover']);
|
|
13
|
+
const DEDENT_WORDS = new Set(['done', 'end', 'otherwise', 'recover']);
|
|
14
14
|
|
|
15
15
|
// Patterns whose line OPENS a new block (next line indented).
|
|
16
16
|
const INDENT_STARTERS = [
|
|
17
17
|
/^make\s+\S+\s*\(/, // make name(...)
|
|
18
|
+
/^to\s+\S+/, // to add a and b together ...
|
|
18
19
|
/^if\s+/, // if ...
|
|
19
20
|
/^otherwise\b/, // otherwise
|
|
20
21
|
/^for\s+each\s+/, // for each ...
|
|
22
|
+
/^for\s+every\s+/, // for every ... in ...
|
|
23
|
+
/^for\s+index\s+/, // for index i from ... to ...
|
|
21
24
|
/^while\s+/, // while ...
|
|
25
|
+
/^repeat\s+\d+\s+times\b/, // repeat N times ...
|
|
26
|
+
/^repeat\s+(with|while|until)\b/, // repeat with/while/until ...
|
|
22
27
|
/^when\s+someone\s+visits/, // when someone visits ...
|
|
23
28
|
/^when\s+someone\s+(sends|clicks)\b/, // when someone sends / clicks (Telegram)
|
|
24
29
|
/^when\s+socket\b/, // when socket connects / sends message / disconnects (v2.1)
|
|
@@ -37,6 +42,14 @@ const INDENT_STARTERS = [
|
|
|
37
42
|
/^recover\b/, // recover [as name] (v2.1.1 error handling)
|
|
38
43
|
/^retry\s+\d+\s+times\b/, // retry N times ... (v2.1.1 retries)
|
|
39
44
|
/^every\s+\d+\s+(seconds?|minutes?|hours?|days?)\b/, // every 5 minutes (v2.1)
|
|
45
|
+
/^every\s+N\s+(seconds?|minutes?|hours?|days?)\b/, // every N seconds (variable)
|
|
46
|
+
/^every\s+frame\b/, // every frame (v2.1.1 game loop)
|
|
47
|
+
/^after\s+\d+\s+(milliseconds?|seconds?|minutes?|hours?|days?|frames?)\b/, // after 3 seconds
|
|
48
|
+
/^run\s+in\s+parallel\b/, // run in parallel ... done as results
|
|
49
|
+
/^switch\s+\S+\s+against\b/, // switch expr against ... done
|
|
50
|
+
/^match\s+\S+\s+against\b/, // match expr against ... done
|
|
51
|
+
/^stream\s+/, // stream "file" as line ...
|
|
52
|
+
/^test\s+"/, // test "name"
|
|
40
53
|
/^schedule\s+"/, // schedule "..." (v2.1 cron)
|
|
41
54
|
/^websocket\s+server\b/, // websocket server (v2.1)
|
|
42
55
|
/^whatsapp\s+bot\s*$/, // whatsapp bot (v2.1.1 WhatsApp runtime)
|
|
@@ -45,6 +58,13 @@ const INDENT_STARTERS = [
|
|
|
45
58
|
/^send\s+mail\s*$/, // send mail (v2.1)
|
|
46
59
|
/^google\s+oauth\s*$/, // google oauth (v2.1.1 Google sign-in)
|
|
47
60
|
/^query\b/, // query SQL block (v0.6 SQLite DX)
|
|
61
|
+
/^postgres\b/, // postgres "conn" (connection, no body)
|
|
62
|
+
/^mongo\b/, // mongo "conn" (connection, no body)
|
|
63
|
+
/^enable\s+sessions\b/, // enable sessions "secret"
|
|
64
|
+
/^require\s+api\s+key\b/, // require api key from ...
|
|
65
|
+
/^limit\s+requests\b/, // limit requests to N per minute
|
|
66
|
+
/^accept\s+uploads\b/, // accept uploads ...
|
|
67
|
+
/^when\s+[^\s]+(\s+"[^"]*")?\s+happens\b/, // when target "<event>" happens (v2.1.1)
|
|
48
68
|
/^insert\b/, // insert SQL block
|
|
49
69
|
/^update\b/, // update SQL block
|
|
50
70
|
/^delete\b(?!\s*["'])/, // delete SQL block (v2.1.1: NOT `delete "<url>"`,
|