@skillstech/thunderlang 1.7.0 → 2.0.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 (73) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +15 -3
  3. package/dist/core.cjs +303 -41
  4. package/dist/index.cjs +9906 -1387
  5. package/dist/learn.cjs +1420 -93
  6. package/package.json +17 -15
  7. package/src/cli-main.mjs +381 -149
  8. package/src/core/ThunderRuntime.cs +22 -1
  9. package/src/core/check.mjs +320 -6
  10. package/src/core/cli.mjs +60 -8
  11. package/src/core/csharp-run.mjs +2 -2
  12. package/src/core/diagnostics.mjs +9 -0
  13. package/src/core/engine-core.mjs +148 -19
  14. package/src/core/engine-values.mjs +3 -0
  15. package/src/core/engine.mjs +131 -7
  16. package/src/core/from-python.mjs +1 -1
  17. package/src/core/go-run.mjs +5 -3
  18. package/src/core/index.mjs +12 -3
  19. package/src/core/java/thunder/ThunderRuntime.java +1 -0
  20. package/src/core/java-run.mjs +2 -2
  21. package/src/core/kind.mjs +6 -0
  22. package/src/core/lexer.mjs +16 -2
  23. package/src/core/parser.mjs +215 -29
  24. package/src/core/project-root.mjs +18 -0
  25. package/src/core/project.mjs +34 -16
  26. package/src/core/react-run.mjs +2 -2
  27. package/src/core/runtime-go/thunder_runtime.go +310 -2
  28. package/src/core/runtime-python.mjs +365 -3
  29. package/src/core/runtime-typescript.mjs +150 -5
  30. package/src/core/rust/thunder_runtime.rs +1 -0
  31. package/src/core/rust-run.mjs +2 -2
  32. package/src/core/serving.mjs +12 -0
  33. package/src/core/store-format.mjs +110 -0
  34. package/src/core/target-csharp.mjs +14 -0
  35. package/src/core/target-go.mjs +24 -3
  36. package/src/core/target-java.mjs +14 -0
  37. package/src/core/target-python.mjs +46 -5
  38. package/src/core/target-rust.mjs +14 -0
  39. package/src/core/target-typescript.mjs +76 -6
  40. package/src/core/typescript-run.mjs +6 -4
  41. package/src/core-changes-fs.mjs +28 -0
  42. package/src/core-changes.d.mts +67 -0
  43. package/src/core-changes.mjs +603 -0
  44. package/src/core-rules.mjs +146 -0
  45. package/src/core-services.d.mts +4 -0
  46. package/src/core-services.mjs +49 -0
  47. package/src/emit.mjs +3 -3
  48. package/src/evidence-words.d.mts +6 -0
  49. package/src/evidence-words.mjs +47 -0
  50. package/src/evidence.mjs +36 -1
  51. package/src/examples.d.mts +21 -0
  52. package/src/examples.mjs +175 -0
  53. package/src/index.d.ts +19 -0
  54. package/src/index.mjs +8 -1
  55. package/src/learn-lessons.mjs +1 -1
  56. package/src/lsp.mjs +110 -0
  57. package/src/mcp.mjs +47 -12
  58. package/src/obligations.d.mts +5 -0
  59. package/src/obligations.mjs +30 -2
  60. package/src/program.d.mts +7 -0
  61. package/src/program.mjs +7 -0
  62. package/src/read-repo-fs.mjs +2 -1
  63. package/src/review.mjs +75 -6
  64. package/src/same.mjs +16 -6
  65. package/src/scan-queries.mjs +2 -1
  66. package/src/symbols.d.mts +23 -0
  67. package/src/symbols.mjs +351 -0
  68. package/src/system.mjs +1 -1
  69. package/src/template.d.mts +31 -0
  70. package/src/template.mjs +189 -0
  71. package/src/trace-cli.mjs +8 -3
  72. package/src/trace-fs.mjs +29 -3
  73. package/src/trace.mjs +23 -7
