@skillstech/thunderlang 1.6.0 → 1.7.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 (57) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/core.cjs +135 -60
  3. package/dist/index.cjs +394 -89
  4. package/dist/learn.cjs +81 -22
  5. package/package.json +1 -1
  6. package/src/ai.mjs +2 -1
  7. package/src/atlas.mjs +2 -1
  8. package/src/behaviour.mjs +246 -0
  9. package/src/cli-main.mjs +2818 -0
  10. package/src/cli.mjs +9 -2799
  11. package/src/conflict.mjs +0 -0
  12. package/src/core/ThunderDotnet.cs +195 -0
  13. package/src/core/check.mjs +4 -4
  14. package/src/core/cli.mjs +7 -2
  15. package/src/core/csharp-run.mjs +29 -8
  16. package/src/core/diagnostics.mjs +3 -1
  17. package/src/core/engine-core.mjs +20 -1
  18. package/src/core/go-run.mjs +3 -2
  19. package/src/core/java-run.mjs +3 -3
  20. package/src/core/kind.mjs +42 -0
  21. package/src/core/parser.mjs +54 -7
  22. package/src/core/project.mjs +3 -0
  23. package/src/core/react-run.mjs +3 -3
  24. package/src/core/runtime-npm.mjs +79 -0
  25. package/src/core/runtime-react.mjs +2 -1
  26. package/src/core/runtime-typescript.mjs +7 -3
  27. package/src/core/rust-run.mjs +3 -2
  28. package/src/core/target-csharp.mjs +5 -1
  29. package/src/core/target-go.mjs +1 -1
  30. package/src/core/target-python.mjs +1 -1
  31. package/src/core/target-rust.mjs +1 -1
  32. package/src/core/target-typescript.mjs +33 -1
  33. package/src/core/typescript-run.mjs +9 -4
  34. package/src/decision.mjs +2 -1
  35. package/src/distributed.mjs +2 -1
  36. package/src/emit.mjs +2 -2
  37. package/src/focus.mjs +2 -1
  38. package/src/intent-atlas.mjs +4 -3
  39. package/src/mcp.mjs +10 -3
  40. package/src/passport-fs.mjs +2 -1
  41. package/src/passport.mjs +2 -1
  42. package/src/privacy.mjs +2 -1
  43. package/src/read-repo.mjs +3 -2
  44. package/src/report.mjs +3 -2
  45. package/src/review.mjs +2 -1
  46. package/src/select.mjs +2 -1
  47. package/src/semantic-diff.mjs +7 -6
  48. package/src/system.mjs +2 -1
  49. package/src/text-order.mjs +6 -0
  50. package/src/thunderize.mjs +2 -1
  51. package/src/trace-data.mjs +3 -2
  52. package/src/trace.mjs +4 -3
  53. package/src/write-across-cli.mjs +22 -4
  54. package/src/write-across.mjs +2 -1
  55. package/src/write-steps.mjs +14 -3
  56. package/src/write-words.mjs +59 -2
  57. package/syntaxes/thunder.tmLanguage.json +196 -0
@@ -1,3 +1,4 @@
1
+ import { byText } from './text-order.mjs';
1
2
  // Semantic diff over the Intent Graph (founder directive #4, IL owns diff/merge). Diff
2
3
  // two versions of a graph/atlas BY MEANING: nodes added/removed/changed, relationships
3
4
  // added/removed, and , the load-bearing feature , which approvals a change invalidates.
@@ -30,9 +31,9 @@ export function diffGraphs(before, after) {
30
31
  const bn = bNodes.get(id);
31
32
  if (bn && contentKey(bn) !== contentKey(an)) changedNodes.push({ id, type: an.type, before: bn, after: an });
32
33
  }
33
- addedNodes.sort((a, b) => a.id.localeCompare(b.id));
34
- removedNodes.sort((a, b) => a.id.localeCompare(b.id));
35
- changedNodes.sort((a, b) => a.id.localeCompare(b.id));
34
+ addedNodes.sort((a, b) => byText(a.id, b.id));
35
+ removedNodes.sort((a, b) => byText(a.id, b.id));
36
+ changedNodes.sort((a, b) => byText(a.id, b.id));
36
37
 
37
38
  const bRel = new Set((before.relationships || []).map(relKey));
38
39
  const aRel = new Set((after.relationships || []).map(relKey));
@@ -113,12 +114,12 @@ export function mergeGraphs(base, ours, theirs) {
113
114
  const present = inO !== inB ? inO : inT; // ours changed presence -> ours; else theirs
114
115
  if (present) mergedRels.push(r);
115
116
  }
116
- mergedRels.sort((a, b2) => relKey(a).localeCompare(relKey(b2)));
117
+ mergedRels.sort((a, b2) => byText(relKey(a), relKey(b2)));
117
118
 
