@skillstech/thunderlang 1.8.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 (47) hide show
  1. package/CHANGELOG.md +78 -1
  2. package/README.md +5 -0
  3. package/dist/core.cjs +73 -25
  4. package/dist/index.cjs +1230 -519
  5. package/dist/learn.cjs +89 -32
  6. package/package.json +17 -15
  7. package/src/cli-main.mjs +186 -151
  8. package/src/core/ThunderRuntime.cs +22 -1
  9. package/src/core/check.mjs +8 -0
  10. package/src/core/engine-core.mjs +7 -0
  11. package/src/core/engine-values.mjs +2 -0
  12. package/src/core/from-python.mjs +1 -1
  13. package/src/core/go-run.mjs +3 -1
  14. package/src/core/index.mjs +7 -2
  15. package/src/core/java/thunder/ThunderRuntime.java +1 -0
  16. package/src/core/kind.mjs +3 -0
  17. package/src/core/parser.mjs +22 -21
  18. package/src/core/project.mjs +21 -0
  19. package/src/core/runtime-go/thunder_runtime.go +41 -1
  20. package/src/core/rust/thunder_runtime.rs +1 -0
  21. package/src/core/target-csharp.mjs +14 -0
  22. package/src/core/target-go.mjs +14 -0
  23. package/src/core/target-java.mjs +14 -0
  24. package/src/core/target-python.mjs +8 -0
  25. package/src/core/target-rust.mjs +14 -0
  26. package/src/core/target-typescript.mjs +14 -0
  27. package/src/core-changes-fs.mjs +1 -1
  28. package/src/emit.mjs +3 -3
  29. package/src/evidence-words.d.mts +6 -0
  30. package/src/evidence-words.mjs +47 -0
  31. package/src/evidence.mjs +8 -1
  32. package/src/index.d.ts +15 -0
  33. package/src/index.mjs +4 -1
  34. package/src/learn-lessons.mjs +1 -1
  35. package/src/lsp.mjs +110 -0
  36. package/src/mcp.mjs +5 -9
  37. package/src/obligations.d.mts +5 -0
  38. package/src/obligations.mjs +30 -2
  39. package/src/program.d.mts +3 -0
  40. package/src/program.mjs +3 -0
  41. package/src/review.mjs +6 -3
  42. package/src/same.mjs +16 -6
  43. package/src/scan-queries.mjs +2 -1
  44. package/src/symbols.d.mts +23 -0
  45. package/src/symbols.mjs +351 -0
  46. package/src/template.d.mts +31 -0
  47. package/src/template.mjs +189 -0
@@ -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) {
@@ -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,10 +25,15 @@ 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
- 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]),
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]),
30
31
  recordFields: imported.flatMap((r) => [...(r.program.names.recordFields ?? [])]), funcInputs: imported.flatMap((r) => [...(r.program.names.funcInputs ?? [])]),
31
32
  alts: imported.flatMap((r) => [...(r.program.names.alts ?? [])]), altsOf: imported.flatMap((r) => [...(r.program.names.altsOf ?? [])]) } : null;
33
+ }
34
+
35
+ export function compileCore(source, { file = 'main.thunder', imported = [], srcModules = [] } = {}) {
36
+ const seed = seedFrom(imported);
32
37
  const program = parseCore(source, { seed });
33
38
  const { diagnostics, info } = checkCore(program, { imported: imported.map((r) => r.info) });
34
39
  const ok = diagnostics.length === 0;
@@ -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; }
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',
@@ -311,7 +311,7 @@ export class ExprParser {
311
311
  const ak = this.longest(run, (key) => this.names.alts.has(key));
312
312
  if (ak && !this.longest(run, (key) => this.names.known.has(key))) {
313
313
  s.i += ak;
314
- return wrap({ k: 'isAlt', e: l, alt: keyOf(run.slice(0, ak)), text: run.slice(0, ak).map((x) => x.text).join(' '), line });
314
+ return wrap({ k: 'isAlt', e: l, alt: keyOf(run.slice(0, ak)), text: run.slice(0, ak).map((x) => x.text).join(' '), col: run[0].col, line });
315
315
  }
316
316
  }
317
317
  return { k: 'cmp', op: neg ? '!=' : '==', l, r: this.add(s, o), line };