@@ -8,16 +8,44 @@
8
8
  //
9
9
  // A program that uses a Python module ("Use csv as csv") is not run here: Thunder never imitates a library.
10
10
 
11
- import { readFileSync } from 'node:fs';
11
+ import { readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs';
12
12
  import { Worker, MessageChannel, receiveMessageOnPort } from 'node:worker_threads';
13
- import { resolve as resolvePath } from 'node:path';
14
- import { ENGINES, pythonModulesUsed, refusalText, runInProcess as runCore, testInProcess as testCore, ThunderErr, PyErr } from './engine-core.mjs';
13
+ import { spawnSync } from 'node:child_process';
14
+ import { createServer } from 'node:http';
15
+ import { resolve as resolvePath, dirname } from 'node:path';
16
+ import { ENGINES, pythonModulesUsed, refusalText, runInProcess as runCore, testInProcess as testCore, engineForServing, ThunderErr, PyErr } from './engine-core.mjs';
17
+ import { asPyErr, explain, NOT_GIVEN } from './engine-values.mjs';
18
+ import { inputValue, dataJson } from './store-format.mjs';
15
19
 
16
20
  export { ENGINES, pythonModulesUsed, refusalText, ThunderErr, PyErr };
17
21
 
18
22
  /** Files a program reads come from disk, relative to the folder it runs in. */
19
23
  const readText = (path, cwd) => readFileSync(resolvePath(cwd, path), 'utf8');
20
24
 
25
+ /**
26
+ * Stored lists (Store … as a list of …) live in files under the folder the program runs in (data/<name>.json).
27
+ * A save writes a new file next to the old one and then renames it, so a file is never left half written.
28
+ */
29
+ export function nodeStore(cwd) {
30
+ return {
31
+ load(file) { try { return readFileSync(resolvePath(cwd, file), 'utf8'); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } },
32
+ save(file, text) {
33
+ const path = resolvePath(cwd, file);
34
+ mkdirSync(dirname(path), { recursive: true });
35
+ writeFileSync(`${path}.saving`, text);
36
+ renameSync(`${path}.saving`, path);
37
+ },
38
+ };
39
+ }
40
+
41
+ // A call to another service (the answer from GET "…") waits for its answer, as every step of a program does: Node's
42
+ // fetch runs in a child process and the engine reads what it printed. The same as compiled TypeScript.
43
+ const FETCH = "let d='';process.stdin.on('data',(c)=>d+=c).on('end',async()=>{const q=JSON.parse(d);try{const r=await fetch(q.url,{method:q.method,headers:q.body==null?{accept:'application/json'}:{accept:'application/json','content-type':'application/json'},body:q.body??undefined,signal:AbortSignal.timeout(30000)});process.stdout.write(JSON.stringify({status:r.status,text:await r.text()}))}catch(e){process.stdout.write(JSON.stringify({error:String(e.cause?.code??e.cause?.message??e.message),name:e.name}))}})";
44
+ export function nodeHttp(method, url, body) {
45
+ const r = spawnSync(process.execPath, ['-e', FETCH], { input: JSON.stringify({ method, url, body }), encoding: 'utf8' });
46
+ try { return JSON.parse(r.stdout); } catch { return { error: 'no answer' }; }
47
+ }
48
+
21
49
  /**
22
50
  * Run a program with the Thunder engine. `entry` is a compileCore result. Returns { status, stdout, stderr }, the way
23
51
  * `python main.py` would end: status 0, or 1 after an error reported in Thunder words. On this thread first (fast, no
@@ -27,23 +55,23 @@ const readText = (path, cwd) => readFileSync(resolvePath(cwd, path), 'utf8');
27
55
  export function runWithEngine({ entry, cwd = process.cwd() } = {}) {
28
56
  const uses = pythonModulesUsed([entry]);
29
57
  if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
30
- const r = runCore({ entry, cwd, deeper: true, readText });
58
+ const r = runCore({ entry, cwd, deeper: true, readText, store: nodeStore(cwd), http: nodeHttp });
31
59
  return r.needsDeeperStack ? runSync({ entry, cwd }) : r;
32
60
  }
33
61
 
34
62
  /** The same, on the calling thread only. */
35
- export function runInProcess({ entry, cwd = process.cwd(), deeper = false } = {}) { return runCore({ entry, cwd, deeper, readText }); }
63
+ export function runInProcess({ entry, cwd = process.cwd(), deeper = false } = {}) { return runCore({ entry, cwd, deeper, readText, store: nodeStore(cwd), http: nodeHttp }); }
36
64
 
37
65
  /** Run every Test block, the way run_tests.py does: one line per test, then the totals. */
38
66
  export function testWithEngine({ results, cwd = process.cwd() } = {}) {
39
67
  const uses = pythonModulesUsed(results);
40
68
  if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
41
- const r = testCore({ results, cwd, deeper: true, readText });
69
+ const r = testCore({ results, cwd, deeper: true, readText, http: nodeHttp });
42
70
  return r.needsDeeperStack ? runSync({ results, cwd, tests: true }) : r;
43
71
  }
44
72
 
45
73
  /** The same, on the calling thread only. */
46
- export function testInProcess({ results, cwd = process.cwd(), deeper = false } = {}) { return testCore({ results, cwd, deeper, readText }); }
74
+ export function testInProcess({ results, cwd = process.cwd(), deeper = false } = {}) { return testCore({ results, cwd, deeper, readText, http: nodeHttp }); }
47
75
 
48
76
  function runSync(job) {
49
77
  const shared = new Int32Array(new SharedArrayBuffer(4));
@@ -61,3 +89,99 @@ function runSync(job) {
61
89
  }
62
90
  }
63
91
 
92
+
93
+ const kindName = { whole: 'a whole number', number: 'a number', money: 'money', text: 'text', bool: 'yes or no', date: 'a date' };
94
+
95
+ /**
96
+ * thunder run --engine thunder for a program with endpoints: run its main part, then answer requests on this machine,
97
+ * one at a time, until stopped (Ctrl+C). The same answers, words, and statuses as compiled Python and TypeScript.
98
+ * Gives back a status only when it could not start.
99
+ */
100
+ export function serveWithEngine({ entry, cwd = process.cwd() } = {}) {
101
+ const ready = engineForServing({ entry, cwd, readText, store: nodeStore(cwd), http: nodeHttp });
102
+ if (!ready.eng) return ready;
103
+ const { eng, mod } = ready;
104
+ if (ready.stdout) process.stdout.write(ready.stdout);
105
+ const own = (s) => !entry.info.imported?.has(s);
106
+ const routes = (entry.info.endpoints ?? []).filter(own).map((f) => {
107
+ const fromPath = new Set(f.endpoint.segments.filter((g) => g.param).map((g) => g.param));
108
+ return { f, method: f.endpoint.method, path: f.endpoint.path, parts: f.endpoint.path.split('/').filter(Boolean), inputs: f.params.map((p) => ({ text: p.text, py: p.py, type: p.type, path: fromPath.has(p.name), dflt: !!p.dflt })) };
109
+ });
110
+ const host = process.env.THUNDER_HOST || '127.0.0.1';
111
+ const port = Number(process.env.THUNDER_PORT || 8080);
112
+ const match = (parts, got) => {
113
+ if (parts.length !== got.length) return null;
114
+ const found = {};
115
+ for (let i = 0; i < parts.length; i++) {
116
+ const m = parts[i].match(/^\{(.+)\}$/);
117
+ if (m) found[m[1].trim().toLowerCase()] = decodeURIComponent(got[i]);
118
+ else if (parts[i] !== got[i]) return null;
119
+ }
120
+ return found;
121
+ };
122
+ const server = createServer((req, res) => {
123
+ const chunks = [];
124
+ req.on('data', (c) => chunks.push(c));
125
+ req.on('end', () => {
126
+ const flush = () => { if (eng.out.length) { process.stdout.write(eng.out.join('')); eng.out = []; } };
127
+ const send = (status, value, plain = false) => {
128
+ let data;
129
+ if (plain) data = JSON.stringify(value);
130
+ else { try { data = dataJson(value); } catch (e) { status = 500; data = JSON.stringify({ problem: explain(asPyErr(e)) }); } }
131
+ flush();
132
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(data) });
133
+ res.end(data);
134
+ process.stdout.write(`${req.method} ${req.url} -> ${status}\n`);
135
+ };
136
+ const problem = (status, text) => send(status, { problem: text }, true);
137
+ const url = new URL(req.url, 'http://localhost');
138
+ const got = url.pathname.split('/').filter(Boolean);
139
+ const query = Object.fromEntries(url.searchParams);
140
+ let chosen = null;
141
+ const methods = [];
142
+ for (const r of routes) {
143
+ const found = match(r.parts, got);
144
+ if (!found) continue;
145
+ methods.push(r.method);
146
+ if (r.method === req.method) chosen = { r, found };
147
+ }
148
+ if (!chosen) return methods.length ? problem(405, `${url.pathname} answers only ${methods.join(', ')}.`) : problem(404, `Nothing here answers ${req.method} ${url.pathname}.`);
149
+ const { r, found } = chosen;
150
+ let body = {};
151
+ const raw = Buffer.concat(chunks).toString('utf8');
152
+ if (raw) {
153
+ try { body = JSON.parse(raw); } catch { return problem(400, "The request's body is not JSON Thunder can read."); }
154
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return problem(400, "The request's body should be a JSON object, written { … }.");
155
+ }
156
+ const args = [];
157
+ try {
158
+ for (const inp of r.inputs) {
159
+ const key = inp.text.toLowerCase();
160
+ const where = `"${inp.text}"`;
161
+ if (inp.path) args.push(inputValue(found[key], inp.type, where, true));
162
+ else if (key in query || (inp.py && inp.py in query)) args.push(inputValue(key in query ? query[key] : query[inp.py], inp.type, where, true));
163
+ else if (inp.text in body || key in body || (inp.py && inp.py in body)) args.push(inputValue(inp.text in body ? body[inp.text] : key in body ? body[key] : body[inp.py], inp.type, where, false));
164
+ else if (inp.dflt) args.push(NOT_GIVEN);
165
+ else if (inp.type.k === 'optional') args.push(null);
166
+ else return problem(400, `${r.method} ${r.path} needs ${inp.text} (${kindName[inp.type.k] ?? inp.type.k}).`);
167
+ }
168
+ } catch (e) { return problem(400, explain(asPyErr(e))); }
169
+ let answer;
170
+ try { answer = eng.answer(mod, r.f, args); } catch (e0) {
171
+ const e = asPyErr(e0);
172
+ if (e.pyType === 'Stop') return problem(e.status ?? 400, explain(e));
173
+ if (e.pyType === 'RuleBroken') return problem(422, explain(e));
174
+ flush();
175
+ process.stderr.write(`${eng.describeError(e)}\n`);
176
+ return problem(500, explain(e));
177
+ }
178
+ try { eng.saveStores(mod); } catch (e0) { const e = asPyErr(e0); process.stderr.write(`${eng.describeError(e)}\n`); return problem(500, explain(e)); }
179
+ return send(answer.status, answer.value);
180
+ });
181
+ });
182
+ server.listen(port, host, () => {
183
+ process.stdout.write(`Thunder is answering on http://${host}:${port}\n${routes.map((r) => ` ${r.method} ${r.path}\n`).join('')}Press Ctrl+C to stop.\n`);
184
+ });
185
+ process.on('SIGINT', () => { process.stdout.write('Stopped answering.\n'); server.close(); process.exit(0); });
186
+ return null;
187
+ }
@@ -543,7 +543,7 @@ class FunctionPrinter {
543
543
  if (f === 'sum' && one) return `the sum of ${paren(this.value(one, item))}`;
544
544
  if (f === 'min' && one) return `the smallest of ${paren(this.value(one, item))}`;
545
545
  if (f === 'max' && one) return `the largest of ${paren(this.value(one, item))}`;
546
- if (f === 'round') nt('Python round() rounds halves to even; Thunder rounds half up');
546
+ if (f === 'round') nt('Python round() rounds halves to even; Thunder rounds halves away from zero');
547
547
  if (f === 'sorted') return this.sorted(e, item);
548
548
  if (f === 'abs' && one) return `the absolute value of ${paren(this.value(one, item))}`;
549
549
  if ((f === 'max' || f === 'min') && args.length >= 2) {
@@ -10,14 +10,14 @@ import { spawnSync } from 'node:child_process';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import { tmpdir } from 'node:os';
12
12
  import { toGo, pythonOnlyUses, id, goStr, goNamespaces as namespaces } from './target-go.mjs';
13
- import { npmRefusals, dotnetRefusals } from './target-typescript.mjs';
13
+ import { npmRefusals, dotnetRefusals, httpRefusals } from './target-typescript.mjs';
14
14
  import { diag } from './diagnostics.mjs';
15
15
 
16
16
  export const GO_RUNTIME = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'runtime-go', 'thunder_runtime.go'), 'utf8');