118
119
  return {
119
120
  schema: 'intent-merge-v1',
120
- merged: { nodes: [...merged.values()].sort((a, b2) => a.id.localeCompare(b2.id)), relationships: mergedRels },
121
- conflicts: conflicts.sort((a, b2) => a.id.localeCompare(b2.id)),
121
+ merged: { nodes: [...merged.values()].sort((a, b2) => byText(a.id, b2.id)), relationships: mergedRels },
122
+ conflicts: conflicts.sort((a, b2) => byText(a.id, b2.id)),
122
123
  clean: conflicts.length === 0,
123
124
  summary: { nodes: merged.size, relationships: mergedRels.length, conflicts: conflicts.length },
124
125
  };
package/src/system.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { byText } from './text-order.mjs';
1
2
  // The whole system: calls across files and services. Browser-safe, zero dependencies.
2
3
  //
3
4
  // After every file is read into the model, each step's call (from its meaning tree, `expr`) is followed through the
@@ -950,5 +951,5 @@ export function callsSummary(model) {
950
951
  if (l.kind === 'sends-to') p.sends++; else p.calls++;
951
952
  if (p.examples.length < 3) p.examples.push({ from: a.id, to: b.id, says: l.kind === 'sends-to' ? `${a.label} sends ${l.method ? `${l.method} ${l.path}` : l.event ? `the event ${l.event}` : `a task`} to ${b.label}` : `${a.label} calls ${b.label}` });
952
953
  }
953
- return [...pairs.values()].sort((x, y) => (y.calls + y.sends) - (x.calls + x.sends) || x.from.localeCompare(y.from) || x.to.localeCompare(y.to));
954
+ return [...pairs.values()].sort((x, y) => (y.calls + y.sends) - (x.calls + x.sends) || byText(x.from, y.from) || byText(x.to, y.to));
954
955
  }
@@ -0,0 +1,6 @@
1
+ // One order for text everywhere in the compiler: by character code, the same on every machine.
2
+ // Not localeCompare: its order depends on the machine's locale (so the same input could sort differently), and its
3
+ // first call loads the whole Unicode collation data (about a quarter of a second at every start).
4
+
5
+ /** Compare two texts by character code: a negative number, 0, or a positive number, for Array.prototype.sort. */
6
+ export const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
@@ -4,6 +4,7 @@
4
4
  import { readCode } from './read.mjs';
5
5
  import { readableLanguage, readingOf } from './read-repo.mjs';
6
6
  import { thunderText, visualFor } from './visual.mjs';
7
+ import { byText } from './text-order.mjs';
7
8
 
8
9
  export const THUNDERIZE_SCHEMA = 'thunderize-v1';
9
10
  export const THUNDER_TEXT_EXT = '.thunder-text';
@@ -49,7 +50,7 @@ export function thunderizeFiles(files, { name = 'app' } = {}) {
49
50
  try { out.push(thunderizeFile(f.path, f.source, language, readingOf(f, language))); }
50
51
  catch (e) { skipped.push({ path: f.path, reason: `could not be read: ${e.message}` }); }
51
52
  }
52
- out.sort((a, b) => a.path.localeCompare(b.path));
53
+ out.sort((a, b) => byText(a.path, b.path));
53
54
  const total = { files: out.length, actions: 0, rules: 0, functions: 0, notReadYet: 0 };
54
55
  for (const f of out) for (const k of ['actions', 'rules', 'functions', 'notReadYet']) total[k] += f.counts[k];
55
56
  const langs = [...new Set(out.map((f) => LANGUAGE_NAMES[f.language] || f.language))].sort();
@@ -1,3 +1,4 @@
1
+ import { byText } from './text-order.mjs';
1
2
  // Thunder Trace, the data side: packages, settings, and tables each repository declares or uses. Browser-safe, no
2
3
  // Node APIs. trace.mjs links them across repositories; this file only reads them, with the line each one is on.
3
4
  //
@@ -126,7 +127,7 @@ export function settingsIn(files) {
126
127
  }
127
128
  }
128
129
  }
129
- return out.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.key.localeCompare(b.key));
130
+ return out.sort((a, b) => byText(a.file, b.file) || a.line - b.line || byText(a.key, b.key));
130
131
  }
131
132
 
132
133
  // ── Tables ─────────────────────────────────────────────────────────────────────────────────────────────
@@ -212,7 +213,7 @@ export function tablesIn(files) {
212
213
  // The same table, file, line, and access once (a statement like UPDATE t … FROM t names it twice).
213
214
  const seen = new Set();
214
215
  return out.filter((t) => { const k = `${t.file}|${t.line}|${t.table}|${t.access}`; if (seen.has(k)) return false; seen.add(k); return true; })
215
- .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.table.localeCompare(b.table));
216
+ .sort((a, b) => byText(a.file, b.file) || a.line - b.line || byText(a.table, b.table));
216
217
  }