@@ -352,7 +352,7 @@ export class ExprParser {
352
352
  if (!run.length) s.fail(`I expected a field name after "'s".`, null, 'TC108');
353
353
  const k = this.longest(run, (key) => this.names.fields.has(key)) || run.length;
354
354
  s.i -= run.length - k;
355
- e = { k: 'field', obj: e, name: keyOf(run.slice(0, k)), text: run.slice(0, k).map((w) => w.text).join(' '), line: s.line };
355
+ e = { k: 'field', obj: e, name: keyOf(run.slice(0, k)), text: run.slice(0, k).map((w) => w.text).join(' '), col: run[0].col, line: s.line };
356
356
  } else if (isWord(t, 'at') && !isWord(s.peek(1), 'least') && !isWord(s.peek(1), 'most')) {
357
357
  s.next();
358
358
  const key = this.unary(s, { ...o, noAnd: true });
@@ -446,7 +446,7 @@ export class ExprParser {
446
446
  if (!k) s.fail(`I don't know the kind of value "${run.map((x) => x.text).join(' ')}".`, 'Kinds: number, whole number, text, yes/no, money, date, list of …, map of … to …, optional …, or a record you defined with "A … has:".', 'TC306');
447
447
  s.i -= run.length - k;
448
448
  const key = keyOf(run.slice(0, k));
449
- return { k: 'record', name: this.names.records.has(key) ? key : key.replace(/s$/, '') };
449
+ return { k: 'record', name: this.names.records.has(key) ? key : key.replace(/s$/, ''), col: run[0].col, line: s.line };
450
450
  }
451
451
 
452
452
  /** The fields a record is built with: with name "Ann" and balance $10 (none without "with"). */
@@ -572,7 +572,7 @@ export class ExprParser {
572
572
  const rk = this.longest(run.slice(i), (key) => recs.includes(key));
573
573
  if (!rk || i + rk !== run.length) continue;
574
574
  s.i -= run.length - i - rk;
575
- const node = { k: 'new', record: keyOf(run.slice(i, i + rk)), alt, altText: run.slice(0, i).map((x) => x.text).join(' '), fields: this.recordFields(s, line), line };
575
+ const node = { k: 'new', record: keyOf(run.slice(i, i + rk)), alt, altText: run.slice(0, i).map((x) => x.text).join(' '), altCol: run[0].col, recordCol: run[i].col, fields: this.recordFields(s, line), line };
576
576
  return node;
577
577
  }
578
578
  // "a refunded Payment": words before a data type that has alternatives, but not one of them (the checker says so).
@@ -580,7 +580,7 @@ export class ExprParser {
580
580
  const rk = this.longest(run.slice(i), (key) => this.names.altsOf.has(key));
581
581
  if (!rk || i + rk !== run.length) continue;
582
582
  s.i -= run.length - i - rk;
583
- return { k: 'new', record: keyOf(run.slice(i, i + rk)), alt: keyOf(run.slice(0, i)), altText: run.slice(0, i).map((x) => x.text).join(' '), fields: this.recordFields(s, line), line };
583
+ return { k: 'new', record: keyOf(run.slice(i, i + rk)), alt: keyOf(run.slice(0, i)), altText: run.slice(0, i).map((x) => x.text).join(' '), altCol: run[0].col, recordCol: run[i].col, fields: this.recordFields(s, line), line };
584
584
  }
585
585
  }
586
586
  // a record: "a Customer with name "Ann" and balance $10", "a new Customer"
@@ -591,7 +591,7 @@ export class ExprParser {
591
591
  s.i -= run.length - off - recK;
592
592
  const name = keyOf(run.slice(off, off + recK));
593
593
  const fields = this.recordFields(s, line);
594
- const node = { k: 'new', record: name, fields, line };
594
+ const node = { k: 'new', record: name, recordCol: run[off].col, fields, line };
595
595
  if (!fields.length && this.open) this.open.push(node); // a block of "field: value" lines may fill it
596
596
  return node;
597
597
  }
@@ -607,18 +607,19 @@ export class ExprParser {
607
607
  const key = keyOf(run.slice(0, k));
608
608
  const text = run.slice(0, k).map((x) => x.text).join(' ');
609
609
  if (this.names.known.get(key) === 'func') {
610
- if (isSym(s.peek(), '(')) return { k: 'call', name: key, text, args: this.parenArgs(s), line };
611
- if (s.word('with')) return { k: 'call', name: key, text, args: this.withArgs(s), line };
612
- const node = { k: 'call', name: key, text, args: [], line, bare: true };
610
+ const col = run[0].col;
611
+ if (isSym(s.peek(), '(')) return { k: 'call', name: key, text, col, args: this.parenArgs(s), line };
612
+ if (s.word('with')) return { k: 'call', name: key, text, col, args: this.withArgs(s), line };
613
+ const node = { k: 'call', name: key, text, col, args: [], line, bare: true };
613
614
  if (this.open) this.open.push(node); // a block of "input: value" lines may fill it
614
615
  return node;
615
616
  }
616
- return { k: 'name', name: key, text, line };
617
+ return { k: 'name', name: key, text, col: run[0].col, line };
617
618
  }
618
619
  const fk = this.longest(run, (key) => this.names.fields.has(key));
619
- if (fk) { s.i -= run.length - fk; return { k: 'name', name: keyOf(run.slice(0, fk)), text: run.slice(0, fk).map((x) => x.text).join(' '), line, unknown: true }; }
620
+ if (fk) { s.i -= run.length - fk; return { k: 'name', name: keyOf(run.slice(0, fk)), text: run.slice(0, fk).map((x) => x.text).join(' '), col: run[0].col, line, unknown: true }; }
620
621
  // An unknown name: kept whole, so the checker can say exactly what it did not know.
621
- return { k: 'name', name: keyOf(run), text: run.map((x) => x.text).join(' '), line, unknown: true };
622
+ return { k: 'name', name: keyOf(run), text: run.map((x) => x.text).join(' '), col: run[0]?.col, line, unknown: true };
622
623
  }
623
624
  }
624
625
 
