@skillstech/thunderlang 0.4.2 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +64 -0
- package/dist/core.cjs +8389 -4510
- package/dist/index.cjs +7218 -3842
- package/package.json +1 -1
- package/src/anchor.d.mts +12 -0
- package/src/anchor.mjs +127 -0
- package/src/cli.mjs +234 -42
- package/src/codegen.mjs +27 -9
- package/src/core.d.ts +19 -0
- package/src/core.mjs +16 -0
- package/src/emit.mjs +1 -1
- package/src/expr.mjs +42 -1
- package/src/human-contract.d.mts +20 -0
- package/src/human-contract.mjs +213 -0
- package/src/index.d.ts +23 -0
- package/src/index.mjs +11 -0
- package/src/lift.mjs +7 -0
- package/src/mcp.mjs +139 -54
- package/src/obligations.d.mts +9 -0
- package/src/obligations.mjs +35 -0
- package/src/plain-contract.d.mts +30 -0
- package/src/plain-contract.mjs +339 -0
- package/src/promote.d.mts +6 -0
- package/src/promote.mjs +179 -0
- package/src/read-repo-fs.mjs +29 -0
- package/src/read-repo.d.mts +21 -0
- package/src/read-repo.mjs +139 -0
- package/src/read.d.mts +29 -0
- package/src/read.mjs +1620 -0
- package/src/review-atlas.d.mts +19 -0
- package/src/review-atlas.mjs +136 -0
- package/src/steps.d.mts +2 -0
- package/src/steps.mjs +297 -0
- package/src/target-elixir.mjs +79 -0
- package/src/target-go.mjs +95 -0
- package/src/target-kotlin.mjs +91 -0
- package/src/target-rust.mjs +99 -0
- package/src/target-scala.mjs +93 -0
- package/src/target-types.mjs +97 -0
- package/src/target-util.mjs +1 -59
- package/src/testing.mjs +12 -9
- package/src/thunder-repo.mjs +96 -0
- package/src/translate.d.mts +5 -0
- package/src/translate.mjs +126 -0
- package/src/write.d.mts +24 -0
- package/src/write.mjs +263 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Browser-safe decision translator: renders each decision as a readable, typed function in a
|
|
2
|
+
// target language. It uses the SAME expression translators (exprTo*) and the SAME input-type
|
|
3
|
+
// inference as the executable target adapters (target-*.mjs), minus their test harness, so what
|
|
4
|
+
// a reader sees here matches what `thunder test <file> --target <lang>` compiles and runs.
|
|
5
|
+
// Deterministic, no AI, no Node imports.
|
|
6
|
+
import { exprToJs, exprToPython, exprToGo, exprToRust, exprToCSharp, exprToJava } from './expr.mjs';
|
|
7
|
+
import { inputNames, inferInputTypes, strLit } from './target-types.mjs';
|
|
8
|
+
|
|
9
|
+
const RELATIONAL = /^(<=|>=|<|>)$/;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Example values decide an input's type first (as the target adapters do). With no example value
|
|
13
|
+
* for an input, fall back to how the rules use it: a relational comparison means number, a bare
|
|
14
|
+
* operand of and/or/not means bool, anything else stays string.
|
|
15
|
+
*/
|
|
16
|
+
function typesFor(ast, dec) {
|
|
17
|
+
const names = inputNames(dec);
|
|
18
|
+
const types = inferInputTypes(ast, dec);
|
|
19
|
+
const hasExample = (n) => (ast.tests || []).some((t) => t.name === dec.name && (t.cases || []).some((c) => (c.given || {})[n] != null));
|
|
20
|
+
// A declared type (`amount: number`, as the reader and typed contracts emit) wins outright.
|
|
21
|
+
const declared = {};
|
|
22
|
+
for (const raw of dec.inputs || []) {
|
|
23
|
+
const m = String(raw).match(/^\s*(\w+)\s*:\s*(number|boolean|bool|string)\s*$/);
|
|
24
|
+
if (m) declared[m[1]] = m[2] === 'boolean' ? 'bool' : m[2];
|
|
25
|
+
}
|
|
26
|
+
for (const n of names) {
|
|
27
|
+
if (declared[n]) { types[n] = declared[n]; continue; }
|
|
28
|
+
if (hasExample(n)) continue;
|
|
29
|
+
let guess = 'string';
|
|
30
|
+
for (const r of dec.rules || []) {
|
|
31
|
+
const toks = String(r.when || '').split(/\s+|(?=[()])|(?<=[()])/).filter(Boolean);
|
|
32
|
+
toks.forEach((t, i) => {
|
|
33
|
+
if (t !== n) return;
|
|
34
|
+
if (RELATIONAL.test(toks[i - 1] || '') || RELATIONAL.test(toks[i + 1] || '')) guess = 'number';
|
|
35
|
+
else if (guess === 'string' && !/^(==|!=|in)$/.test(toks[i + 1] || '') && !/^(==|!=)$/.test(toks[i - 1] || '')) guess = 'bool';
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
types[n] = guess;
|
|
39
|
+
}
|
|
40
|
+
return types;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const tryExpr = (fn, when, inputs, fallback) => { try { return fn(when, { inputs }); } catch { return fallback; } };
|
|
44
|
+
|
|
45
|
+
const LANGS = {
|
|
46
|
+
typescript: {
|
|
47
|
+
label: 'TypeScript',
|
|
48
|
+
types: { number: 'number', bool: 'boolean', string: 'string' },
|
|
49
|
+
emit(d, names, types) {
|
|
50
|
+
const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(', ');
|
|
51
|
+
const L = [`export function ${d.name}(${params}): string {`];
|
|
52
|
+
for (const r of d.rules || []) L.push(` if (${tryExpr(exprToJs, r.when, names, 'false')}) return ${strLit(r.result)};`);
|
|
53
|
+
L.push(` return ${strLit(d.default ?? '')};`, '}');
|
|
54
|
+
return L;
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
python: {
|
|
58
|
+
label: 'Python',
|
|
59
|
+
types: { number: 'float', bool: 'bool', string: 'str' },
|
|
60
|
+
emit(d, names, types) {
|
|
61
|
+
const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(', ');
|
|
62
|
+
const L = [`def ${d.name}(${params}) -> str:`];
|
|
63
|
+
for (const r of d.rules || []) L.push(` if ${tryExpr(exprToPython, r.when, names, 'False')}:`, ` return ${strLit(r.result)}`);
|
|
64
|
+
L.push(` return ${strLit(d.default ?? '')}`);
|
|
65
|
+
return L;
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
go: {
|
|
69
|
+
label: 'Go',
|
|
70
|
+
types: { number: 'float64', bool: 'bool', string: 'string' },
|
|
71
|
+
emit(d, names, types) {
|
|
72
|
+
const params = names.map((n) => `${n} ${this.types[types[n]]}`).join(', ');
|
|
73
|
+
const L = [`func ${d.name}(${params}) string {`];
|
|
74
|
+
for (const r of d.rules || []) L.push(`\tif ${tryExpr(exprToGo, r.when, names, 'false')} {`, `\t\treturn ${strLit(r.result)}`, '\t}');
|
|
75
|
+
L.push(`\treturn ${strLit(d.default ?? '')}`, '}');
|
|
76
|
+
return L;
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
rust: {
|
|
80
|
+
label: 'Rust',
|
|
81
|
+
types: { number: 'f64', bool: 'bool', string: '&str' },
|
|
82
|
+
emit(d, names, types) {
|
|
83
|
+
const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(', ');
|
|
84
|
+
const L = [`fn ${d.name}(${params}) -> &'static str {`];
|
|
85
|
+
for (const r of d.rules || []) L.push(` if ${tryExpr(exprToRust, r.when, names, 'false')} {`, ` return ${strLit(r.result)};`, ' }');
|
|
86
|
+
L.push(` ${strLit(d.default ?? '')}`, '}');
|
|
87
|
+
return L;
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
csharp: {
|
|
91
|
+
label: 'C#',
|
|
92
|
+
types: { number: 'double', bool: 'bool', string: 'string' },
|
|
93
|
+
emit(d, names, types) {
|
|
94
|
+
const params = names.map((n) => `${this.types[types[n]]} ${n}`).join(', ');
|
|
95
|
+
const L = [`public static string ${d.name}(${params})`, '{'];
|
|
96
|
+
for (const r of d.rules || []) L.push(` if (${tryExpr(exprToCSharp, r.when, names, 'false')}) return ${strLit(r.result)};`);
|
|
97
|
+
L.push(` return ${strLit(d.default ?? '')};`, '}');
|
|
98
|
+
return L;
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
java: {
|
|
102
|
+
label: 'Java',
|
|
103
|
+
types: { number: 'double', bool: 'boolean', string: 'String' },
|
|
104
|
+
emit(d, names, types) {
|
|
105
|
+
const params = names.map((n) => `${this.types[types[n]]} ${n}`).join(', ');
|
|
106
|
+
const L = [`public static String ${d.name}(${params}) {`];
|
|
107
|
+
for (const r of d.rules || []) L.push(` if (${tryExpr(exprToJava, r.when, names, 'false')}) return ${strLit(r.result)};`);
|
|
108
|
+
L.push(` return ${strLit(d.default ?? '')};`, '}');
|
|
109
|
+
return L;
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
export const TRANSLATE_LANGUAGES = Object.entries(LANGS).map(([key, l]) => ({ key, label: l.label }));
|
|
115
|
+
|
|
116
|
+
/** Translate every decision in a parsed ThunderLang AST into `lang`. Returns source text. */
|
|
117
|
+
export function translateDecisions(ast, lang) {
|
|
118
|
+
const L = LANGS[lang];
|
|
119
|
+
if (!L) throw new Error(`Unknown language ${lang}. Use one of: ${Object.keys(LANGS).join(', ')}.`);
|
|
120
|
+
const comment = lang === 'python' ? '#' : '//';
|
|
121
|
+
const out = [`${comment} Generated from ThunderLang. Deterministic, no AI. The first matching rule wins.`];
|
|
122
|
+
for (const d of ast.decisions || []) {
|
|
123
|
+
out.push('', ...L.emit(d, inputNames(d), typesFor(ast, d)));
|
|
124
|
+
}
|
|
125
|
+
return out.join('\n');
|
|
126
|
+
}
|
package/src/write.d.mts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export const WRITE_SCHEMA: 'thunder-write-v1';
|
|
2
|
+
export interface ChangedCase { inputs: Record<string, string | number | boolean>; before: string; after: string }
|
|
3
|
+
export interface ChangedCases { checked: number; changed: ChangedCase[]; note: string }
|
|
4
|
+
export interface WriteChange { line: number; column: number; before: string; after: string }
|
|
5
|
+
export function writeRule(args: {
|
|
6
|
+
source: string; language?: string; file?: string; decision: string; line?: number | null;
|
|
7
|
+
/** 1-based rule number, or 'otherwise' for the fallback answer. */
|
|
8
|
+
rule: number | 'otherwise';
|
|
9
|
+
/** The rule's new condition in Thunder form (amount < 75). Only numbers, comparisons, and text may change. */
|
|
10
|
+
when?: string | null;
|
|
11
|
+
/** The rule's new answer (Review). */
|
|
12
|
+
answer?: string | null;
|
|
13
|
+
}):
|
|
14
|
+
| { schema: 'thunder-write-v1'; ok: true; source: string; problems: []; decision: string; rule: number | 'otherwise'; change: WriteChange[]; before: string; after: string; cases: ChangedCases }
|
|
15
|
+
| { schema: 'thunder-write-v1'; ok: false; source: string; problems: string[] };
|
|
16
|
+
export function changedCases(before: unknown, after: unknown): ChangedCases;
|
|
17
|
+
export type RulePart =
|
|
18
|
+
| { kind: 'number'; value: number }
|
|
19
|
+
| { kind: 'text'; value: string }
|
|
20
|
+
| { kind: 'comparison'; value: '<' | '<=' | '>' | '>=' | '==' | '!='; words: string }
|
|
21
|
+
| { kind: 'fixed'; value: string; words: string };
|
|
22
|
+
export const COMPARISON_CHOICES: Array<{ op: '<' | '<=' | '>' | '>=' | '==' | '!='; words: string }>;
|
|
23
|
+
export function ruleParts(when: string): RulePart[];
|
|
24
|
+
export function joinRuleParts(parts: RulePart[]): string;
|
package/src/write.mjs
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// Thunder write: change a rule in the Thunder picture and only the matching code changes.
|
|
2
|
+
//
|
|
3
|
+
// A recovered decision reads "if amount is at most 100, the answer is Approve". Thunder write lets a person
|
|
4
|
+
// change a number (100 -> 75), a comparison (at most -> under), a text value ("gold" -> "platinum"), or an
|
|
5
|
+
// answer (Approve -> Review), and writes exactly those characters back into the original file, keeping the
|
|
6
|
+
// file's own spelling (=== stays ===, 100.0 stays a decimal, 100m keeps its suffix, quotes keep their style).
|
|
7
|
+
//
|
|
8
|
+
// Every write is checked by reading the file again: the edited rule must now read exactly as intended, and
|
|
9
|
+
// every other rule, answer, and function in the file must read exactly as before. Otherwise nothing changes.
|
|
10
|
+
// It also runs the old and the new rule on boundary inputs and lists the cases whose answer changes.
|
|
11
|
+
//
|
|
12
|
+
// Deterministic and browser-safe. It edits text only; it never runs the code it edits.
|
|
13
|
+
import { readCode, sayCondition } from './read.mjs';
|
|
14
|
+
import { tokenize } from './expr.mjs';
|
|
15
|
+
import { recoverModel } from './promote.mjs';
|
|
16
|
+
|
|
17
|
+
export const WRITE_SCHEMA = 'thunder-write-v1';
|
|
18
|
+
|
|
19
|
+
const CMP = new Set(['<', '<=', '>', '>=', '==', '!=']);
|
|
20
|
+
const editable = (t) => t.t === 'num' || t.t === 'str' || (t.t === 'op' && CMP.has(t.v));
|
|
21
|
+
const category = (t) => (t.t === 'op' ? 'cmp' : t.t);
|
|
22
|
+
const sameTok = (a, b) => a.t === b.t && a.v === b.v;
|
|
23
|
+
const normWhen = (w) => tokenize(w).map((t) => (t.t === 'str' ? JSON.stringify(t.v) : String(t.v))).join(' ');
|
|
24
|
+
|
|
25
|
+
const COMMENT = { python: ['#'], ruby: ['#'], php: ['#', '//', '/*'] };
|
|
26
|
+
const commentStarts = (language) => COMMENT[language] || ['//', '/*'];
|
|
27
|
+
|
|
28
|
+
/** Numbers, comparison operators, and text literals in a slice of the original file, with exact offsets. */
|
|
29
|
+
function scanSource(source, from, to, language) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const starts = commentStarts(language);
|
|
32
|
+
let i = from;
|
|
33
|
+
while (i < to) {
|
|
34
|
+
const c = source[i];
|
|
35
|
+
if (starts.some((s) => source.startsWith(s, i))) {
|
|
36
|
+
if (source.startsWith('/*', i)) { const j = source.indexOf('*/', i + 2); i = j < 0 ? to : j + 2; }
|
|
37
|
+
else { const j = source.indexOf('\n', i); i = j < 0 ? to : j; }
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
41
|
+
let j = i + 1;
|
|
42
|
+
while (j < source.length && source[j] !== c && source[j] !== '\n') j += source[j] === '\\' ? 2 : 1;
|
|
43
|
+
if (source[j] === c) out.push({ t: 'str', v: source.slice(i + 1, j), start: i, end: j + 1, raw: source.slice(i, j + 1), quote: c });
|
|
44
|
+
i = j + 1;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (/[A-Za-z_$]/.test(c)) { // identifiers (and digits inside them) are not values
|
|
48
|
+
let j = i;
|
|
49
|
+
while (j < to && /[A-Za-z0-9_$]/.test(source[j])) j++;
|
|
50
|
+
out.push({ t: 'id', v: source.slice(i, j), start: i, end: j });
|
|
51
|
+
i = j;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (/[0-9]/.test(c)) {
|
|
55
|
+
const m = source.slice(i, to).match(/^[0-9][0-9_]*(\.[0-9][0-9_]*)?([eE][+-]?[0-9]+)?(f64|f32|i32|i64|u32|u64|[fFdDmMlLuU]{0,2})/);
|
|
56
|
+
const raw = m[0];
|
|
57
|
+
const suffix = m[3] || '';
|
|
58
|
+
out.push({ t: 'num', v: Number(raw.slice(0, raw.length - suffix.length).replace(/_/g, '')), start: i, end: i + raw.length, raw, suffix, decimal: !!m[1] });
|
|
59
|
+
i += raw.length;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const op = ['===', '!==', '<=>', '==', '!=', '<=', '>=', '->', '=>', '<<', '>>', '<-', '<', '>'].find((o) => source.startsWith(o, i));
|
|
63
|
+
if (op) {
|
|
64
|
+
if (!['<=>', '->', '=>', '<<', '>>', '<-'].includes(op)) out.push({ t: 'op', v: op === '===' ? '==' : op === '!==' ? '!=' : op, start: i, end: i + op.length, raw: op });
|
|
65
|
+
i += op.length;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
i++;
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const matches = (src, t) => src.t === t.t && (t.t === 'num' ? src.v === t.v : src.v === t.v);
|
|
74
|
+
|
|
75
|
+
/** Find the source tokens that are the rule's numbers, comparisons, and text, in order. */
|
|
76
|
+
function locate(srcToks, wanted) {
|
|
77
|
+
const found = [];
|
|
78
|
+
let k = 0;
|
|
79
|
+
for (const s of srcToks) {
|
|
80
|
+
if (k < wanted.length && matches(s, wanted[k])) { found.push(s); k++; }
|
|
81
|
+
}
|
|
82
|
+
return k === wanted.length ? found : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function spell(srcTok, next) {
|
|
86
|
+
if (next.t === 'op') {
|
|
87
|
+
if (srcTok.raw === '===' || srcTok.raw === '!==') return next.v === '==' ? '===' : next.v === '!=' ? '!==' : next.v;
|
|
88
|
+
return next.v;
|
|
89
|
+
}
|
|
90
|
+
if (next.t === 'num') {
|
|
91
|
+
let s = String(next.v);
|
|
92
|
+
if (srcTok.decimal && Number.isInteger(next.v)) s += '.0';
|
|
93
|
+
return s + srcTok.suffix;
|
|
94
|
+
}
|
|
95
|
+
return srcTok.quote + next.v + srcTok.quote;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const lineStartsOf = (source) => { const out = [0]; for (let i = 0; i < source.length; i++) if (source[i] === '\n') out.push(i + 1); return out; };
|
|
99
|
+
|
|
100
|
+
function findDecision(reading, name, line) {
|
|
101
|
+
const ds = reading.items.filter((i) => i.kind === 'decision' && i.name === name);
|
|
102
|
+
if (!ds.length) return null;
|
|
103
|
+
if (line == null) return ds[0];
|
|
104
|
+
return ds.reduce((best, d) => (Math.abs(d.line - line) < Math.abs(best.line - line) ? d : best));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The character range of a rule (its condition line through the line before the next rule or the fallback).
|
|
108
|
+
function ruleRegion(source, decision, index) {
|
|
109
|
+
const starts = lineStartsOf(source);
|
|
110
|
+
const lines = [...decision.rules.map((r) => r.line), decision.otherwise.line];
|
|
111
|
+
const first = index === 'otherwise' ? decision.otherwise.line : decision.rules[index].line;
|
|
112
|
+
const later = lines.filter((l) => l > first);
|
|
113
|
+
const last = index === 'otherwise' ? first : Math.max(first, (later.length ? Math.min(...later) : first + 1) - 1);
|
|
114
|
+
return [starts[first - 1] ?? source.length, starts[last] != null ? starts[last] - 1 : source.length];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const view = (it) => JSON.stringify({ kind: it.kind, name: it.name, says: it.says, thunder: it.thunder, rules: it.rules?.map((r) => [r.when, r.result]), otherwise: it.otherwise?.result, guards: it.guards?.map((g) => g.says ?? g.when) });
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Change one rule of a recovered decision and write it back to the original code.
|
|
121
|
+
*
|
|
122
|
+
* rule: 1-based rule number, or 'otherwise' for the fallback answer.
|
|
123
|
+
* when: the rule's new condition, in Thunder form (amount < 75). Numbers, comparisons, and text may change.
|
|
124
|
+
* answer: the rule's new answer (Review).
|
|
125
|
+
*
|
|
126
|
+
* Returns { schema, ok, source, problems, change, before, after, cases }. When ok is false, `source` is the
|
|
127
|
+
* original, untouched, and `problems` says why in plain words.
|
|
128
|
+
*/
|
|
129
|
+
export function writeRule({ source, language, file = '', decision: name, line = null, rule, when = null, answer = null }) {
|
|
130
|
+
const fail = (...problems) => ({ schema: WRITE_SCHEMA, ok: false, source, problems });
|
|
131
|
+
if (when == null && answer == null) return fail('Say what to change: a new condition (when) or a new answer.');
|
|
132
|
+
const reading = readCode(source, { language, file });
|
|
133
|
+
const lang = reading.language;
|
|
134
|
+
const d = findDecision(reading, name, line);
|
|
135
|
+
if (!d) return fail(`No decision named ${name} was found. Thunder write changes decisions: functions that choose between fixed answers.`);
|
|
136
|
+
const index = rule === 'otherwise' ? 'otherwise' : Number(rule) - 1;
|
|
137
|
+
if (index !== 'otherwise' && !(Number.isInteger(index) && d.rules[index])) return fail(`${name} has ${d.rules.length} rule${d.rules.length === 1 ? '' : 's'}; there is no rule ${rule}.`);
|
|
138
|
+
if (index === 'otherwise' && when != null) return fail('The fallback answer has no condition to change. Change its answer instead.');
|
|
139
|
+
const target = index === 'otherwise' ? d.otherwise : d.rules[index];
|
|
140
|
+
const [from, to] = ruleRegion(source, d, index);
|
|
141
|
+
const srcToks = scanSource(source, from, to, lang);
|
|
142
|
+
const edits = []; // { start, end, text }
|
|
143
|
+
|
|
144
|
+
// 1. The condition: only numbers, comparisons, and text values may change; the shape must stay the same.
|
|
145
|
+
let newWhen = target.when;
|
|
146
|
+
if (when != null) {
|
|
147
|
+
let oldT, newT;
|
|
148
|
+
try { oldT = tokenize(target.when); newT = tokenize(when); } catch (e) { return fail(`The new condition could not be read: ${e.message}`); }
|
|
149
|
+
const structural = oldT.length !== newT.length || oldT.some((t, i) => !sameTok(t, newT[i]) && !(editable(t) && editable(newT[i]) && category(t) === category(newT[i])));
|
|
150
|
+
if (structural) return fail(`Thunder write can change a number, a comparison, or a text value in a rule. "${when}" also changes the rule's shape (names, and/or, or parentheses). Use Propose rule change for that.`);
|
|
151
|
+
const wanted = oldT.filter(editable);
|
|
152
|
+
const found = locate(srcToks, wanted);
|
|
153
|
+
if (!found) return fail(`The values in "${sayCondition(target.when)}" could not be found exactly in the code at line ${target.line}, so it is not safe to write them back.`);
|
|
154
|
+
let k = 0;
|
|
155
|
+
oldT.forEach((t, i) => {
|
|
156
|
+
if (!editable(t)) return;
|
|
157
|
+
const s = found[k++];
|
|
158
|
+
const next = newT[i];
|
|
159
|
+
if (sameTok(t, next)) return;
|
|
160
|
+
if (next.t === 'str' && (next.v.includes(s.quote) || next.v.includes('\\'))) return edits.push({ bad: `The text ${JSON.stringify(next.v)} contains a quote or backslash; write it in the code directly.` });
|
|
161
|
+
edits.push({ start: s.start, end: s.end, text: spell(s, next), was: s.raw });
|
|
162
|
+
});
|
|
163
|
+
newWhen = normWhen(when);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// 2. The answer: reuse a spelling this function already returns, or change the text of a string answer.
|
|
167
|
+
if (answer != null && answer !== target.result) {
|
|
168
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(answer)) return fail(`The answer must be a name such as Approve or Review; "${answer}" is not.`);
|
|
169
|
+
const reads = (t, result) => (t.t === 'str' && t.v === result) || (t.t === 'id' && t.v === result);
|
|
170
|
+
const sites = srcToks.filter((t) => reads(t, target.result));
|
|
171
|
+
if (sites.length !== 1) return fail(`The answer ${target.result} could not be found exactly once near line ${target.line}, so it is not safe to change.`);
|
|
172
|
+
const site = sites[0];
|
|
173
|
+
// An answer spelled elsewhere in this decision, for example Decision.REVIEW or "Review".
|
|
174
|
+
const others = [...d.rules.map((_, i) => i), 'otherwise'].filter((i) => i !== index && (i === 'otherwise' ? d.otherwise : d.rules[i]).result === answer);
|
|
175
|
+
let text = null;
|
|
176
|
+
for (const i of others) {
|
|
177
|
+
const [a, b] = ruleRegion(source, d, i);
|
|
178
|
+
const t = scanSource(source, a, b, lang).find((x) => reads(x, answer));
|
|
179
|
+
if (t && t.t === site.t) { text = t.raw ?? t.v; break; }
|
|
180
|
+
}
|
|
181
|
+
if (text == null && site.t === 'str') text = site.quote + answer + site.quote;
|
|
182
|
+
if (text == null) return fail(`${name} does not return ${answer} anywhere yet, and its answers are code names (such as ${site.v}), so Thunder write will not invent one. Add ${answer} in the code first, or use Propose rule change.`);
|
|
183
|
+
edits.push({ start: site.start, end: site.end, text, was: site.raw ?? site.v });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const bad = edits.find((e) => e.bad);
|
|
187
|
+
if (bad) return fail(bad.bad);
|
|
188
|
+
const real = edits.filter((e) => source.slice(e.start, e.end) !== e.text).sort((a, b) => b.start - a.start);
|
|
189
|
+
if (!real.length) return fail('Nothing would change: the rule already reads that way.');
|
|
190
|
+
let next = source;
|
|
191
|
+
for (const e of real) next = next.slice(0, e.start) + e.text + next.slice(e.end);
|
|
192
|
+
|
|
193
|
+
// 3. Verify by reading the file again.
|
|
194
|
+
const problems = [];
|
|
195
|
+
let after;
|
|
196
|
+
try { after = readCode(next, { language: lang, file }); } catch (e) { return fail(`The changed file could not be read: ${e.message}`); }
|
|
197
|
+
const d2 = findDecision(after, name, d.line);
|
|
198
|
+
if (!d2) return fail(`${name} is no longer read as a decision after the change.`);
|
|
199
|
+
const wantResult = answer ?? target.result;
|
|
200
|
+
if (d2.rules.length !== d.rules.length) problems.push('The number of rules changed.');
|
|
201
|
+
d.rules.forEach((r, i) => {
|
|
202
|
+
const r2 = d2.rules[i];
|
|
203
|
+
if (!r2) return;
|
|
204
|
+
const w = i === index ? newWhen : normWhen(r.when);
|
|
205
|
+
const res = i === index ? wantResult : r.result;
|
|
206
|
+
if (normWhen(r2.when) !== w) problems.push(`Rule ${i + 1} reads "${sayCondition(r2.when)}" after the change, not "${sayCondition(w)}".`);
|
|
207
|
+
if (r2.result !== res) problems.push(`Rule ${i + 1} answers ${r2.result} after the change, not ${res}.`);
|
|
208
|
+
});
|
|
209
|
+
const wantOtherwise = index === 'otherwise' ? wantResult : d.otherwise.result;
|
|
210
|
+
if (d2.otherwise?.result !== wantOtherwise) problems.push(`The fallback answers ${d2.otherwise?.result} after the change, not ${wantOtherwise}.`);
|
|
211
|
+
const others = reading.items.filter((i) => i !== d), others2 = after.items.filter((i) => i !== d2);
|
|
212
|
+
if (others.length !== others2.length) problems.push('Another part of the file reads differently after the change.');
|
|
213
|
+
else others.forEach((o, i) => { if (view(o) !== view(others2[i])) problems.push(`${o.name} (line ${o.line}) reads differently after the change.`); });
|
|
214
|
+
if (problems.length) return fail(...problems);
|
|
215
|
+
|
|
216
|
+
const starts = lineStartsOf(source);
|
|
217
|
+
const lineOf = (off) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const m = (lo + hi + 1) >> 1; if (starts[m] <= off) lo = m; else hi = m - 1; } return lo + 1; };
|
|
218
|
+
const change = real.slice().reverse().map((e) => ({ line: lineOf(e.start), column: e.start - starts[lineOf(e.start) - 1] + 1, before: e.was, after: e.text }));
|
|
219
|
+
const label = (r) => (r === 'otherwise' ? 'Otherwise' : `If ${sayCondition(r.when)}`);
|
|
220
|
+
const beforeRule = index === 'otherwise' ? `Otherwise, the answer is ${target.result}` : `${label(target)}, the answer is ${target.result}`;
|
|
221
|
+
const afterRule = index === 'otherwise' ? `Otherwise, the answer is ${wantResult}` : `If ${sayCondition(newWhen)}, the answer is ${wantResult}`;
|
|
222
|
+
return { schema: WRITE_SCHEMA, ok: true, source: next, problems: [], decision: name, rule: index === 'otherwise' ? 'otherwise' : index + 1, change, before: beforeRule, after: afterRule, cases: changedCases(d, d2) };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Run the old and the new decision on the same boundary inputs (both sides of every threshold, every text
|
|
227
|
+
* value) and list the inputs whose answer changes. This covers the inputs checked, not every possible input.
|
|
228
|
+
*/
|
|
229
|
+
export function changedCases(before, after) {
|
|
230
|
+
const a = recoverModel(before, { extraConditions: after.rules.map((r) => r.when) });
|
|
231
|
+
const b = recoverModel(after, { extraConditions: before.rules.map((r) => r.when) });
|
|
232
|
+
if (!a.ok || !b.ok) return { checked: 0, changed: [], note: `The cases could not be compared: ${(a.ok ? b : a).reason}` };
|
|
233
|
+
const lookup = new Map(b.all.map((x) => [JSON.stringify(x.a), x.r.result]));
|
|
234
|
+
const changed = [];
|
|
235
|
+
for (const x of a.all) {
|
|
236
|
+
const next = lookup.get(JSON.stringify(x.a));
|
|
237
|
+
if (next !== undefined && next !== x.r.result) changed.push({ inputs: x.a, before: x.r.result, after: next });
|
|
238
|
+
}
|
|
239
|
+
return { checked: a.all.length, changed, note: `Checked ${a.all.length} boundary input${a.all.length === 1 ? '' : 's'}; ${changed.length} now get${changed.length === 1 ? 's' : ''} a different answer. These are the values on each side of every limit, not every possible input.` };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const CMP_WORDS = { '<=': 'at most', '<': 'less than', '>=': 'at least', '>': 'more than', '==': 'is', '!=': 'is not' };
|
|
243
|
+
/** The comparisons a person can choose between, in plain words. */
|
|
244
|
+
export const COMPARISON_CHOICES = Object.entries(CMP_WORDS).map(([op, words]) => ({ op, words }));
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* A rule's condition split into the parts a person sees: names and words stay fixed; numbers, comparisons, and
|
|
248
|
+
* text values can change. Joining the parts back with `joinRuleParts` gives a condition `writeRule` accepts.
|
|
249
|
+
*/
|
|
250
|
+
export function ruleParts(when) {
|
|
251
|
+
return tokenize(when).map((t) => {
|
|
252
|
+
if (t.t === 'num') return { kind: 'number', value: t.v };
|
|
253
|
+
if (t.t === 'str') return { kind: 'text', value: t.v };
|
|
254
|
+
if (t.t === 'op' && CMP.has(t.v)) return { kind: 'comparison', value: t.v, words: CMP_WORDS[t.v] };
|
|
255
|
+
if (t.t === 'bool') return { kind: 'fixed', value: String(t.v), words: String(t.v) };
|
|
256
|
+
if (t.t === 'kw') return { kind: 'fixed', value: t.v, words: t.v };
|
|
257
|
+
return { kind: 'fixed', value: String(t.v), words: String(t.v) };
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function joinRuleParts(parts) {
|
|
262
|
+
return parts.map((p) => (p.kind === 'text' ? JSON.stringify(String(p.value)) : String(p.value))).join(' ').replace(/\( /g, '(').replace(/ \)/g, ')');
|
|
263
|
+
}
|