217
218
 
218
219
  /** Does this access define the table (rather than use it)? */
package/src/trace.mjs CHANGED
@@ -20,6 +20,7 @@ import { thunderModel } from './model.mjs';
20
20
  import { serviceFacts, segsMatch, GENERIC_PATHS } from './system.mjs';
21
21
  import { sha256 } from './hash.mjs';
22
22
  import { packagesIn, settingsIn, tablesIn, isManifest, LOCAL_VERSION, isGenericSetting, DEFINES } from './trace-data.mjs';
23
+ import { byText } from './text-order.mjs';
23
24
 
24
25
  export const TRACE_SCHEMA = 'thunder-trace-v1';
25
26
  export const TRACE_IMPACT_SCHEMA = 'thunder-trace-impact-v1';
@@ -169,8 +170,8 @@ export function linkRepos(read) {
169
170
  const sortKey = (l) => `${l.from.cite}|${l.to?.cite ?? ''}|${l.kind}|${l.call ?? l.event ?? l.path ?? l.package ?? l.table ?? ''}`;
170
171
  // (A step inside a callback is read for the callback and for the function around it: the same call, once.)
171
172
  const once = (xs) => { const seen = new Set(); return xs.filter((x) => { const k = sortKey(x); if (seen.has(k)) return false; seen.add(k); return true; }); };
172
- links.splice(0, links.length, ...once(links).sort((a, b) => sortKey(a).localeCompare(sortKey(b))));
173
- notLinked.splice(0, notLinked.length, ...once(notLinked).sort((a, b) => sortKey(a).localeCompare(sortKey(b))));
173
+ links.splice(0, links.length, ...once(links).sort((a, b) => byText(sortKey(a), sortKey(b))));
174
+ notLinked.splice(0, notLinked.length, ...once(notLinked).sort((a, b) => byText(sortKey(a), sortKey(b))));
174
175
  const repos = read.map(({ unknown, ...r }) => ({ ...r, unknown: unknown ?? [], packages: pk(r), settings: r.settings ?? [], tables: tb(r) }));
175
176
  const body = { schema: TRACE_SCHEMA, rulesVersion: TRACE_RULES_VERSION, repos, links, notLinked, shared };
176
177
  return { ...body, fingerprint: sha256(JSON.stringify(body)) };
@@ -311,7 +312,7 @@ export function traceImpact(trace, changes) {
311
312
  if (findings.length > found || routes.length || listeners.length || requests.length || publishes.length || c.before) touched.push({ repo: c.repo, file: c.file, status: c.status });
312
313
  }
313
314
  const rank = { high: 0, medium: 1, low: 2 };
314
- findings.sort((a, b) => rank[a.risk] - rank[b.risk] || a.at.cite.localeCompare(b.at.cite));
315
+ findings.sort((a, b) => rank[a.risk] - rank[b.risk] || byText(a.at.cite, b.at.cite));
315
316
  return { schema: TRACE_IMPACT_SCHEMA, traceFingerprint: trace.fingerprint, findings, changed: touched, stopsAt: 1, note: 'Stops at the first hop: callers of the callers are not listed. Links are facts read from code (no code was run); a call whose address is worked out when it runs is not linked.' };
316
317
  }
317
318
 
@@ -6,6 +6,7 @@
6
6
  import { readFileSync, writeFileSync, statSync } from 'node:fs';
7
7
  import { basename, dirname, join, resolve } from 'node:path';
8
8
  import { spawnSync } from 'node:child_process';
9
+ import { behaviourCheck } from './behaviour.mjs';
9
10
  import { collectReadableFiles } from './read-repo-fs.mjs';
10
11
  import { writeRuleAcross, writeAcrossEvidence } from './write-across.mjs';
11
12
  import { buildPassport } from './passport-fs.mjs';