@@ -747,7 +748,7 @@ function nameWords(ts, line, what) {
747
748
  if (t.t !== 'word') throw new CoreError(diag('TC105', line, `A name can only use words, but "${show(t)}" is not a word.`));
748
749
  if (RESERVED.has(t.lower)) throw new CoreError(diag('TC202', line, `A name can't contain the word "${t.text}", because it belongs to Thunder.`, `Try a name without "${t.text}".`));
749
750
  }
750
- return { name: keyOf(words), text: words.map((x) => x.text).join(' ') };
751
+ return { name: keyOf(words), text: words.map((x) => x.text).join(' '), col: words[0].col };
751
752
  }
752
753
 
753
754
  function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
@@ -843,8 +844,8 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
843
844
  if (!isSym(ct[ct.length - 1], ':') || ct.length < 2) throw new CoreError(diag('TC108', c.line, 'Under "Depending on", each case is an alternative and a colon, for example: Successful:'));
844
845
  const sub = parseBlock(c.children, ep, names, diagnostics, ctx);
845
846
  if (ct.length === 2 && isWord(ct[0], 'otherwise')) { otherwise = sub; continue; }
846
- const { name, text } = nameWords(ct.slice(0, -1), c.line, 'A case');
847
- cases.push({ alt: name, text, body: sub, line: c.line });
847
+ const { name, text, col } = nameWords(ct.slice(0, -1), c.line, 'A case');
848
+ cases.push({ alt: name, text, col, body: sub, line: c.line });
848
849
  } catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
849
850
  }
850
851
  return { k: 'depending', subject, cases, otherwise, line };
@@ -888,7 +889,7 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
888
889
  }
889
890
  if (w0 === 'to' && isSym(ts[ts.length - 1], ':')) {
890
891
  if (!ctx.top) fail('TC402', 'A "To" block (a function) must be written at the left edge, not inside another block.');
891
- const { name, text } = nameWords(header().slice(1), line, '"To"');
892
+ const { name, text, col } = nameWords(header().slice(1), line, '"To"');
892
893
  const kids = n.children;
893
894
  let params = [];
894
895
  let bodyNodes = kids;
@@ -900,7 +901,7 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
900
901
  r++;
901
902
  }
902
903
  bodyNodes = kids.slice(r);
903
- return { k: 'func', name, text, params, body: parseBlock(bodyNodes, ep, names, diagnostics, { inFunc: true }), line };
904
+ return { k: 'func', name, text, col, params, body: parseBlock(bodyNodes, ep, names, diagnostics, { inFunc: true }), line };
904
905
  }
905
906
  if (w0 === 'receive') fail('TC111', '"Receive" must be the first line inside a "To" block or a "Screen".');