17
17
 
18
18
  /** TC405 for every Use in a file: Python modules exist only for the Python target. */
19
19
  export function goDiagnostics(result) {
20
- return [...npmRefusals(result.info, 'Go', diag), ...dotnetRefusals(result.info, 'Go', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
20
+ return [...npmRefusals(result.info, 'Go', diag), ...dotnetRefusals(result.info, 'Go', diag), ...httpRefusals(result.info, 'Go', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
21
21
  `"${u.module}" is a Python module, and this program is compiled to Go, which cannot use it.`,
22
22
  'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
23
23
  }
@@ -101,7 +101,9 @@ export function runGo(outDir, { tests = false, cwd = outDir, stdio = 'pipe' } =
101
101
  export function buildGo(outDir, { tests = false } = {}) {
102
102
  const go = goToolchain();
103
103
  if (go.error) return { skipped: go.error };
104
- const r = spawnSync(go.cmd, ['build', '-trimpath', '-o', join(tmpdir(), `thunder-go-check-${process.pid}`), ...(tests ? ['-tags', 'thundertests'] : []), '.'], { cwd: outDir, encoding: 'utf8', env: goEnv() });
104
+ const bin = join(tmpdir(), `thunder-go-check-${process.pid}`);
105
+ const r = spawnSync(go.cmd, ['build', '-trimpath', '-o', bin, ...(tests ? ['-tags', 'thundertests'] : []), '.'], { cwd: outDir, encoding: 'utf8', env: goEnv() });
106
+ rmSync(bin, { force: true }); // only the check matters; the binary is not kept
105
107
  return { ok: r.status === 0, output: `${r.stdout}${r.stderr}`.trim() };
106
108
  }
107
109
 
@@ -25,14 +25,23 @@ export const CORE_VERSION = '0.1.0';
25
25
  * values this file may use (test files see the project's src files); `srcModules` are the Python modules to
26
26
  * import them from.
27
27
  */
28
+ /** The names other files give a file that uses them (a project's tests see its src/ files), for parseCore's seed. */
29
+ export function seedFrom(imported = []) {
30
+ return imported.length ? { known: imported.flatMap((r) => [...r.program.names.known].filter(([, kind]) => kind !== 'var')), fields: imported.flatMap((r) => [...r.program.names.fields]), records: imported.flatMap((r) => [...r.program.names.records]),
31
+ recordFields: imported.flatMap((r) => [...(r.program.names.recordFields ?? [])]), funcInputs: imported.flatMap((r) => [...(r.program.names.funcInputs ?? [])]),
32
+ alts: imported.flatMap((r) => [...(r.program.names.alts ?? [])]), altsOf: imported.flatMap((r) => [...(r.program.names.altsOf ?? [])]) } : null;
33
+ }
34
+
28
35
  export function compileCore(source, { file = 'main.thunder', imported = [], srcModules = [] } = {}) {
29
- const seed = imported.length ? { known: imported.flatMap((r) => [...r.program.names.known].filter(([, kind]) => kind !== 'var')), fields: imported.flatMap((r) => [...r.program.names.fields]), records: imported.flatMap((r) => [...r.program.names.records]),
30
- recordFields: imported.flatMap((r) => [...(r.program.names.recordFields ?? [])]), funcInputs: imported.flatMap((r) => [...(r.program.names.funcInputs ?? [])]) } : null;
36
+ const seed = seedFrom(imported);
31
37
  const program = parseCore(source, { seed });
32
38
  const { diagnostics, info } = checkCore(program, { imported: imported.map((r) => r.info) });
33
39
  const ok = diagnostics.length === 0;
34
40
  const python = ok ? toPython(program, info, { source: file, imports: srcModules }) : null;
35
- return { ok, diagnostics, python, program, info, file };
41
+ // A draft: holes (TC120) are its only problems. It never runs or builds, but nothing in it is wrong yet.
42
+ const holes = diagnostics.filter((d) => d.code === 'TC120');
43
+ const draft = holes.length > 0 && holes.length === diagnostics.length;
44
+ return { ok, diagnostics, python, program, info, file, holes, draft };
36
45
  }
37
46
 
38
47
  export function diagnosticsText(result) {
@@ -989,6 +989,7 @@ public class ThunderRuntime {
989
989
  }
990
990
 
991
991
  public static Object addTo(Object target, Object value) { if (isList(target)) { asList(target).add(value); return target; } return add(target, value); }
992
+ public static Object copyList(Object target) { if (!isList(target)) throw attrErr(target, "append"); return new java.util.ArrayList<Object>(asList(target)); }
992
993
  public static void appendTo(Object target, Object value) { if (!isList(target)) throw attrErr(target, "append"); asList(target).add(value); }
993
994
  public static void removeFrom(Object target, Object value) {
994
995
  if (target instanceof PyDict) { PyDict d = (PyDict) target; if (!d.has(value)) throw MissingValue("There is no entry for " + show(value) + " to remove."); d.delete(value); return; }
@@ -7,7 +7,7 @@ import { writeFileSync, mkdirSync, readFileSync, rmSync, existsSync } from 'node
7
7
  import { join, delimiter } from 'node:path';
8
8
  import { spawnSync } from 'node:child_process';
9
9
  import { toJava, javaTestRunner, javaClassName } from './target-java.mjs';
10
- import { pythonOnlyUses, npmRefusals, dotnetRefusals } from './target-typescript.mjs';
10
+ import { pythonOnlyUses, npmRefusals, dotnetRefusals, storeRefusals, httpRefusals } from './target-typescript.mjs';
11
11
  import { diag } from './diagnostics.mjs';
12
12
 
13
13
  const RUNTIME_DIR = new URL('./java/thunder/', import.meta.url);
@@ -19,7 +19,7 @@ const exportedNames = (r) => [...r.info.records, ...r.info.funcs, ...r.info.cons
19
19
 
20
20
  /** TC405 for every Use in a file: Python modules exist only for the Python target. */
21
21
  export function javaDiagnostics(result) {
22
- return [...npmRefusals(result.info, 'Java', diag), ...dotnetRefusals(result.info, 'Java', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
22
+ return [...npmRefusals(result.info, 'Java', diag), ...dotnetRefusals(result.info, 'Java', diag), ...storeRefusals(result.info, 'Java', diag), ...httpRefusals(result.info, 'Java', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
23
23
  `"${u.module}" is a Python module, and this program is compiled to Java, which cannot use it.`,
24
24
  'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
25
25
  }
package/src/core/kind.mjs CHANGED
@@ -8,6 +8,9 @@
8
8
  // 3. Anything that could be either (an empty file, or "use csv" alone) stays a mission, as before 1.7.
9
9
  // Every mission written before this rule existed starts with a mission keyword, so none changes meaning.
10
10
 
11
+ /** The Thunder language version this compiler speaks (docs/spec-2.md). Every 2.x compiler runs every 2.x program. */
12
+ export const LANGUAGE_VERSION = '2';
13
+
11
14
  /** The keywords a mission file's top-level blocks start with (the mission parser's own list, src/parse.mjs). */
12
15
  export const MISSION_KEYWORDS = new Set([
13
16
  'mission', 'note', 'goal', 'why', 'requires', 'requires_skill', 'demonstrates', 'input', 'output', 'guarantees',
@@ -40,3 +43,6 @@ export function fileKind(source) {
40
43
  if (!first.indented && m && MISSION_KEYWORDS.has(m[1])) return { kind: 'mission', reason: `its first line starts with the mission keyword "${m[1]}"` };
41
44
  return { kind: 'program', reason: `its first line ("${first.text.length > 40 ? `${first.text.slice(0, 40)}…` : first.text}") cannot start a mission` };
42
45
  }
46
+
47
+ /** A Thunder Core program (not a mission) by its path and text: a .thunder file, by the rule above. */
48
+ export const isCoreProgram = (path, source) => /\.thunder$/i.test(path) && fileKind(source ?? '').kind === 'program';
@@ -10,11 +10,11 @@
10
10
  // money $200, $0.10 { t: 'money', text }
11
11
  // percent 20%, 12.5% { t: 'percent', text }
12
12
  // str "Hello, {name}!" (parts: strings and { tokens } holes) { t: 'str', parts }
13
- // sym + - * / ( ) [ ] , : . = == != <> < <= > >= { t: 'sym', text }
13
+ // sym + - * / ( ) [ ] , : . = == != <> < <= > >= ? { t: 'sym', text } (? is a hole: ?number)
14
14
 
15
15
  import { diag, CoreError } from './diagnostics.mjs';
16
16
 
17
- const SYMS = ['==', '!=', '<>', '<=', '>=', '+', '-', '*', '/', '(', ')', '[', ']', ',', ':', '.', '=', '<', '>'];
17
+ const SYMS = ['==', '!=', '<>', '<=', '>=', '+', '-', '*', '/', '(', ')', '[', ']', ',', ':', '.', '=', '<', '>', '?'];
18
18
  const WORD_START = /[\p{L}_]/u;
19
19
  const WORD_CHAR = /[\p{L}\p{N}_]/u;
20
20
 
@@ -22,6 +22,20 @@ const WORD_CHAR = /[\p{L}\p{N}_]/u;
22
22
  export function tokenizeLine(text, line, colOffset = 0) {
23
23
  const toks = [];
24
24
  let i = 0;
25
+ // When someone calls GET /habits/{name}: the path is one token (it may hold {name} parts and other characters).
26
+ const ep = text.match(/^(when)(\s+)(someone)(\s+)(calls)(\s+)([A-Za-z]+)(\s+)(\/\S*?)(\s*)(:)(\s*(#.*)?)$/i);
27
+ if (ep) {
28
+ let col = colOffset + 1;
29
+ const out = [];
30
+ const parts = ep.slice(1, 12);
31
+ parts.forEach((part, k) => {
32
+ if (k === 8) out.push({ t: 'path', text: part, col, line });
33
+ else if (k === 10) out.push({ t: 'sym', text: ':', col, line });
34
+ else if (part && !/^\s*$/.test(part)) out.push({ t: 'word', text: part, lower: part.toLowerCase(), col, line });
35
+ col += part.length;
36
+ });
37
+ return out;
38
+ }
25
39
  const at = (k = 0) => text[i + k];
26
40
  while (i < text.length) {
27
41
  const c = at();