@@ -13,17 +14,18 @@ import { renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
13
14
  import { paint, useColor } from './term.mjs';
14
15
 
15
16
  const USAGE = `usage: thunder write <folder…> --decision <name> --rule <n> --when "<condition>" [--write]
16
- [--run "part: cmd" …] [--passport passport.json] [--purpose "…"] [--json]
17
+ [--run "part: cmd" …] [--passport passport.json] [--purpose "…"] [--behaviour] [--json]
17
18
  Finds every implementation of the rule across the folders (each one part, in any language Thunder reads) and
18
19
  changes its number, comparison, or text value in each of them. Without --write: the plan only. With --write: every
19
20
  implementation changes, or none does. Test files are never edited; those that mention the old value are listed.
20
- Exit codes: 0 done (or planned), 1 refused or a --run command failed, 2 usage.`;
21
+ --behaviour runs each Python implementation before and after on inputs made from its code and lists the answers
22
+ that change (it runs that code). Exit codes: 0 done (or planned), 1 refused or a --run command failed, 2 usage.`;
21
23
 
22
24
  /** Is this `thunder write` call about several folders (rather than one file)? */
23
25
  export function isWriteAcross(argv) {
24
26
  const paths = [];
25
27
  for (let i = 0; i < argv.length; i++) {
26
- if (argv[i].startsWith('--')) { if (!['--write', '--json', '-w'].includes(argv[i])) i++; continue; }
28
+ if (argv[i].startsWith('--')) { if (!['--write', '--json', '-w', '--behaviour', '--behavior'].includes(argv[i])) i++; continue; }
27
29
  paths.push(argv[i]);
28
30
  }
29
31
  if (argv.includes('--edit')) return false;
@@ -45,6 +47,7 @@ export async function writeAcrossMain(argv) {
45
47
  else if (x === '--md-out') a.mdOut = need();
46
48
  else if (x === '--purpose') a.purpose = need();
47
49
  else if (x === '--json') a.json = true;
50
+ else if (x === '--behaviour' || x === '--behavior') a.behaviour = true;
48
51
  else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
49
52
  else if (x === '--answer') { console.error('thunder write: across folders, only a rule\'s condition can change (--when). Each service may answer in its own way (a label on the page, an amount in billing), so one new answer would not fit them all.'); return 2; }
50
53
  else if (x.startsWith('--')) { console.error(`thunder write: there is no option ${x} for a change across folders.\n${USAGE}`); return 2; }
@@ -100,9 +103,17 @@ export async function writeAcrossMain(argv) {
100
103
  }
101
104
  const failed = runs.filter((x) => x.exitCode !== 0);
102
105
 
106
+ // --behaviour: run each Python implementation before and after the change, on inputs made from its code.
107
+ const behaviour = r.ok && a.behaviour ? r.plan.map((p) => {
108
+ const key = `${p.part}/${p.file}`;
109
+ const before = files.find((f) => f.part === p.part && f.path === p.file)?.source ?? '';
110
+ const after = r.files[key] ?? before;
111
+ return { part: p.part, file: p.file, ...behaviourCheck({ path: dirOf(key), name: p.decision, before, after }) };
112
+ }) : [];
113
+
103
114
  if (a.json) {
104
115
  const { files: _f, ...rest } = r;
105
- console.log(JSON.stringify({ ...rest, written, runs, ...(a.passport ? { passport: a.passport } : {}) }, null, 2));
116
+ console.log(JSON.stringify({ ...rest, written, runs, ...(a.behaviour ? { behaviour } : {}), ...(a.passport ? { passport: a.passport } : {}) }, null, 2));
106
117
  return !r.ok || failed.length ? 1 : 0;
107
118
  }
108
119
  const say = (s = '') => console.log(paint(s, useColor()));
@@ -122,6 +133,13 @@ export async function writeAcrossMain(argv) {
122
133
  for (const c of p.change) say(` line ${c.line}, column ${c.column}: ${c.before} -> ${c.after}`);
123
134
  }
124
135
  say('\nChecked by reading each file again: the rule reads as intended, and every other rule and function in each file reads exactly as before.');
136
+ if (behaviour.length) {
137
+ say('\nWhat the change does, run before and after on inputs made from the code (tested on these inputs only; not a proof):');
138
+ for (const b of behaviour) {
139
+ say(` ${b.part}/${b.file} ${b.status === 'changed' ? `${b.changes.length} of ${b.inputs} inputs give a different answer` : b.status === 'same' ? `all ${b.inputs} inputs give the same answer` : b.status === 'broken' ? `the changed file does not load (${b.reason})` : `not run (${b.reason})`}`);
140
+ for (const ex of (b.examples ?? []).slice(0, 3)) say(` ${ex}`);
141
+ }
142
+ }
125
143
  if (r.notIncluded.length) {
126
144
  say('\nNot included (similar, but Thunder cannot tell it is the same rule; check by hand):');
127
145
  for (const n of r.notIncluded) say(` ${n.part}/${n.file}:${n.line} ${n.why}`);
@@ -20,6 +20,7 @@ import { readCode, sayCondition } from './read.mjs';
20
20
  import { tokenize } from './expr.mjs';
21
21
  import { writeRule } from './write.mjs';
22
22
  import { isTestFile } from './trace.mjs';
23
+ import { byText } from './text-order.mjs';
23
24
 
24
25
  export const WRITE_ACROSS_SCHEMA = 'thunder-write-across-v1';
25
26
 
@@ -150,7 +151,7 @@ export function writeRuleAcross(files, { decision, rule, when }) {
150
151
  }
151
152
  result.files[k] = source;
152
153
  }
153
- result.plan.sort((a, b) => where(a).localeCompare(where(b)) || a.line - b.line);
154
+ result.plan.sort((a, b) => byText(where(a), where(b)) || a.line - b.line);
154
155
  if (problems.length) return { ...base, files: {}, plan: [], rule: result.rule, notIncluded: result.notIncluded, tests: result.tests, problems: ['Nothing was changed: every implementation must be written exactly, or none is.', ...problems] };
155
156
  return { ...result, ok: true };
156
157
  }
@@ -30,7 +30,7 @@
30
30
  // A patch that fails its proof is never returned as written.
31
31
  //
32
32
  // Deterministic and browser-safe (no Node APIs): it edits text and reads it; it never runs the code it edits.
33
- import { thunderTree, thunderStep, looksThunder } from './write-words.mjs';
33
+ import { thunderTree, thunderStep, looksThunder, unknownName, unknownNameReason } from './write-words.mjs';
34
34
  import { readCode } from './read.mjs';
35
35
  import { readableLanguage } from './read-repo.mjs';
36
36
  import { parseExpr, parseStatement, parseStatementSpans, renderExpr, renderStatement, sameExpr, normalizeExpr, nodesOf, sayFull, blockEnd } from './meaning.mjs';
@@ -275,11 +275,18 @@ function exprFrom(input, language, what = 'expression') {
275
275
  if (looksThunder(input) && words().tree) return words().tree;
276
276
  for (const l of PARSE_ORDER(language)) {
277
277
  const t = parseExpr(input, l);
278
- if (t && t.kind !== 'code' && !misreadIs(t)) return adapt(t, language);
278
+ if (t && t.kind !== 'code' && !misreadIs(t)) return known(adapt(t, language), language);
279
279
  }
280
280
  if (words().tree) return words().tree;
281
+ if (said?.unknown) refuse(`The ${what} "${input}" could not be read: ${said.error}`);
281
282
  refuse(`The ${what} "${input}" could not be read${said?.error ? ` (${said.error})` : ''}. Write it in Thunder's words, for example "days is more than 10 and not member's vip", or as code.`);
282
283
  }