906
907
  if (w0 === 'screen' && isSym(ts[ts.length - 1], ':')) {
@@ -921,7 +922,7 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
921
922
  // makes sure a field is only read where the alternative is known, and that "Depending on" covers every one.
922
923
  if ((w0 === 'a' || w0 === 'an') && isOneOf(ts)) {
923
924
  if (!ctx.top) fail('TC402', 'A data type ("A … is one of:") must be written at the left edge, not inside another block.');
924
- const { name, text } = nameWords(ts.slice(1, -4), line, 'A data type');
925
+ const { name, text, col } = nameWords(ts.slice(1, -4), line, 'A data type');
925
926
  const alts = [];
926
927
  for (const c of n.children) {
927
928
  try {
@@ -941,11 +942,11 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
941
942
  const opt = (t) => (t.k === 'optional' ? t : { k: 'optional', of: t });
942
943
  const fields = [{ name: 'which', text: 'which', type: { k: 'text' }, line, hidden: true }];
943
944
  for (const a of alts) for (const f of a.fields) if (!fields.some((x) => x.name === f.name)) fields.push({ ...f, type: opt(f.type) });
944
- return { k: 'record', name, text, fields, rules: [], alts, line };
945
+ return { k: 'record', name, text, col, fields, rules: [], alts, line };
945
946
  }
946
947
  if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has') && isSym(ts[ts.length - 1], ':')) {
947
948
  if (!ctx.top) fail('TC402', 'A record ("A … has:") must be written at the left edge, not inside another block.');
948
- const { name, text } = nameWords(ts.slice(1, -2), line, 'A record');
949
+ const { name, text, col } = nameWords(ts.slice(1, -2), line, 'A record');
949
950
  const fields = [], rules = [];
950
951
  for (const c of n.children) {
951
952
  try {
@@ -955,7 +956,7 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
955
956
  fields.push({ ...nameWords(c.tokens.slice(0, k), c.line, 'A field'), type: typeOf(ep, c.tokens.slice(k + 1), c.line), line: c.line });
956
957
  } catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
957
958
  }
958
- return { k: 'record', name, text, fields, rules, line };
959
+ return { k: 'record', name, text, col, fields, rules, line };
959
960
  }
960
961
  if (w0 === 'expect') return { ...parseExpect(rest, line, ep), raw: n.raw };
961
962
  if (w0 === 'never') return parseNever(ts, line, ep);
@@ -3,6 +3,7 @@
3
3
  // Source ownership: in a Thunder project the .thunder files are the source. generated/ is a build artifact,
4
4
  // rewritten by every build; it is never read back.
5
5
 
6
+ import { LANGUAGE_VERSION } from './kind.mjs';
6
7
  import { spawnServing } from './serving.mjs';
7
8
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync, rmSync } from 'node:fs';
8
9
  import { join, dirname, relative, resolve, basename } from 'node:path';
@@ -45,8 +46,26 @@ export function parseToml(text) {
45
46
  return out;
46
47
  }
47
48
 
49
+ export { LANGUAGE_VERSION };
50
+
51
+ /**
52
+ * The language a project is written in, from thunder.toml ([project] language = "2"). A project without it is read as
53
+ * the current language. A newer major version is refused with what to do, never read as something else.
54
+ */
55
+ export function projectLanguage(value, where = 'thunder.toml') {
56
+ if (value == null || value === '') return LANGUAGE_VERSION;
57
+ const text = String(value).trim();
58
+ const m = /^(\d+)(?:\.(\d+))?$/.exec(text);
59
+ if (!m) throw new Error(`${where}: language = "${text}" is not a language version. Write language = "${LANGUAGE_VERSION}".`);
60
+ const major = Number(m[1]);
61
+ if (major > Number(LANGUAGE_VERSION)) throw new Error(`${where}: this project is written in Thunder language ${text}, and this compiler speaks language ${LANGUAGE_VERSION}. Install a newer ThunderLang: npm install -g @skillstech/thunderlang`);
62
+ if (major < Number(LANGUAGE_VERSION)) throw new Error(`${where}: language = "${text}" is older than any version Thunder keeps. Programs written before 2.0 are read as language ${LANGUAGE_VERSION}: write language = "${LANGUAGE_VERSION}".`);
63
+ return text;
64
+ }
65
+
48
66
  export function loadProject(root) {
49
67
  const toml = parseToml(readFileSync(join(root, PROJECT_FILE), 'utf8'));
68
+ const language = projectLanguage(toml.project?.language);
50
69
  const build = toml.build ?? {};
51
70
  const target = String(build.target ?? 'python');
52
71
  if (!TARGETS.includes(target)) throw new Error(`thunder.toml: target "${target}" is not supported yet. Thunder Core builds ${TARGETS.map((t) => `${TARGET_NAMES[t] ?? t} (target = "${t}")`).join(', ')}.`);
@@ -54,6 +73,7 @@ export function loadProject(root) {
54
73
  root,
55
74
  name: toml.project?.name ?? basename(root),
56
75
  version: toml.project?.version ?? '0.1.0',
76
+ language,
57
77
  target,
58
78
  src: build.source ?? 'src',
59
79
  tests: build.tests ?? 'tests',
@@ -174,6 +194,7 @@ export function newProject(dir, { force = false } = {}) {
174
194
  [project]
175
195
  name = "${name}"
176
196
  version = "0.1.0"
197
+ language = "${LANGUAGE_VERSION}" # the Thunder language version (docs/spec-2.md)
177
198
 
178
199
  [build]
179
200
  target = "python"
@@ -2285,6 +2285,14 @@ func AddTo(target, value V) V {
2285
2285
  }
2286
2286
  return Add(target, value)
2287
2287
  }
2288
+ // CopyList: a new list with the same items (a watched list is changed on a copy).
2289
+ func CopyList(target V) V {
2290
+ l, ok := target.(*List)
2291
+ if !ok {
2292
+ panic(attrErr(target, "append"))
2293
+ }
2294
+ return &List{append([]V(nil), l.Items...)}
2295
+ }
2288
2296
  func AppendTo(target, value V) {
2289
2297
  l, ok := target.(*List)
2290
2298
  if !ok {
@@ -2482,15 +2490,47 @@ func ApplyOp(op string, a V) V {
2482
2490
  // pyLower / pyUpper: Unicode case mapping, with the special cases JavaScript and Python share.
2483
2491
  func pyLower(s string) string {
2484
2492
  var b strings.Builder
2485
- for _, r := range s {
2493
+ rs := []rune(s)
2494
+ for i, r := range rs {
2486
2495
  if r == 'İ' {
2487
2496
  b.WriteString("i̇")
2488
2497
  continue
2489
2498
  }
2499
+ if r == 'Σ' && finalSigma(rs, i) {
2500
+ b.WriteRune('ς')
2501
+ continue
2502
+ }
2490
2503
  b.WriteRune(unicode.ToLower(r))
2491
2504
  }
2492
2505
  return b.String()
2493
2506
  }
2507
+
2508
+ // finalSigma: Unicode's Final_Sigma rule, as Python and JavaScript apply it: a cased letter comes before (skipping
2509
+ // case-ignorable characters) and none comes after.
2510
+ func finalSigma(rs []rune, i int) bool {
2511
+ cased := func(r rune) bool { return unicode.IsUpper(r) || unicode.IsLower(r) || unicode.IsTitle(r) }
2512
+ ignorable := func(r rune) bool {
2513
+ return unicode.In(r, unicode.Mn, unicode.Me, unicode.Cf, unicode.Lm, unicode.Sk) || r == '\'' || r == '.' || r == ':' || r == '’' || r == '·'
2514
+ }
2515
+ before := false
2516
+ for j := i - 1; j >= 0; j-- {
2517
+ if ignorable(rs[j]) {
2518
+ continue
2519
+ }
2520
+ before = cased(rs[j])
2521
+ break
2522
+ }
2523
+ if !before {
2524
+ return false
2525
+ }
2526
+ for j := i + 1; j < len(rs); j++ {
2527
+ if ignorable(rs[j]) {
2528
+ continue
2529
+ }
2530
+ return !cased(rs[j])
2531
+ }
2532
+ return true
2533
+ }
2494
2534
  func pyUpper(s string) string {
2495
2535
  var b strings.Builder
2496
2536
  for _, r := range s {
@@ -1389,6 +1389,7 @@ pub fn map_get(m: Value, k: Value, dflt: Option<Value>) -> Value {
1389
1389
  }
1390
1390
 
1391
1391
  pub fn add_to(target: Value, value: Value) -> Value { if let List(l) = &target { l.borrow_mut().push(value); return target; } add(target, value) }
1392
+ pub fn copy_list(target: Value) -> Value { if let List(l) = &target { list(l.borrow().clone()) } else { raise(attr_err(&target, "append")) } }
1392
1393
  pub fn append_to(target: Value, value: Value) { if let List(l) = &target { l.borrow_mut().push(value); } else { raise(attr_err(&target, "append")) } }
1393
1394
  pub fn remove_from(target: Value, value: Value) {
1394
1395
  if let Map(d) = &target { if !d.borrow().has(&value) { missing_value(format!("There is no entry for {} to remove.", show_s(&value))) } d.borrow_mut().delete(&value); return; }
@@ -336,6 +336,20 @@ class Gen {
336
336
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
337
337
  const v = this.fresh('v'), t = this.fresh('t');
338
338
  const head = `object ${v} = ${this.x(s.e)}, ${t} = ${this.x(s.target)};`;
339
+ if (s.guard) {
340
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
341
+ const n = this.fresh('new');
342
+ const op = s.k === 'add' ? `T.appendTo(${n}, ${v});` : `T.removeFrom(${n}, ${v});`;
343
+ if (isName) {
344
+ this.line(L, `{ ${head} object ${n} = T.copyList(${t}); ${op}`);
345
+ this.ind++;
346
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: n })}, ${cs(rule.text)}, ${rule.line}, ${n});`, L);
347
+ this.emit(`${id(py)} = ${n}; }`, L);
348
+ this.ind--;
349
+ this.rulesAfter(s, py);
350
+ } else this.line(L, `{ ${head} object ${n} = T.copyList(${t}); ${op} ${this.storeCode(s.target, n)} }`);
351
+ return;
352
+ }
339
353
  let body;
340
354
  if (s.targetKind === 'list') body = s.k === 'add' ? `T.appendTo(${t}, ${v});` : `T.removeFrom(${t}, ${v});`;
341
355
  else if (s.targetKind === 'map') body = `T.removeFrom(${t}, ${v});`;
@@ -378,6 +378,20 @@ class Gen {
378
378
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
379
379
  const v = this.fresh('v'), t = this.fresh('t');
380
380
  const head = `${v} := ${this.x(s.e)}; ${t} := ${this.x(s.target)}`;
381
+ if (s.guard) {
382
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
383
+ const n = this.fresh('new');
384
+ const op = s.k === 'add' ? `T.AppendTo(${n}, ${v})` : `T.RemoveFrom(${n}, ${v})`;
385
+ if (isName) {
386
+ this.line(L, `{ ${head}; ${n} := T.CopyList(${t}); ${op}`);
387
+ this.ind++;
388
+ for (const rule of s.rules) this.emit(`T.Never(${this.x(rule.rule.cond, { subject: n })}, ${goStr(rule.text)}, ${rule.line}, ${n})`, L);
389
+ this.emit(`${this.nameOf(py)} = ${n} }`, L);
390
+ this.ind--;
391
+ this.rulesAfter(s, py);
392
+ } else this.line(L, `{ ${head}; ${n} := T.CopyList(${t}); ${op}; ${this.storeCode(s.target, n)} }`);
393
+ return;
394
+ }
381
395
  let body;
382
396
  if (s.targetKind === 'list') body = s.k === 'add' ? `T.AppendTo(${t}, ${v})` : `T.RemoveFrom(${t}, ${v})`;
383
397
  else if (s.targetKind === 'map') body = `T.RemoveFrom(${t}, ${v})`;
@@ -420,6 +420,20 @@ class Gen {
420
420
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
421
421
  const v = this.fresh('v'), t = this.fresh('t');
422
422
  const head = `Object ${v} = ${this.x(s.e)}, ${t} = ${this.x(s.target)};`;
423
+ if (s.guard) {
424
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
425
+ const n = this.fresh('new');
426
+ const op = s.k === 'add' ? `T.appendTo(${n}, ${v});` : `T.removeFrom(${n}, ${v});`;
427
+ if (isName) {
428
+ this.line(L, `{ ${head} Object ${n} = T.copyList(${t}); ${op}`);
429
+ this.ind++;
430
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: n })}, ${javaString(rule.text)}, ${rule.line}, ${n});`, L);
431
+ this.emit(`${this.lv(py)} = ${n}; }`, L);
432
+ this.ind--;
433
+ this.rulesAfter(s, py);
434
+ } else this.line(L, `{ ${head} Object ${n} = T.copyList(${t}); ${op} ${this.storeCode(s.target, n)} }`);
435
+ return;
436
+ }
423
437
  let body;
424
438
  if (s.targetKind === 'list') body = s.k === 'add' ? `T.appendTo(${t}, ${v});` : `T.removeFrom(${t}, ${v});`;
425
439
  else if (s.targetKind === 'map') body = `T.removeFrom(${t}, ${v});`;
@@ -267,6 +267,14 @@ class Gen {
267
267
  case 'add': case 'remove': {
268
268
  const v = this.x(s.e).c;
269
269
  const target = this.lv(s.target);
270
+ if (s.guard) {
271
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
272
+ const copy = `_copy_${s.line}_`;
273
+ this.emit(`${copy} = list(${target})`, L);
274
+ this.emit(s.k === 'add' ? `${copy}.append(${v})` : `${this.R('remove_from')}(${copy}, ${v})`, L);
275
+ if (s.target.k === 'name') this.assign(s, target, copy); else this.store(s.target, copy, L);
276
+ return;
277
+ }
270
278
  if (s.targetKind === 'list') this.emit(s.k === 'add' ? `${target}.append(${v})` : `${this.R('remove_from')}(${target}, ${v})`, L);
271
279
  else if (s.targetKind === 'map') this.emit(`${this.R('remove_from')}(${target}, ${v})`, L);
272
280
  else if (s.targetKind === 'number') { if (s.target.k === 'name' && s.rules?.length) { this.assign(s, target, `${target} ${s.k === 'add' ? '+' : '-'} ${v}`); return; } this.emit(`${target} ${s.k === 'add' ? '+' : '-'}= ${v}`, L); }
@@ -375,6 +375,20 @@ class Gen {
375
375
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
376
376
  const v = this.fresh('v'), t = this.fresh('t');
377
377
  const head = `let ${v} = ${this.x(s.e)}; let ${t} = ${this.x(s.target)};`;
378
+ if (s.guard) {
379
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
380
+ const n = this.fresh('new');
381
+ const op = s.k === 'add' ? `T::append_to(${n}.clone(), ${v});` : `T::remove_from(${n}.clone(), ${v});`;
382
+ if (isName) {
383
+ this.line(L, `{ ${head} let ${n} = T::copy_list(${t}); ${op}`);
384
+ this.ind++;
385
+ for (const rule of s.rules) this.emit(`T::never(${this.x(rule.rule.cond, { subject: `${n}.clone()` })}, ${rs(rule.text)}, ${rule.line}, ${n}.clone());`, L);
386
+ this.emit(`${id(py)} = ${n}; }`, L);
387
+ this.ind--;
388
+ this.rulesAfter(s, py);
389
+ } else this.line(L, `{ ${head} let ${n} = T::copy_list(${t}); ${op} ${this.storeCode(s.target, n)} }`);
390
+ return;
391
+ }
378
392
  let body;
379
393
  if (s.targetKind === 'list') body = s.k === 'add' ? `T::append_to(${t}, ${v});` : `T::remove_from(${t}, ${v});`;
380
394
  else if (s.targetKind === 'map') body = `T::remove_from(${t}, ${v});`;
@@ -399,6 +399,20 @@ export class Gen {
399
399
  const py = isName ? s.target.ref?.py ?? 'unknown' : null;
400
400
  const v = this.fresh('v'), t = this.fresh('t');
401
401
  const head = `const ${v} = ${this.x(s.e)}, ${t} = ${this.x(s.target)};`;
402
+ if (s.guard) {
403
+ // A list a Never rule watches: change a copy, check it, then keep it (the old list stays if refused).
404
+ const n = this.fresh('new');
405
+ const op = s.k === 'add' ? `T.appendTo(${n}, ${v});` : `T.removeFrom(${n}, ${v});`;
406
+ if (isName) {
407
+ this.line(L, `{ ${head} const ${n} = T.copyList(${t}); ${op}`);
408
+ this.ind++;
409
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: n })}, ${js(rule.text)}, ${rule.line}, ${n});`, L);
410
+ this.emit(`${id(py)} = ${n}; }`, L);
411
+ this.ind--;
412
+ this.rulesAfter(s, py);
413
+ } else this.line(L, `{ ${head} const ${n} = T.copyList(${t}); ${op} ${this.storeCode(s.target, n)} }`);
414
+ return;
415
+ }
402
416
  let body;
403
417
  if (s.targetKind === 'list') body = s.k === 'add' ? `T.appendTo(${t}, ${v});` : `T.removeFrom(${t}, ${v});`;
404
418
  else if (s.targetKind === 'map') body = `T.removeFrom(${t}, ${v});`;
@@ -1,7 +1,7 @@
1
1
  // Reading Thunder Core files from disk for core-changes.mjs (which is browser-safe and reads nothing itself).
2
2
  import { readdirSync, readFileSync, statSync } from 'node:fs';
3
3
  import { join, relative, sep } from 'node:path';
4
- import { isCoreProgram } from './core-changes.mjs';
4
+ import { isCoreProgram } from './core/kind.mjs';
5
5
 
6
6
  const SKIP = new Set(['node_modules', '.git', 'generated', 'data', 'dist', 'build', '.thunder']);
7
7
 
package/src/emit.mjs CHANGED
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
30
30
  };
31
31
  }
32
32
 
33
- export const COMPILER_VERSION = '1.8.0';
33
+ export const COMPILER_VERSION = '2.0.0';
34
34
  export const PROOF_SCHEMA_VERSION = '0.1.0';
35
35
  // Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
36
36
  // Certified to key cert proofs to the compiler. Stable slug per the coordination bus.
@@ -475,7 +475,6 @@ export function semanticDiagnostics(ast) {
475
475
  // ── .intent-proof.json ───────────────────────────────────────────────────────
476
476
  export function buildProof(ast, { sourceFile, sourceHash, targetsRequested, targetsGenerated, diagnostics, generatedAt, origin = 'authored' }) {
477
477
  const passedSemantic = !diagnostics.some((x) => x.level === 'error');
478
- const verifiedText = ast.verify.join(' ').toLowerCase();
479
478
  return {
480
479
  schemaVersion: PROOF_SCHEMA_VERSION,
481
480
  sourceProduct: SOURCE_PRODUCT,
@@ -492,7 +491,8 @@ export function buildProof(ast, { sourceFile, sourceHash, targetsRequested, targ
492
491
  targetsGenerated,
493
492
  guarantees: ast.guarantees.map((g) => ({
494
493
  id: g.id, text: g.statement,
495
- status: g.verify.length > 0 || verifiedText ? 'planned' : 'needs_verification',
494
+ // planned only when this guarantee names its own check; a verify block elsewhere in the mission doesn't count.
495
+ status: g.verify.length > 0 ? 'planned' : 'needs_verification',
496
496
  evidence: g.verify,
497
497
  verifications: g.verifications || [],
498
498
  })),
@@ -0,0 +1,6 @@
1
+ export type EvidenceLevel = 'proven' | 'tested' | 'partial' | 'unverified' | 'violated';
2
+ export const EVIDENCE_LEVELS: EvidenceLevel[];
3
+ export const EVIDENCE_WORDS: Record<EvidenceLevel, { word: string; means: string }>;
4
+ export function evidenceWord(level: string): string | null;
5
+ export function evidenceMeaning(level: string): string | null;
6
+ export function combineEvidence(levels: Iterable<string>): EvidenceLevel;
@@ -0,0 +1,47 @@
1
+ // The five evidence words (roadmap 4.5). Everywhere Thunder tells a person how strongly something is checked, it
2
+ // uses one of these words, with this meaning, and says what the evidence was. Browser-safe, no dependencies.
3
+ //
4
+ // Proven holds for every possible input: checked exhaustively, or proved by a solver
5
+ // Tested passed on the cases that ran, and only on those
6
+ // Partially checked some parts are checked and passed; others are not checked yet (each is named)
7
+ // Unverified nothing checks it yet
8
+ // Violated a check failed: there is a case where it does not hold (the case is shown)
9
+ //
10
+ // The words are about evidence, not about how sure anyone feels. "Tested" never becomes "Proven" because there were
11
+ // many tests. Machine fields keep their own values (an obligation's status is still "verified" in JSON, for the
12
+ // tools that read it); each also carries `evidence`, one of the keys below, and people see the word.
13
+
14
+ export const EVIDENCE_LEVELS = ['proven', 'tested', 'partial', 'unverified', 'violated'];
15
+
16
+ export const EVIDENCE_WORDS = {
17
+ proven: { word: 'Proven', means: 'holds for every possible input: checked exhaustively, or proved by a solver' },
18
+ tested: { word: 'Tested', means: 'passed on the cases that ran, and only on those' },
19
+ partial: { word: 'Partially checked', means: 'some parts are checked and passed; others are not checked yet' },
20
+ unverified: { word: 'Unverified', means: 'nothing checks it yet' },
21
+ violated: { word: 'Violated', means: 'a check failed: there is a case where it does not hold' },
22
+ };
23
+
24
+ /** The word for a level ("Tested"), or null for a level that isn't one of the five. */
25
+ export function evidenceWord(level) {
26
+ return EVIDENCE_WORDS[level]?.word ?? null;
27
+ }
28
+
29
+ /** "Tested: passed on the cases that ran, and only on those". */
30
+ export function evidenceMeaning(level) {
31
+ const w = EVIDENCE_WORDS[level];
32
+ return w ? `${w.word}: ${w.means}` : null;
33
+ }
34
+
35
+ /**
36
+ * The level of something made of parts: a failed part makes it Violated; every part Proven makes it Proven; every
37
+ * part checked makes it Tested; some checked and some not makes it Partially checked; nothing checked, Unverified.
38
+ */
39
+ export function combineEvidence(levels) {
40
+ const ls = [...levels].filter((l) => EVIDENCE_LEVELS.includes(l));
41
+ if (!ls.length) return 'unverified';
42
+ if (ls.includes('violated')) return 'violated';
43
+ if (ls.every((l) => l === 'proven')) return 'proven';
44
+ if (ls.every((l) => l === 'proven' || l === 'tested')) return 'tested';
45
+ if (ls.every((l) => l === 'unverified')) return 'unverified';
46
+ return 'partial';
47
+ }
package/src/evidence.mjs CHANGED
@@ -14,6 +14,12 @@
14
14
  // schema (see the TL->STW proposal on the comms bus). Field names may adjust once STW confirms.
15
15
 
16
16
  import { sha256hex } from './hash.mjs';
17
+ import { combineEvidence } from './evidence-words.mjs';
18
+
19
+ // The evidence word for a claim (docs/evidence-words.md). evidenceType 'tool_verified' names the layer (a deterministic
20
+ // tool made the event), not how strong the evidence is: that is `evidence`, one of proven / tested / partial /
21
+ // unverified / violated. A claim whose named test passed is tested; a planned one (named, not run) is unverified.
22
+ const CLAIM_EVIDENCE = { verified: 'tested', failed: 'violated', planned: 'unverified', needs_verification: 'unverified' };
17
23
 
18
24
  const COUNTED_STATUSES = ['verified', 'failed', 'planned', 'needs_verification'];
19
25
  const stripHash = (h) => String(h || '').replace(/^sha256:/, '');
@@ -36,7 +42,7 @@ function envelope(eventType, evidenceId, ctx = {}, payload = {}) {
36
42
  };
37
43
  }
38
44
 
39
- const safeClaim = (kind, c) => ({ id: c.id, kind, status: c.status, provenBy: c.provenBy || null });
45
+ const safeClaim = (kind, c) => ({ id: c.id, kind, status: c.status, evidence: c.evidenceLevel || CLAIM_EVIDENCE[c.status] || 'unverified', provenBy: c.provenBy || null });
40
46
  function countByStatus(claims) {
41
47
  const counts = Object.fromEntries(COUNTED_STATUSES.map((s) => [s, 0]));
42
48
  for (const c of claims) if (c && Object.prototype.hasOwnProperty.call(counts, c.status)) counts[c.status]++;
@@ -62,6 +68,7 @@ export function toEvidenceEvents(proof) {
62
68
  proofStatus: proof.proofStatus || null,
63
69
  total: claims.length,
64
70
  counts: countByStatus(claims),
71
+ evidence: combineEvidence(claims.map((c) => c.evidence)),
65
72
  freshness: { implementation: fr.implementation || null, dependencies: fr.dependencies ? fr.dependencies.hash || null : null, environment: fr.environment || null },
66
73
  claims,
67
74
  })];
package/src/index.d.ts CHANGED
@@ -464,6 +464,11 @@ export function runTests(ast: IntentAst): TestReport;
464
464
  export interface ObligationResolution {
465
465
  kind: 'guarantee' | 'prohibition'; id?: string; text: string;
466
466
  status: 'verified' | 'failed' | 'declared' | 'unverified';
467
+ /** The evidence word's key (docs/evidence-words.md): passing named cases are 'tested', a failed one 'violated'. */
468
+ evidenceLevel: 'tested' | 'partial' | 'unverified' | 'violated';
469
+ /** "Tested", "Partially checked", "Unverified", or "Violated". */
470
+ evidenceWord: string;
471
+ /** The names of the tests that ran for it (passed or failed). A name kept for compatibility: a passing test is Tested evidence, not a proof. */
467
472
  verify: string[]; kinds: string[]; provenBy: string | null;
468
473
  evidence: Array<{ name: string; pass: boolean | null; cases: number }>;
469
474
  unresolved: string[];
@@ -471,7 +476,15 @@ export interface ObligationResolution {
471
476
  export function resolveObligations(ast: IntentAst): {
472
477
  obligations: ObligationResolution[]; tests: TestReport;
473
478
  verified: number; failed: number; declared: number; unverified: number;
479
+ evidence: { tested: number; partial: number; unverified: number; violated: number };
474
480
  };
481
+ export const CLAIM_STATUS: { verified: 'verified'; failed: 'failed'; declared: 'planned'; unverified: 'needs_verification' };
482
+ export function claimStatus(status: string): 'verified' | 'failed' | 'planned' | 'needs_verification';
483
+ export const EVIDENCE_LEVELS: Array<'proven' | 'tested' | 'partial' | 'unverified' | 'violated'>;
484
+ export const EVIDENCE_WORDS: Record<'proven' | 'tested' | 'partial' | 'unverified' | 'violated', { word: string; means: string }>;
485
+ export function evidenceWord(level: string): string | null;
486
+ export function evidenceMeaning(level: string): string | null;
487
+ export function combineEvidence(levels: Iterable<string>): 'proven' | 'tested' | 'partial' | 'unverified' | 'violated';
475
488
 
476
489
  // Outcome contracts (executable commitments)
477
490
  export const OUTCOME_SCHEMA: string;
@@ -763,6 +776,8 @@ export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPAR
763
776
  export type { ChangedCase, ChangedCases, WriteChange, RulePart } from './write.mjs';
764
777
  export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, proveChange, describeEdit, unifiedDiff } from './write-steps.mjs';
765
778
  export { examplesOf, EXAMPLES_SCHEMA } from './examples.mjs';
779
+ export { templateOf, TEMPLATE_SCHEMA } from './template.mjs';
780
+ export { symbolAt, definitionsAt, referencesAt, renameAt, applyRename } from './symbols.mjs';
766
781
  export { coreChanges, affectedBy, CORE_CHANGES_SCHEMA, AFFECTED_SCHEMA } from './core-changes.mjs';
767
782
  export { withCoreBehaviour } from './core-changes.mjs';
768
783
  export { coreServiceFacts } from './core-services.mjs';