284
+ /** A tree written as code, refused when it uses a name the code does not have (it would fail when run). */
285
+ function known(tree, language) {
286
+ const word = unknownName(tree, language, wordsSource, wordsScope);
287
+ if (word) refuse(`It cannot be written: ${unknownNameReason(word, wordsScope)}`);
288
+ return tree;
289
+ }
283
290
  /** Adapt a tree read in another language to this file's spelling (== in JavaScript is ===, quotes, true/True). */
284
291
  function adapt(tree, language) {
285
292
  const t = cloneShape(tree);
@@ -303,7 +310,8 @@ function statementFrom(input, language) {
303
310
  const t = parseStatement(input, l);
304
311
  if (t && t.kind !== 'code') {
305
312
  const a = adapt(t, language);
306
- try { renderStatement(a, language); return a; } catch { /* try the next reading */ }
313
+ try { renderStatement(a, language); } catch { continue; /* try the next reading */ }
314
+ return known(a, language);
307
315
  }
308
316
  }
309
317
  refuse(`The step "${input}" could not be read as one statement.`);
@@ -1240,6 +1248,9 @@ function opAddFunction(state, edit) {
1240
1248
  if (language === 'go' && inputs.some((p) => !p.type)) refuse('Go needs a type for every input.');
1241
1249
  const ctx = { language, source, item: { name, line: 1 } };
1242
1250
  if (language === 'go' && edit.returns) ctx.goResults = edit.returns;
1251
+ // The new function's names are its inputs and the file's names.
1252
+ wordsScope = `${name}(${inputs.map((p) => p.name).join(', ')})`;
1253
+ wordsSource = `${wordsScope}\n${source}`;
1243
1254
  const nodes = (edit.steps || []).map((s) => stepSpec(s, { ...ctx, source: `${source}\nfunc ${name}() (${edit.returns || ''}) {}` }));
1244
1255
  if (!nodes.length) refuse('A new function needs at least one step.');
1245
1256
  const unit = indentUnit(source, language);
@@ -51,6 +51,25 @@ const lit = (type, value, raw) => ({ kind: 'literal', type, value, raw });
51
51
  const NULL_RAW = { python: 'None', go: 'nil', typescript: 'null', javascript: 'null' };
52
52
 
53
53
  class Unsaid extends Error {}
54
+ class Unknown extends Error { constructor(word) { super(word); this.word = word; } }
55
+
56
+ /** The function's inputs, from its signature (the first parentheses in `scope`). */
57
+ export function inputsOf(scope) {
58
+ const code = codeOnly(scope || ''), open = code.indexOf('(');
59
+ if (open < 0) return [];
60
+ let depth = 0, end = open;
61
+ for (; end < code.length; end++) { if (code[end] === '(') depth++; else if (code[end] === ')' && --depth === 0) break; }
62
+ const out = [];
63
+ for (const part of code.slice(open + 1, end).split(',')) {
64
+ const id = part.replace(/^\s*[*&.]*\s*/, '').match(/^[A-Za-z_]\w*/)?.[0];
65
+ if (id && !KEYWORDS.has(id) && id !== 'self' && id !== 'cls' && !out.includes(id)) out.push(id);
66
+ }
67
+ return out;
68
+ }
69
+ const unknownWord = (word, scope) => {
70
+ const inputs = inputsOf(scope);
71
+ return `"${word}" is not a name in this function or file${inputs.length ? `; its inputs are ${inputs.map((i) => `"${nameWords(i) || i}"`).join(', ')}` : ''}. Use one of its names, or add an input first (addInput).`;
72
+ };
54
73
  const no = (why) => { throw new Unsaid(why); };
55
74
 
56
75
  /** A Core expression (core/parser.mjs) as a meaning tree for `language`. */
@@ -69,8 +88,10 @@ function toTree(n, language, names) {
69
88
  case 'bool': return lit('bool', n.v, py ? (n.v ? 'True' : 'False') : String(n.v));
70
89
  case 'nothing': return lit('null', null, NULL_RAW[language]);
71
90
  case 'name': {
72
- const id = names.get(n.name) ?? (/^[A-Za-z_]\w*$/.test(n.name) ? n.name : null);
73
- if (!id) no(`"${n.name}" (no name in the file is said that way)`);
91
+ // Only a name the code already has: a word that is no name in the function or the file is refused, never
92
+ // written as a new name the code would fail on.
93
+ const id = names.get(n.name);
94
+ if (!id) throw new Unknown(n.name);
74
95
  return nm(id);
75
96
  }
76
97
  case 'field': case 'dot': {
@@ -152,6 +173,7 @@ export function thunderTree(text, language, source, scope = '') {
152
173
  try { parsed = parseThunder(text, source, scope); } catch (e) { return { error: String(e.message).replace(/^Line 1: /, '').split('\n')[0] }; }
153
174
  try { return { tree: toTree(parsed.node, language, parsed.names) }; } catch (e) {
154
175
  if (e instanceof Unsaid) return { error: `Thunder write cannot say ${e.message} in ${language} yet.` };
176
+ if (e instanceof Unknown) return { error: unknownWord(e.word, scope), unknown: e.word };
155
177
  throw e;
156
178
  }
157
179
  }
@@ -180,3 +202,38 @@ export function thunderStep(text, language, source, scope = '') {
180
202
  }
181
203
  return null;
182
204
  }
205
+
206
+ // Names every program in the language has without writing them: built-in functions, types, and globals.
207
+ const BUILTINS = {
208
+ python: 'abs all any ascii bin bool bytearray bytes callable chr dict dir divmod enumerate filter float format frozenset getattr globals hasattr hash hex id int isinstance issubclass iter len list locals map max min next object oct open ord pow print range repr reversed round set setattr slice sorted str sum super tuple type vars zip Exception ValueError TypeError KeyError IndexError RuntimeError AttributeError NotImplementedError StopIteration LookupError ArithmeticError ZeroDivisionError OSError NotImplemented Ellipsis __name__ __file__',
209
+ typescript: 'Math JSON Object Array String Number Boolean Date Error TypeError RangeError Promise Map Set WeakMap Symbol BigInt RegExp console parseInt parseFloat isNaN isFinite undefined NaN Infinity globalThis window document process require module exports',
210
+ go: 'len cap append make new copy delete panic recover print println close complex real imag min max clear error string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 float32 float64 bool byte rune any iota fmt errors strings strconv',
211
+ };
212
+ BUILTINS.javascript = BUILTINS.typescript;
213
+
214
+ /**
215
+ * The first name in `tree` that the code does not have (not in the file, not built in), or null. Names the step
216
+ * itself introduces are allowed: assignment and declaration targets, loop variables, and a function's own inputs.
217
+ */
218
+ export function unknownName(tree, language, source, scope = '') {
219
+ const known = new Set(BUILTINS[language]?.split(' ') ?? []);
220
+ // The function's own code counts as code even where the file is read as text around it (a docstring example).
221
+ for (const text of [codeOnly(source), codeOnly(scope)]) for (const m of text.matchAll(/\b[A-Za-z_][A-Za-z0-9_]*\b/g)) known.add(m[0]);
222
+ for (const k of KEYWORDS) known.add(k);
223
+ const bound = new Set();
224
+ const all = [];
225
+ const walk = (n) => {
226
+ if (Array.isArray(n)) { n.forEach(walk); return; }
227
+ if (!n || typeof n !== 'object') return;
228
+ if (n.kind === 'lambda' || n.kind === 'code') { bound.add('*'); return; }
229
+ if (n.kind === 'name') all.push(n.name);
230
+ if ((n.kind === 'assign' || n.kind === 'declare') && n.target?.kind === 'name') bound.add(n.target.name);
231
+ if (n.kind === 'declare' && typeof n.name === 'string') bound.add(n.name);
232
+ if (n.kind === 'loop') for (const v of [n.variable, n.var, n.name, n.target]) { if (typeof v === 'string') bound.add(v); else if (v?.kind === 'name') bound.add(v.name); }
233
+ for (const [k, v] of Object.entries(n)) if (k !== 'raw' && v && typeof v === 'object') walk(v);
234
+ };
235
+ walk(tree);
236
+ if (bound.has('*')) return null;
237
+ return all.find((id) => !known.has(id) && !bound.has(id)) ?? null;
238
+ }
239
+ export const unknownNameReason = (word, scope) => unknownWord(word, scope);
@@ -0,0 +1,196 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
3
+ "name": "ThunderLang",
4
+ "scopeName": "source.thunder",
5
+ "fileTypes": [
6
+ "thunder",
7
+ "tl",
8
+ "intent"
9
+ ],
10
+ "patterns": [
11
+ {
12
+ "include": "#comment"
13
+ },
14
+ {
15
+ "include": "#string"
16
+ },
17
+ {
18
+ "include": "#core-definition"
19
+ },
20
+ {
21
+ "include": "#core-keyword"
22
+ },
23
+ {
24
+ "include": "#block-keyword"
25
+ },
26
+ {
27
+ "include": "#field-value"
28
+ },
29
+ {
30
+ "include": "#field-type"
31
+ },
32
+ {
33
+ "include": "#operator"
34
+ },
35
+ {
36
+ "include": "#core-value"
37
+ },
38
+ {
39
+ "include": "#core-soft"
40
+ },
41
+ {
42
+ "include": "#number"
43
+ },
44
+ {
45
+ "include": "#type"
46
+ }
47
+ ],
48
+ "repository": {
49
+ "comment": {
50
+ "match": "#.*$",
51
+ "name": "comment.line.number-sign.thunder"
52
+ },
53
+ "string": {
54
+ "name": "string.quoted.double.thunder",
55
+ "begin": "\"",
56
+ "end": "\"",
57
+ "patterns": [
58
+ {
59
+ "match": "\\\\.",
60
+ "name": "constant.character.escape.thunder"
61
+ },
62
+ {
63
+ "match": "\\{[^{}\"]+\\}",
64
+ "name": "variable.other.interpolation.thunder"
65
+ }
66
+ ]
67
+ },
68
+ "block-keyword": {
69
+ "comment": "A line-leading keyword introduces a block or a field (indentation-structured).",
70
+ "match": "^\\s*(mission|use|goal|why|because|requires|inputs?|outputs?|guarantees?|never|constraints?|assumptions?|risks|target|style|verify|errors|examples|service|api|event|database|architecture|selection|title|for|persona|customer|problem|evidence|opportunity|outcome_contract|outcome|metric|scope|include|exclude|non_goal|owner|unknown|question|assumption|experience|pattern|decision|rule|default|when|return|command|on|compensate|notify|preserve|lifecycle|state|transition|from|to|terminal|always|eventually|until|conflict|options|between|resolve_by|resolution|choose|approval|capability|interface|provides|slo|release|result|learning|component|artifact|test|case|scenario|given|expect|events|data|waiver|note|implements|covers|variant|token|classification|purpose|retention|basis|baseline|window|direction|includes|measures|value|kind|ref|version|status|date|reason|approved_by|by|at|decision|expires|before|idempotency_key|timeout|retry|backoff|confidence|source|recover|follows|actor|accessible|responsive|asked_of|resolve|validate)\\b",
71
+ "captures": {
72
+ "1": {
73
+ "name": "keyword.control.thunder"
74
+ }
75
+ }
76
+ },
77
+ "field-value": {
78
+ "comment": "A record or a call written as a block: buy price: $20.00 (every word of the name is the field).",
79
+ "match": "^\\s+([a-z][a-z0-9_]*(?: [a-z][a-z0-9_]*)*)(:)(?=\\s+\\S)",
80
+ "captures": {
81
+ "1": {
82
+ "name": "variable.other.property.thunder"
83
+ },
84
+ "2": {
85
+ "name": "punctuation.separator.key-value.thunder"
86
+ }
87
+ }
88
+ },
89
+ "field-type": {
90
+ "comment": "A typed field: name: Type (optionally List<Type>).",
91
+ "match": "\\b([a-z][A-Za-z0-9_.]*)\\s*(:)\\s*([A-Z][A-Za-z0-9]*(?:<[^>]+>)?)",
92
+ "captures": {
93
+ "1": {
94
+ "name": "variable.other.member.thunder"
95
+ },
96
+ "2": {
97
+ "name": "punctuation.separator.thunder"
98
+ },
99
+ "3": {
100
+ "name": "entity.name.type.thunder"
101
+ }
102
+ }
103
+ },
104
+ "operator": {
105
+ "comment": "Expression operators used in decision conditions (when ...).",
106
+ "match": "(>=|<=|==|!=|>|<|=|\\+|\\-|\\*|/|%)|\\b(and|or|not|in)\\b",
107
+ "name": "keyword.operator.thunder"
108
+ },
109
+ "number": {
110
+ "match": "\\b\\d+(?:\\.\\d+)?%?\\b",
111
+ "name": "constant.numeric.thunder"
112
+ },
113
+ "type": {
114
+ "comment": "PascalCase identifiers are entities/types in ThunderLang.",
115
+ "match": "\\b([A-Z][A-Za-z0-9]*)(?:<[^>]+>)?\\b",
116
+ "name": "entity.name.type.thunder"
117
+ },
118
+ "core-definition": {
119
+ "comment": "Thunder Core: 'To calculate discount:' names a function; 'A Trade has:' names a record.",
120
+ "patterns": [
121
+ {
122
+ "match": "^\\s*(To)\\s+([a-z][\\w ]*?)(:)\\s*$",
123
+ "captures": {
124
+ "1": {
125
+ "name": "keyword.control.thunder"
126
+ },
127
+ "2": {
128
+ "name": "entity.name.function.thunder"
129
+ },
130
+ "3": {
131
+ "name": "punctuation.separator.thunder"
132
+ }
133
+ }
134
+ },
135
+ {
136
+ "match": "^\\s*(An?)\\s+([A-Z]\\w*(?: [A-Z]\\w*)*)\\s+(has)(:)",
137
+ "captures": {
138
+ "1": {
139
+ "name": "keyword.control.thunder"
140
+ },
141
+ "2": {
142
+ "name": "entity.name.type.thunder"
143
+ },
144
+ "3": {
145
+ "name": "keyword.other.thunder"
146
+ },
147
+ "4": {
148
+ "name": "punctuation.separator.thunder"
149
+ }
150
+ }
151
+ },
152
+ {
153
+ "match": "^\\s+([A-Z][\\w ]*?)\\s+(is)\\s+((?:an? )?(?:optional )?(?:text|money|number|whole number|date|yes/no|yes or no|list|map)\\b[\\w ]*)",
154
+ "captures": {
155
+ "1": {
156
+ "name": "variable.other.property.thunder"
157
+ },
158
+ "2": {
159
+ "name": "keyword.operator.thunder"
160
+ },
161
+ "3": {
162
+ "name": "support.type.thunder"
163
+ }
164
+ }
165
+ }
166
+ ]
167
+ },
168
+ "core-keyword": {
169
+ "comment": "Thunder Core statement words at the start of a line.",
170
+ "match": "^\\s*(Set|say|Say|print|Keep|Increase|Decrease|Add|Remove|Sort|Reverse|When|If|Otherwise(?: when| if)?|For each|Repeat(?: while| until)?|Stop with|Give(?: back)?|Receive|Test|Expect|Use|Never allow)\\b",
171
+ "captures": {
172
+ "1": {
173
+ "name": "keyword.control.thunder"
174
+ }
175
+ }
176
+ },
177
+ "core-soft": {
178
+ "comment": "Small words that join a statement's parts.",
179
+ "match": "\\b(to|with|by|from|as|at least|at most|more than|less than|each|while|until|times|of|where|sorted|descending|be|fail|this fails|joined with|split at|replacing|starts with|ends with|contains)\\b",
180
+ "name": "keyword.other.thunder"
181
+ },
182
+ "core-value": {
183
+ "comment": "Money, percents, and yes / no / nothing.",
184
+ "patterns": [
185
+ {
186
+ "match": "-?\\$\\d[\\d,]*(?:\\.\\d+)?",
187
+ "name": "constant.numeric.money.thunder"
188
+ },
189
+ {
190
+ "match": "\\b(yes|no|nothing|true|false)\\b",
191
+ "name": "constant.language.thunder"
192
+ }
193
+ ]
194
+ }
195
+ }
196
+ }