@skillstech/thunderlang 0.5.11 → 0.5.12
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 +437 -0
- package/dist/core.cjs +30431 -7604
- package/dist/index.cjs +28577 -5331
- package/dist/learn.cjs +22676 -3870
- package/package.json +12 -3
- package/src/bicep.mjs +167 -0
- package/src/cli.mjs +169 -3
- package/src/commands.mjs +464 -0
- package/src/core.d.ts +12 -4
- package/src/core.mjs +12 -4
- package/src/emit.mjs +1 -1
- package/src/executed.d.mts +53 -0
- package/src/executed.mjs +465 -0
- package/src/faithful.mjs +137 -0
- package/src/file-formats.mjs +35 -0
- package/src/hcl.mjs +94 -0
- package/src/index.d.ts +7 -1
- package/src/index.mjs +6 -1
- package/src/infra-bicep.mjs +312 -0
- package/src/infra-cloud.mjs +348 -0
- package/src/infra-compose.mjs +315 -0
- package/src/infra-containers.mjs +100 -0
- package/src/infra-docker.mjs +267 -0
- package/src/infra-expr.mjs +509 -0
- package/src/infra-gha.mjs +350 -0
- package/src/infra-k8s.mjs +657 -0
- package/src/infra-terraform.mjs +499 -0
- package/src/infra-words.mjs +811 -0
- package/src/libraries.mjs +202 -0
- package/src/lift.mjs +48 -6
- package/src/meaning.d.mts +89 -0
- package/src/meaning.mjs +2544 -0
- package/src/model.d.mts +59 -12
- package/src/model.mjs +462 -80
- package/src/powershell.mjs +1361 -0
- package/src/read-repo-fs.mjs +29 -7
- package/src/read-repo.d.mts +5 -1
- package/src/read-repo.mjs +33 -7
- package/src/read.d.mts +21 -1
- package/src/read.mjs +1015 -42
- package/src/review.d.mts +35 -0
- package/src/review.mjs +671 -0
- package/src/rlang.mjs +1084 -0
- package/src/round-trip.d.mts +12 -0
- package/src/round-trip.mjs +174 -0
- package/src/runners/thunder-generate.mjs +56 -0
- package/src/runners/thunder-trace.cjs +284 -0
- package/src/runners/thunder_trace.py +599 -0
- package/src/running.d.mts +104 -0
- package/src/running.mjs +787 -0
- package/src/same.d.mts +1 -0
- package/src/same.mjs +24 -3
- package/src/shell.mjs +1212 -0
- package/src/sql.mjs +3 -2
- package/src/steps.d.mts +6 -1
- package/src/steps.mjs +1448 -86
- package/src/system.d.mts +12 -0
- package/src/system.mjs +845 -0
- package/src/things-langs.mjs +275 -0
- package/src/thunderize.mjs +3 -3
- package/src/visual.d.mts +5 -5
- package/src/visual.mjs +24 -3
- package/src/write-steps.d.mts +64 -0
- package/src/write-steps.mjs +1608 -0
- package/src/write.mjs +2 -1
- package/src/yaml.mjs +403 -0
|
@@ -0,0 +1,1608 @@
|
|
|
1
|
+
// Writing in Thunder: a person changes software in Thunder, and the code is written for them.
|
|
2
|
+
//
|
|
3
|
+
// A Thunder edit is a small, explicit operation on the meaning model, addressed by member (function) and step:
|
|
4
|
+
//
|
|
5
|
+
// setValue change a value in a step (7 -> 10, "gold" -> "platinum", false -> true)
|
|
6
|
+
// setCondition change a question: its whole condition, a comparison, one side, its negation, add or remove a clause
|
|
7
|
+
// addStep add a step before or after a step, or at the start or end of a question's side
|
|
8
|
+
// removeStep remove a step (and everything inside it)
|
|
9
|
+
// moveStep move a step before or after another step
|
|
10
|
+
// addStop add a Stop (an error with a message): a new question that stops, or a Stop on a question's side
|
|
11
|
+
// removeStop remove a Stop (and its question, when the Stop was all the question did)
|
|
12
|
+
// addInput add an input (with a type and a default when the language needs them)
|
|
13
|
+
// removeInput remove an input the function no longer uses
|
|
14
|
+
// setGivesBack change what a step gives back (a return value), or the declared kind of answer
|
|
15
|
+
// rename rename an input or a name inside a function, or the function itself (meaning-preserving)
|
|
16
|
+
// addFunction add a new function made of Thunder steps (simple cases)
|
|
17
|
+
//
|
|
18
|
+
// Each edit is validated against the meaning tree (thunder-expr-v1, see meaning.mjs) before anything is written.
|
|
19
|
+
// For TypeScript, JavaScript, Python, and Go the code is written deterministically as a minimal patch: only the lines
|
|
20
|
+
// (often only the characters) the edit touches change; comments, formatting, and indentation stay byte for byte.
|
|
21
|
+
// When the language or the shape of the code is beyond the writers, the answer is `needs-ai` with a precise,
|
|
22
|
+
// self-contained instruction for an AI coding agent: this module never calls a network or an AI, and never applies
|
|
23
|
+
// anything on its own. A change written by AI is labeled "AI-written" and checked by the same proof.
|
|
24
|
+
//
|
|
25
|
+
// Proof, after every write: the patched file is read again and
|
|
26
|
+
// edited the edited function's steps must equal the intended steps, tree for tree (nothing more, nothing less)
|
|
27
|
+
// unchanged every other function in every file must mean the same: `sameMeaning` must say 'same' for each, and
|
|
28
|
+
// each one's steps must be identical trees. A different reading is never called "same".
|
|
29
|
+
// run optional: a caller-supplied runner (the CLI runs a test command) — its outcome is reported as is.
|
|
30
|
+
// A patch that fails its proof is never returned as written.
|
|
31
|
+
//
|
|
32
|
+
// Deterministic and browser-safe (no Node APIs): it edits text and reads it; it never runs the code it edits.
|
|
33
|
+
import { readCode } from './read.mjs';
|
|
34
|
+
import { readableLanguage } from './read-repo.mjs';
|
|
35
|
+
import { parseExpr, parseStatement, parseStatementSpans, renderExpr, renderStatement, sameExpr, normalizeExpr, nodesOf, sayFull, blockEnd } from './meaning.mjs';
|
|
36
|
+
import { sameMeaning, nameKey } from './same.mjs';
|
|
37
|
+
import { flowOf } from './model.mjs';
|
|
38
|
+
|
|
39
|
+
export const WRITE_STEPS_SCHEMA = 'thunder-write-steps-v1';
|
|
40
|
+
export const WRITE_STEPS_LANGUAGES = ['typescript', 'javascript', 'python', 'go'];
|
|
41
|
+
export const EDIT_OPS = ['setValue', 'setCondition', 'addStep', 'removeStep', 'moveStep', 'addStop', 'removeStop', 'addInput', 'removeInput', 'setGivesBack', 'rename', 'addFunction'];
|
|
42
|
+
|
|
43
|
+
const LANG_NAME = { typescript: 'TypeScript', javascript: 'JavaScript', python: 'Python', go: 'Go', java: 'Java', csharp: 'C#', kotlin: 'Kotlin', php: 'PHP', ruby: 'Ruby', rust: 'Rust', swift: 'Swift', scala: 'Scala', elixir: 'Elixir', c: 'C', cpp: 'C++' };
|
|
44
|
+
const langName = (l) => LANG_NAME[l] || l;
|
|
45
|
+
|
|
46
|
+
// Two ways an edit cannot be written deterministically.
|
|
47
|
+
class Refused extends Error { constructor(why) { super(why); this.refused = true; } }
|
|
48
|
+
class NeedsAI extends Error { constructor(why) { super(why); this.needsAi = true; } }
|
|
49
|
+
const refuse = (why) => { throw new Refused(why); };
|
|
50
|
+
const needsAi = (why) => { throw new NeedsAI(why); };
|
|
51
|
+
|
|
52
|
+
// ── Text helpers ───────────────────────────────────────────────────────────────────────────────────────────
|
|
53
|
+
|
|
54
|
+
const linesOf = (s) => s.split('\n');
|
|
55
|
+
const indentOf = (line) => (String(line).match(/^[ \t]*/) || [''])[0];
|
|
56
|
+
const lineStarts = (s) => { const out = [0]; for (let i = 0; i < s.length; i++) if (s[i] === '\n') out.push(i + 1); return out; };
|
|
57
|
+
|
|
58
|
+
/** The indent one level deeper than `base`, the way this file writes it. */
|
|
59
|
+
function indentUnit(source, language) {
|
|
60
|
+
if (language === 'go') return '\t';
|
|
61
|
+
const counts = new Map();
|
|
62
|
+
let prev = '';
|
|
63
|
+
for (const l of linesOf(source)) {
|
|
64
|
+
if (!l.trim()) continue;
|
|
65
|
+
const ind = indentOf(l);
|
|
66
|
+
if (ind.length > prev.length && ind.startsWith(prev)) { const u = ind.slice(prev.length); counts.set(u, (counts.get(u) || 0) + 1); }
|
|
67
|
+
prev = ind;
|
|
68
|
+
}
|
|
69
|
+
const best = [...counts.entries()].sort((a, b) => b[1] - a[1])[0];
|
|
70
|
+
return best ? best[0] : language === 'python' ? ' ' : ' ';
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A small unified diff: one hunk per run of changed lines, with three lines of context. */
|
|
74
|
+
export function unifiedDiff(path, before, after) {
|
|
75
|
+
if (before === after) return '';
|
|
76
|
+
const a = linesOf(before), b = linesOf(after);
|
|
77
|
+
// Longest common subsequence on the middle (the common start and end are trimmed first).
|
|
78
|
+
let s = 0;
|
|
79
|
+
while (s < a.length && s < b.length && a[s] === b[s]) s++;
|
|
80
|
+
let ea = a.length, eb = b.length;
|
|
81
|
+
while (ea > s && eb > s && a[ea - 1] === b[eb - 1]) { ea--; eb--; }
|
|
82
|
+
const A = a.slice(s, ea), B = b.slice(s, eb);
|
|
83
|
+
const ops = [];
|
|
84
|
+
if (A.length * B.length > 4e6) { for (const x of A) ops.push(['-', x]); for (const y of B) ops.push(['+', y]); }
|
|
85
|
+
else {
|
|
86
|
+
const dp = Array.from({ length: A.length + 1 }, () => new Uint32Array(B.length + 1));
|
|
87
|
+
for (let i = A.length - 1; i >= 0; i--) for (let j = B.length - 1; j >= 0; j--) dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
|
88
|
+
let i = 0, j = 0;
|
|
89
|
+
while (i < A.length || j < B.length) {
|
|
90
|
+
if (i < A.length && j < B.length && A[i] === B[j]) { ops.push([' ', A[i]]); i++; j++; }
|
|
91
|
+
else if (i < A.length && (j === B.length || dp[i + 1][j] >= dp[i][j + 1])) { ops.push(['-', A[i]]); i++; }
|
|
92
|
+
else { ops.push(['+', B[j]]); j++; }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const all = [...a.slice(0, s).map((x) => [' ', x]), ...ops, ...a.slice(ea).map((x) => [' ', x])];
|
|
96
|
+
const out = [`--- a/${path}`, `+++ b/${path}`];
|
|
97
|
+
let k = 0;
|
|
98
|
+
while (k < all.length) {
|
|
99
|
+
if (all[k][0] === ' ') { k++; continue; }
|
|
100
|
+
let start = Math.max(0, k - 3), end = k;
|
|
101
|
+
// Extend over changes separated by up to 6 unchanged lines.
|
|
102
|
+
for (;;) {
|
|
103
|
+
while (end < all.length && all[end][0] !== ' ') end++;
|
|
104
|
+
let n = end;
|
|
105
|
+
while (n < all.length && all[n][0] === ' ' && n - end < 7) n++;
|
|
106
|
+
if (n < all.length && all[n][0] !== ' ' && n - end < 7) { end = n; continue; }
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
const stop = Math.min(all.length, end + 3);
|
|
110
|
+
let la = 1, lb = 1;
|
|
111
|
+
for (let q = 0; q < start; q++) { if (all[q][0] !== '+') la++; if (all[q][0] !== '-') lb++; }
|
|
112
|
+
const chunk = all.slice(start, stop);
|
|
113
|
+
const na = chunk.filter((x) => x[0] !== '+').length, nb = chunk.filter((x) => x[0] !== '-').length;
|
|
114
|
+
out.push(`@@ -${na ? la : la - 1},${na} +${nb ? lb : lb - 1},${nb} @@`);
|
|
115
|
+
for (const [op, x] of chunk) out.push(`${op}${x}`);
|
|
116
|
+
k = stop;
|
|
117
|
+
}
|
|
118
|
+
return `${out.join('\n')}\n`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ── The meaning model of a file ────────────────────────────────────────────────────────────────────────────
|
|
122
|
+
|
|
123
|
+
const readFile = (f) => {
|
|
124
|
+
const language = readableLanguage(f.path) || f.language;
|
|
125
|
+
return { language, reading: readCode(f.source, { language, file: f.path, allSteps: true }) };
|
|
126
|
+
};
|
|
127
|
+
const membersOf = (reading) => reading.items.filter((i) => (i.kind === 'function' || i.kind === 'decision'));
|
|
128
|
+
|
|
129
|
+
/** A member's identity across an edit: its name and which occurrence of that name in the file. */
|
|
130
|
+
const memberKeys = (reading) => {
|
|
131
|
+
const seen = new Map();
|
|
132
|
+
return membersOf(reading).map((it) => { const n = it.name; const k = (seen.get(n) || 0) + 1; seen.set(n, k); return { key: `${n}#${k}`, item: it }; });
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/** The steps of a function as plain trees: what the proof compares. */
|
|
136
|
+
export function stepShape(steps) {
|
|
137
|
+
return (steps || []).filter((s) => s.expr?.kind !== 'pass').map((s) => ({
|
|
138
|
+
e: s.expr ? s.expr : { kind: 'code', text: String(s.code ?? s.says ?? '').replace(/\s+/g, ' ').trim() },
|
|
139
|
+
c: stepShape(s.children),
|
|
140
|
+
...(s.otherwise ? { o: stepShape(s.otherwise) } : {}),
|
|
141
|
+
...(s.handlers?.length ? { h: s.handlers.map((h) => ({ e: h.expr ?? null, c: stepShape(h.steps) })) } : {}),
|
|
142
|
+
...(s.always ? { a: stepShape(s.always.steps) } : {}),
|
|
143
|
+
}));
|
|
144
|
+
}
|
|
145
|
+
const shapeKey = (shape) => JSON.stringify(normalizeExpr(shape));
|
|
146
|
+
const cloneShape = (x) => JSON.parse(JSON.stringify(x));
|
|
147
|
+
const inputsKey = (item) => JSON.stringify((item.inputs || []).map((p) => [p.name, (p.type ?? '').replace(/\s+/g, '')]));
|
|
148
|
+
|
|
149
|
+
/** Where a step is: { step, list, index, path, parent }. Paths are step numbers from 0; 'else' enters the other side. */
|
|
150
|
+
function locateStep(steps, sel, { flowSteps } = {}) {
|
|
151
|
+
const all = [];
|
|
152
|
+
const walk = (list, path, parent) => list.forEach((s, i) => {
|
|
153
|
+
all.push({ step: s, list, index: i, path: [...path, i], parent });
|
|
154
|
+
if (s.children) walk(s.children, [...path, i], s);
|
|
155
|
+
if (s.otherwise) walk(s.otherwise, [...path, i, 'else'], s);
|
|
156
|
+
});
|
|
157
|
+
walk(steps || [], [], null);
|
|
158
|
+
if (Array.isArray(sel)) return all.find((x) => x.path.join('.') === sel.join('.')) ?? null;
|
|
159
|
+
if (typeof sel === 'string' && /^\d+(?:\.(?:\d+|else))*$/.test(sel) && sel.includes('.')) return all.find((x) => x.path.join('.') === sel) ?? null;
|
|
160
|
+
const line = typeof sel === 'number' ? sel : /^line:\d+$/.test(String(sel)) ? Number(String(sel).slice(5)) : null;
|
|
161
|
+
if (line != null) return all.find((x) => x.step.line === line) ?? null;
|
|
162
|
+
if (/^n\d+$/.test(String(sel)) && flowSteps) {
|
|
163
|
+
const node = flowOf(flowSteps).nodes.find((n) => n.id === sel);
|
|
164
|
+
return node?.line != null ? all.find((x) => x.step.line === node.line) ?? null : null;
|
|
165
|
+
}
|
|
166
|
+
if (/^\d+$/.test(String(sel))) return all.find((x) => x.path.join('.') === String(sel)) ?? null;
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
const pathIn = (shape, path) => {
|
|
170
|
+
let list = shape, node = null;
|
|
171
|
+
for (let i = 0; i < path.length; i++) {
|
|
172
|
+
const p = path[i];
|
|
173
|
+
if (p === 'else') { list = node.o ?? (node.o = []); continue; }
|
|
174
|
+
node = list[p];
|
|
175
|
+
if (i < path.length - 1 && path[i + 1] !== 'else') list = node.c;
|
|
176
|
+
}
|
|
177
|
+
return { list, node, index: path[path.length - 1] };
|
|
178
|
+
};
|
|
179
|
+
const listAt = (shape, path) => {
|
|
180
|
+
// The list holding the step at `path`.
|
|
181
|
+
if (path.length === 1) return shape;
|
|
182
|
+
const parentPath = path.slice(0, -1);
|
|
183
|
+
if (parentPath[parentPath.length - 1] === 'else') return pathIn(shape, parentPath.slice(0, -1)).node.o;
|
|
184
|
+
return pathIn(shape, parentPath).node.c;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// ── Finding the member an edit is for ──────────────────────────────────────────────────────────────────────
|
|
188
|
+
|
|
189
|
+
function parseMemberRef(ref) {
|
|
190
|
+
if (ref && typeof ref === 'object') return { file: ref.file ?? null, name: ref.name, line: ref.line ?? null };
|
|
191
|
+
const s = String(ref ?? '');
|
|
192
|
+
// A model member id: path#owner#name#line.
|
|
193
|
+
const parts = s.split('#');
|
|
194
|
+
if (parts.length >= 3 && /^\d+$/.test(parts[parts.length - 1])) return { file: parts[0], name: parts[parts.length - 2], line: Number(parts[parts.length - 1]) };
|
|
195
|
+
const m = s.match(/^(.+?):([A-Za-z_$][\w$]*)(?::(\d+))?$/);
|
|
196
|
+
if (m) return { file: m[1], name: m[2], line: m[3] ? Number(m[3]) : null };
|
|
197
|
+
return { file: null, name: s, line: null };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function findMember(state, ref) {
|
|
201
|
+
const r = parseMemberRef(ref);
|
|
202
|
+
const candidates = [];
|
|
203
|
+
for (const [path, f] of state.files) {
|
|
204
|
+
if (r.file && path !== r.file && !path.endsWith(`/${r.file}`)) continue;
|
|
205
|
+
const rd = state.read(path);
|
|
206
|
+
if (!rd) continue;
|
|
207
|
+
for (const { key, item } of memberKeys(rd.reading)) if (item.name === r.name) candidates.push({ path, key, item, language: rd.language, reading: rd.reading, source: f });
|
|
208
|
+
}
|
|
209
|
+
if (!candidates.length) refuse(`No function named ${r.name}${r.file ? ` in ${r.file}` : ''} was found.`);
|
|
210
|
+
if (r.line == null && candidates.length > 1) refuse(`${r.name} is in more than one place (${candidates.map((c) => `${c.path}:${c.item.line}`).join(', ')}); say which with its id or line.`);
|
|
211
|
+
return candidates.reduce((best, c) => (r.line == null || Math.abs(c.item.line - r.line) < Math.abs(best.item.line - r.line) ? c : best));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ── Values and expressions a person gives ──────────────────────────────────────────────────────────────────
|
|
215
|
+
|
|
216
|
+
/** A literal tree for a plain value, spelled the way `like` (an existing literal) is spelled. */
|
|
217
|
+
function literalOf(value, language, like = null) {
|
|
218
|
+
if (value === null) return { kind: 'literal', type: 'null', value: null, raw: language === 'python' ? 'None' : language === 'go' ? 'nil' : 'null' };
|
|
219
|
+
if (typeof value === 'boolean') return { kind: 'literal', type: 'bool', value, raw: language === 'python' ? (value ? 'True' : 'False') : String(value) };
|
|
220
|
+
if (typeof value === 'number') {
|
|
221
|
+
if (!Number.isFinite(value)) refuse(`${value} is not a number that can be written.`);
|
|
222
|
+
let raw = String(value);
|
|
223
|
+
if (like?.type === 'number' && /\.\d/.test(like.raw) && Number.isInteger(value)) raw += '.0';
|
|
224
|
+
const suffix = like?.type === 'number' ? String(like.raw).match(/[A-Za-z]+$/)?.[0] ?? '' : '';
|
|
225
|
+
if (suffix && !/^[eE]/.test(suffix)) raw += suffix;
|
|
226
|
+
return { kind: 'literal', type: 'number', value, raw };
|
|
227
|
+
}
|
|
228
|
+
if (typeof value === 'string') {
|
|
229
|
+
const q = like?.type === 'text' && /^'/.test(like.raw) && language !== 'go' ? "'" : '"';
|
|
230
|
+
if (/[\n\r]/.test(value)) needsAi('The text has a line break; the writers keep text on one line.');
|
|
231
|
+
const body = value.replace(/\\/g, '\\\\').replace(new RegExp(q, 'g'), `\\${q}`);
|
|
232
|
+
return { kind: 'literal', type: 'text', value, raw: `${q}${body}${q}` };
|
|
233
|
+
}
|
|
234
|
+
refuse(`${JSON.stringify(value)} is not a value (use a number, text, true/false, or null).`);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const PARSE_ORDER = (lang) => [lang, ...WRITE_STEPS_LANGUAGES.filter((l) => l !== lang)];
|
|
238
|
+
/** An expression a person wrote (in Thunder's neutral form or the file's language), as a tree for this file. */
|
|
239
|
+
function exprFrom(input, language, what = 'expression') {
|
|
240
|
+
if (input && typeof input === 'object' && input.kind) return input;
|
|
241
|
+
if (typeof input !== 'string') return literalOf(input, language);
|
|
242
|
+
for (const l of PARSE_ORDER(language)) {
|
|
243
|
+
const t = parseExpr(input, l);
|
|
244
|
+
if (t && t.kind !== 'code') return adapt(t, language);
|
|
245
|
+
}
|
|
246
|
+
refuse(`The ${what} "${input}" could not be read. Write it as code, for example days > 10 and not member.vip.`);
|
|
247
|
+
}
|
|
248
|
+
/** Adapt a tree read in another language to this file's spelling (== in JavaScript is ===, quotes, true/True). */
|
|
249
|
+
function adapt(tree, language) {
|
|
250
|
+
const t = cloneShape(tree);
|
|
251
|
+
for (const n of nodesOf(t)) {
|
|
252
|
+
if ((language === 'typescript' || language === 'javascript') && n.kind === 'compare') { if (n.op === '==') n.op = '==='; if (n.op === '!=') n.op = '!=='; }
|
|
253
|
+
if (language !== 'typescript' && language !== 'javascript' && n.kind === 'compare') { if (n.op === '===') n.op = '=='; if (n.op === '!==') n.op = '!='; }
|
|
254
|
+
if (n.kind === 'literal' && n.type === 'bool') n.raw = language === 'python' ? (n.value ? 'True' : 'False') : String(n.value);
|
|
255
|
+
if (n.kind === 'literal' && n.type === 'null') n.raw = language === 'python' ? 'None' : language === 'go' ? 'nil' : 'null';
|
|
256
|
+
if (n.kind === 'literal' && n.type === 'text' && language === 'go' && /^'/.test(n.raw)) n.raw = JSON.stringify(n.value);
|
|
257
|
+
}
|
|
258
|
+
return t;
|
|
259
|
+
}
|
|
260
|
+
/** A statement a person wrote, as a tree for this file. */
|
|
261
|
+
function statementFrom(input, language) {
|
|
262
|
+
if (input && typeof input === 'object' && input.kind) return input;
|
|
263
|
+
if (typeof input !== 'string' || !input.trim()) refuse('Say the new step as code, for example notify(order.customer).');
|
|
264
|
+
for (const l of PARSE_ORDER(language)) {
|
|
265
|
+
const t = parseStatement(input, l);
|
|
266
|
+
if (t && t.kind !== 'code') {
|
|
267
|
+
const a = adapt(t, language);
|
|
268
|
+
try { renderStatement(a, language); return a; } catch { /* try the next reading */ }
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
refuse(`The step "${input}" could not be read as one statement.`);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ── Writing one step's code from its new tree, changing only what differs ─────────────────────────────────
|
|
275
|
+
|
|
276
|
+
const STATEMENT_KINDS = new Set(['if', 'return', 'throw', 'assign', 'loop', 'switch', 'case', 'declare', 'yield', 'defer', 'go', 'delete', 'assert', 'with']);
|
|
277
|
+
const SCALAR_SKIP = new Set(['raw', 'error', 'message']);
|
|
278
|
+
const isNode = (v) => v && typeof v === 'object' && !Array.isArray(v) && typeof v.kind === 'string';
|
|
279
|
+
|
|
280
|
+
/** Replacements [{ range, text, node }] that turn `o` into `n`, at the smallest parts that differ; null when a part has no known place. */
|
|
281
|
+
function diffTrees(o, n, sp, language) {
|
|
282
|
+
if (sameExpr(o, n)) return [];
|
|
283
|
+
const whole = () => {
|
|
284
|
+
const range = sp.rangeOf(o);
|
|
285
|
+
if (!range) return null;
|
|
286
|
+
return [{ range, text: renderPart(n, o, sp, language), node: n, old: o }];
|
|
287
|
+
};
|
|
288
|
+
if (o.kind !== n.kind) return whole();
|
|
289
|
+
const keys = new Set([...Object.keys(o), ...Object.keys(n)]);
|
|
290
|
+
const out = [];
|
|
291
|
+
for (const k of keys) {
|
|
292
|
+
const a = o[k], b = n[k];
|
|
293
|
+
if (isNode(a) && isNode(b)) { const d = diffTrees(a, b, sp, language); if (d == null) return whole(); out.push(...d); continue; }
|
|
294
|
+
if (Array.isArray(a) && Array.isArray(b) && a.every((x) => isNode(x) || typeof x !== 'object') && b.every((x) => isNode(x) || typeof x !== 'object')) {
|
|
295
|
+
if (a.length !== b.length) {
|
|
296
|
+
// An and/or that gained or lost a clause: the whole condition is written again.
|
|
297
|
+
return whole();
|
|
298
|
+
}
|
|
299
|
+
for (let i = 0; i < a.length; i++) {
|
|
300
|
+
if (isNode(a[i]) && isNode(b[i])) { const d = diffTrees(a[i], b[i], sp, language); if (d == null) return whole(); out.push(...d); }
|
|
301
|
+
else if (JSON.stringify(a[i]) !== JSON.stringify(b[i])) return whole();
|
|
302
|
+
}
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (JSON.stringify(normalizeExpr(a)) === JSON.stringify(normalizeExpr(b))) continue;
|
|
306
|
+
if (SCALAR_SKIP.has(k) && (STATEMENT_KINDS.has(o.kind) || (k === 'raw' && o.kind === 'literal'))) continue;
|
|
307
|
+
if (o.kind === 'compare' && k === 'op') { out.push({ op: true, from: a, to: b, node: o }); continue; }
|
|
308
|
+
return whole();
|
|
309
|
+
}
|
|
310
|
+
return out;
|
|
311
|
+
}
|
|
312
|
+
function renderPart(n, old, sp, language) {
|
|
313
|
+
if (n.kind === 'literal' && old?.kind === 'literal' && n.type === old.type && n.type === 'text' && !n.raw) return literalOf(n.value, language, old).raw;
|
|
314
|
+
return renderExpr(n, language);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Where an operator sits between a compare's two sides, in the statement's text. */
|
|
318
|
+
function opRange(sp, node, text) {
|
|
319
|
+
const l = sp.rangeOf(node.left), r = sp.rangeOf(node.right);
|
|
320
|
+
if (!l || !r) return null;
|
|
321
|
+
const mid = text.slice(l[1], r[0]);
|
|
322
|
+
const at = mid.indexOf(String(node.op === '==' && mid.includes('===') ? '===' : node.op));
|
|
323
|
+
const m = mid.match(/(===|!==|==|!=|<=|>=|<|>|\bis not\b|\bnot in\b|\bis\b|\bin\b)/);
|
|
324
|
+
if (!m) return at >= 0 ? [l[1] + at, l[1] + at + node.op.length] : null;
|
|
325
|
+
return [l[1] + m.index, l[1] + m.index + m[0].length];
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const COMPOUND = new Set(['binary', 'logic', 'compare', 'chain', 'conditional', 'not', 'lambda', 'assign']);
|
|
329
|
+
/** The new text of a statement head: the old text with only the differing parts replaced, verified by reading it again. */
|
|
330
|
+
function rewriteCode(code, oldTree, newTree, language) {
|
|
331
|
+
const sp = parseStatementSpans(code, language);
|
|
332
|
+
const attempts = [];
|
|
333
|
+
if (sp && sameExpr(sp.tree, oldTree)) {
|
|
334
|
+
const reps = diffTrees(sp.tree, newTree, sp, language);
|
|
335
|
+
if (reps) {
|
|
336
|
+
const build = (paren) => {
|
|
337
|
+
let text = sp.source;
|
|
338
|
+
const edits = reps.map((r) => {
|
|
339
|
+
if (r.op) { const rg = opRange(sp, r.node, sp.source); if (!rg) return null; return { range: rg, text: r.to }; }
|
|
340
|
+
return { range: r.range, text: paren && COMPOUND.has(r.node.kind) && !COMPOUND.has(r.old?.kind) ? `(${r.text})` : r.text };
|
|
341
|
+
});
|
|
342
|
+
if (edits.some((e) => !e)) return null;
|
|
343
|
+
edits.sort((a, b) => b.range[0] - a.range[0]);
|
|
344
|
+
for (let i = 1; i < edits.length; i++) if (edits[i].range[1] > edits[i - 1].range[0]) return null;
|
|
345
|
+
for (const e of edits) text = text.slice(0, e.range[0]) + e.text + text.slice(e.range[1]);
|
|
346
|
+
return text;
|
|
347
|
+
};
|
|
348
|
+
attempts.push(build(false), build(true));
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// Last: the whole head written from the tree, keeping how the original opened its block.
|
|
352
|
+
try {
|
|
353
|
+
let head = renderStatement(newTree, language);
|
|
354
|
+
if (/\n\s*pass$/.test(head) && language === 'python') head = head.replace(/\n\s*pass$/, '');
|
|
355
|
+
else if (/\{\n\}$/.test(head)) head = head.replace(/\n\}$/, '');
|
|
356
|
+
const trimmed = code.trim();
|
|
357
|
+
if (trimmed.endsWith('{') && !head.endsWith('{')) head = `${head} {`;
|
|
358
|
+
if (!trimmed.endsWith(';') && head.endsWith(';') && !/[{:]$/.test(trimmed)) head = head.replace(/;$/, '');
|
|
359
|
+
attempts.push(head);
|
|
360
|
+
} catch { /* the writer cannot say it */ }
|
|
361
|
+
for (const a of attempts) {
|
|
362
|
+
if (a == null) continue;
|
|
363
|
+
const back = parseStatement(a, language);
|
|
364
|
+
if (sameExpr(back, newTree)) return a;
|
|
365
|
+
}
|
|
366
|
+
needsAi(`The writer could not express "${sayFull(newTree)}" in ${langName(language)} so that it reads back exactly.`);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** The lines of a step's head (its own statement, not its block's steps). */
|
|
370
|
+
function headLines(step) {
|
|
371
|
+
const first = step.span?.startLine ?? step.line;
|
|
372
|
+
const inner = [...(step.children || []), ...(step.otherwise || [])].map((c) => c.line).filter((l) => l != null && l >= first);
|
|
373
|
+
const last = inner.length ? Math.max(first, Math.min(...inner) - 1) : step.span?.endLine ?? first;
|
|
374
|
+
return [first, last];
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Replace a step's head in the file with code for `newTree`. Returns the new source. */
|
|
378
|
+
function writeStepTree(source, step, newTree, language) {
|
|
379
|
+
const [a, b] = headLines(step);
|
|
380
|
+
const starts = lineStarts(source);
|
|
381
|
+
const from = starts[a - 1], to = b < starts.length ? starts[b] - 1 : source.length;
|
|
382
|
+
const region = source.slice(from, to);
|
|
383
|
+
let code = String(step.code ?? '').trim();
|
|
384
|
+
// A head over several lines (a condition that wraps) is edited as a whole when it reads as this step.
|
|
385
|
+
if (b > a) {
|
|
386
|
+
const whole = region.trim().replace(language === 'python' ? /\s*#[^\n'"]*$/ : /\s*\/\/[^\n'"]*$/, '');
|
|
387
|
+
const sp = parseStatementSpans(whole, language);
|
|
388
|
+
if (sp && step.expr && sameExpr(sp.tree, step.expr)) code = whole;
|
|
389
|
+
}
|
|
390
|
+
let at = code ? region.indexOf(code) : -1;
|
|
391
|
+
if (at >= 0 && region.indexOf(code, at + 1) >= 0) at = -1;
|
|
392
|
+
if (at >= 0) {
|
|
393
|
+
const next = rewriteCode(code, step.expr, newTree, language);
|
|
394
|
+
return source.slice(0, from + at) + next + source.slice(from + at + code.length);
|
|
395
|
+
}
|
|
396
|
+
// The step's code is not written in one piece in the file (an elif, a condition over several lines): rewrite only
|
|
397
|
+
// the condition, when it is written exactly once in the step's lines and nothing else about the step changes.
|
|
398
|
+
const testKey = step.expr?.test && newTree.test && sameExpr({ ...step.expr, test: null }, { ...newTree, test: null });
|
|
399
|
+
if (testKey) {
|
|
400
|
+
const sp = parseStatementSpans(code, language);
|
|
401
|
+
const variants = [sp?.textOf(sp.tree.test), (() => { try { return renderExpr(step.expr.test, language); } catch { return null; } })()].filter(Boolean);
|
|
402
|
+
for (const v of variants) {
|
|
403
|
+
const i = region.indexOf(v);
|
|
404
|
+
if (i < 0 || region.indexOf(v, i + 1) >= 0) continue;
|
|
405
|
+
const next = rewriteCode(v, step.expr.test, newTree.test, language);
|
|
406
|
+
return source.slice(0, from + i) + next + source.slice(from + i + v.length);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
needsAi(`The code of the step at line ${step.line} is spread over lines in a way the writer does not edit in place.`);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// ── Writing whole statements and blocks ────────────────────────────────────────────────────────────────────
|
|
413
|
+
|
|
414
|
+
/** Code lines for a list of new steps (trees, with `children` and `otherwise`), indented from `indent`. */
|
|
415
|
+
function renderBlock(steps, language, indent, unit) {
|
|
416
|
+
const out = [];
|
|
417
|
+
for (const s of steps) {
|
|
418
|
+
const tree = s.e;
|
|
419
|
+
let head;
|
|
420
|
+
try { head = renderStatement(tree, language); } catch (e) { needsAi(`${langName(language)} cannot say "${sayFull(tree)}" this way (${e.message}).`); }
|
|
421
|
+
const opens = /\n\s*pass$/.test(head) || /\{\n\}$/.test(head);
|
|
422
|
+
if (!opens) { for (const l of head.split('\n')) out.push(indent + l); continue; }
|
|
423
|
+
const h = language === 'python' ? head.replace(/\n\s*pass$/, '') : head.replace(/\n\}$/, '');
|
|
424
|
+
out.push(indent + h);
|
|
425
|
+
if (s.c?.length) out.push(...renderBlock(s.c, language, indent + unit, unit));
|
|
426
|
+
else if (language === 'python') out.push(`${indent}${unit}pass`);
|
|
427
|
+
if (s.o) {
|
|
428
|
+
if (language === 'python') { out.push(`${indent}else:`); out.push(...(s.o.length ? renderBlock(s.o, language, indent + unit, unit) : [`${indent}${unit}pass`])); }
|
|
429
|
+
else { out.push(`${indent}} else {`); out.push(...renderBlock(s.o, language, indent + unit, unit)); out.push(`${indent}}`); }
|
|
430
|
+
} else if (language !== 'python') out.push(`${indent}}`);
|
|
431
|
+
}
|
|
432
|
+
return out;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** A step a person described, as a shape node: a statement, or { if, then, else }, or { stop, error }. */
|
|
436
|
+
function stepSpec(spec, ctx) {
|
|
437
|
+
const { language } = ctx;
|
|
438
|
+
if (typeof spec === 'string' || spec?.kind) return { e: statementFrom(spec, language), c: [] };
|
|
439
|
+
if (spec && typeof spec === 'object' && 'if' in spec) {
|
|
440
|
+
const test = exprFrom(spec.if, language, 'condition');
|
|
441
|
+
return { e: { kind: 'if', test }, c: (spec.then || []).map((x) => stepSpec(x, ctx)), ...(spec.else ? { o: spec.else.map((x) => stepSpec(x, ctx)) } : {}) };
|
|
442
|
+
}
|
|
443
|
+
if (spec && typeof spec === 'object' && 'stop' in spec) return { e: stopTree(ctx, spec.error, spec.stop), c: [] };
|
|
444
|
+
refuse(`A step must be code (a string), { if, then, else }, or { stop, error }; got ${JSON.stringify(spec)}.`);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ── Stops ──────────────────────────────────────────────────────────────────────────────────────────────────
|
|
448
|
+
|
|
449
|
+
const GO_ZERO = (t) => {
|
|
450
|
+
t = t.trim();
|
|
451
|
+
if (t === 'error' || /^(\*|\[\]|map\[|chan\b|func\b|interface\b)/.test(t) || t === 'any') return 'nil';
|
|
452
|
+
if (/^(bool)$/.test(t)) return 'false';
|
|
453
|
+
if (/^(u?int(8|16|32|64)?|float(32|64)|byte|rune|uintptr|complex(64|128))$/.test(t)) return '0';
|
|
454
|
+
if (t === 'string') return '""';
|
|
455
|
+
return null;
|
|
456
|
+
};
|
|
457
|
+
/** The results a Go function declares: ['bool', 'error'], or [] for none. */
|
|
458
|
+
function goResults(source, item) {
|
|
459
|
+
const sig = signatureRange(source, item, 'go');
|
|
460
|
+
if (!sig) return null;
|
|
461
|
+
const after = source.slice(sig.close + 1, source.indexOf('{', sig.close + 1)).trim();
|
|
462
|
+
if (!after) return [];
|
|
463
|
+
const inner = after.startsWith('(') ? after.slice(1, after.lastIndexOf(')')) : after;
|
|
464
|
+
return splitTop(inner).map((x) => { const parts = x.trim().split(/\s+/); return parts.length > 1 && !/^[*\[]/.test(parts[parts.length - 1]) ? parts.slice(1).join(' ') : x.trim(); });
|
|
465
|
+
}
|
|
466
|
+
/** The comma-separated parts of source[from, to) at the top level, with their offsets. */
|
|
467
|
+
function partsWithOffsets(source, from, to) {
|
|
468
|
+
const out = []; let depth = 0, start = from;
|
|
469
|
+
for (let i = from; i < to; i++) {
|
|
470
|
+
const c = source[i];
|
|
471
|
+
if (c === '"' || c === "'" || c === '`') { const q = c; i++; while (i < to && source[i] !== q) { if (source[i] === '\\') i++; i++; } continue; }
|
|
472
|
+
if ('([{<'.includes(c)) depth++;
|
|
473
|
+
if (')]}>'.includes(c) && source[i - 1] !== '=') depth--;
|
|
474
|
+
if (c === ',' && depth === 0) { out.push({ start, end: i, text: source.slice(start, i) }); start = i + 1; }
|
|
475
|
+
}
|
|
476
|
+
if (source.slice(start, to).trim()) out.push({ start, end: to, text: source.slice(start, to) });
|
|
477
|
+
return out;
|
|
478
|
+
}
|
|
479
|
+
function splitTop(s) {
|
|
480
|
+
const out = []; let depth = 0, cur = '';
|
|
481
|
+
for (const c of s) { if ('([{'.includes(c)) depth++; if (')]}'.includes(c)) depth--; if (c === ',' && depth === 0) { out.push(cur); cur = ''; } else cur += c; }
|
|
482
|
+
if (cur.trim()) out.push(cur);
|
|
483
|
+
return out;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** A text literal spelled the way most text in this file is spelled (its quote style). */
|
|
487
|
+
function quoteLike(source, language) {
|
|
488
|
+
if (language === 'go') return null;
|
|
489
|
+
const single = (String(source).match(/(^|[\s(,=:[])'[^'\n]*'/g) || []).length;
|
|
490
|
+
const double = (String(source).match(/(^|[\s(,=:[])"[^"\n]*"/g) || []).length;
|
|
491
|
+
return single > double ? { type: 'text', raw: "'x'" } : null;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** Add an import to a Go file: into its import ( … ) block in order, beside a single import, or after the package line. */
|
|
495
|
+
function addGoImport(source, pkg) {
|
|
496
|
+
const L = linesOf(source);
|
|
497
|
+
const line = `"${pkg}"`;
|
|
498
|
+
const block = L.findIndex((l) => /^import\s*\($/.test(l.trim()));
|
|
499
|
+
if (block >= 0) {
|
|
500
|
+
let end = block + 1;
|
|
501
|
+
while (end < L.length && L[end].trim() !== ')') end++;
|
|
502
|
+
// The first group (standard library) is kept in order.
|
|
503
|
+
let at = block + 1;
|
|
504
|
+
while (at < end && L[at].trim() && L[at].trim() < line) at++;
|
|
505
|
+
L.splice(at, 0, `\t${line}`);
|
|
506
|
+
return L.join('\n');
|
|
507
|
+
}
|
|
508
|
+
const single = L.findIndex((l) => /^import\s+"/.test(l));
|
|
509
|
+
if (single >= 0) {
|
|
510
|
+
const other = L[single].replace(/^import\s+/, '').trim();
|
|
511
|
+
L.splice(single, 1, 'import (', ...[other, line].sort().map((x) => `\t${x}`), ')');
|
|
512
|
+
return L.join('\n');
|
|
513
|
+
}
|
|
514
|
+
const pkgLine = L.findIndex((l) => /^package\s/.test(l));
|
|
515
|
+
L.splice(pkgLine + 1, 0, '', `import ${line}`);
|
|
516
|
+
return L.join('\n');
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** The tree of a Stop in this file's language: throw new Error("…") / raise ValueError("…") / return …, errors.New("…"). */
|
|
520
|
+
function stopTree(ctx, error, message) {
|
|
521
|
+
const { language, source, item } = ctx;
|
|
522
|
+
if (typeof message !== 'string' || !message.trim()) refuse('A Stop needs a message that says why it stops.');
|
|
523
|
+
const text = literalOf(message, language, quoteLike(source, language)).raw;
|
|
524
|
+
if (language === 'python') return statementFrom(`raise ${error || 'ValueError'}(${text})`, language);
|
|
525
|
+
if (language === 'typescript' || language === 'javascript') return statementFrom(`throw new ${error || 'Error'}(${text});`, language);
|
|
526
|
+
if (language === 'go') {
|
|
527
|
+
const results = goResults(source, item);
|
|
528
|
+
if (!results || !results.length || results[results.length - 1] !== 'error') needsAi(`${item.name} does not give back an error, so a Stop in Go needs its signature changed.`);
|
|
529
|
+
const zeros = results.slice(0, -1).map(GO_ZERO);
|
|
530
|
+
if (zeros.some((z) => z == null)) needsAi(`The writer does not know the empty value of ${results.join(', ')} in Go.`);
|
|
531
|
+
if (error) needsAi('A named error type in Go needs its own constructor; the writer uses errors.New.');
|
|
532
|
+
const pkg = /^\s*"errors"\s*$/m.test(source) || /^import\s+"errors"/m.test(source) ? 'errors.New' : /^\s*"fmt"\s*$/m.test(source) || /^import\s+"fmt"/m.test(source) ? 'fmt.Errorf' : null;
|
|
533
|
+
// Neither imported: "errors" is added to the file's imports (shown in the patch).
|
|
534
|
+
if (!pkg) ctx.goImport = 'errors';
|
|
535
|
+
const msg = pkg === 'fmt.Errorf' ? literalOf(message.replace(/%/g, '%%'), language).raw : text;
|
|
536
|
+
return statementFrom(`return ${[...zeros, `${pkg ?? 'errors.New'}(${msg})`].join(', ')}`, language);
|
|
537
|
+
}
|
|
538
|
+
needsAi(`Stops are written for TypeScript, JavaScript, Python, and Go; this file is ${langName(language)}.`);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// ── Signatures ─────────────────────────────────────────────────────────────────────────────────────────────
|
|
542
|
+
|
|
543
|
+
/** Where a function's inputs are written: { open, close } offsets of its ( and ). */
|
|
544
|
+
function signatureRange(source, item, language) {
|
|
545
|
+
const starts = lineStarts(source);
|
|
546
|
+
const from = starts[item.line - 1];
|
|
547
|
+
const nameAt = (() => {
|
|
548
|
+
const re = new RegExp(`(^|[^\\w$])${item.name.replace(/\$/g, '\\$')}(?![\\w$])`, 'g');
|
|
549
|
+
re.lastIndex = from;
|
|
550
|
+
const m = re.exec(source);
|
|
551
|
+
return m && m.index < from + 2000 ? m.index + m[1].length + item.name.length : -1;
|
|
552
|
+
})();
|
|
553
|
+
if (nameAt < 0) return null;
|
|
554
|
+
let open = source.indexOf('(', nameAt);
|
|
555
|
+
if (open < 0) return null;
|
|
556
|
+
// Go methods name their receiver first: func (s *Svc) Name(…) — the name is found after it, so `open` is right.
|
|
557
|
+
let depth = 0, close = -1;
|
|
558
|
+
for (let i = open; i < source.length; i++) {
|
|
559
|
+
const c = source[i];
|
|
560
|
+
if (c === '"' || c === "'" || c === '`') { const q = c; i++; while (i < source.length && source[i] !== q) { if (source[i] === '\\') i++; i++; } continue; }
|
|
561
|
+
if (c === '(') depth++;
|
|
562
|
+
else if (c === ')') { depth--; if (depth === 0) { close = i; break; } }
|
|
563
|
+
}
|
|
564
|
+
if (close < 0) return null;
|
|
565
|
+
void language;
|
|
566
|
+
return { open, close };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** The last line of a function (its closing brace, or its last indented line in Python). */
|
|
570
|
+
function functionEndLine(source, item, language) {
|
|
571
|
+
const L = linesOf(source);
|
|
572
|
+
if (language === 'python') {
|
|
573
|
+
const base = indentOf(L[item.line - 1]).length;
|
|
574
|
+
let last = item.line;
|
|
575
|
+
let i = item.line;
|
|
576
|
+
// Skip the rest of a signature over several lines.
|
|
577
|
+
while (i < L.length && !/:\s*(#.*)?$/.test(L[i - 1])) i++;
|
|
578
|
+
for (let j = i; j < L.length; j++) {
|
|
579
|
+
const l = L[j];
|
|
580
|
+
if (!l.trim()) continue;
|
|
581
|
+
if (indentOf(l).length <= base) break;
|
|
582
|
+
last = j + 1;
|
|
583
|
+
}
|
|
584
|
+
return last;
|
|
585
|
+
}
|
|
586
|
+
const sig = signatureRange(source, item, language);
|
|
587
|
+
if (!sig) return null;
|
|
588
|
+
const open = source.indexOf('{', sig.close);
|
|
589
|
+
// An arrow with an expression body (`(x) => x + 1`) has no braces of its own: it ends where its steps end.
|
|
590
|
+
if (open < 0 || !/^\s*(?::[^{;=]*?)?\s*(?:=>)?\s*$/.test(source.slice(sig.close + 1, open))) return memberEnd(item);
|
|
591
|
+
const end = blockEnd(source, open, language);
|
|
592
|
+
if (end < 0) return null;
|
|
593
|
+
return lineStarts(source).filter((s) => s <= end).length;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// ── Identifiers (for rename) ───────────────────────────────────────────────────────────────────────────────
|
|
597
|
+
|
|
598
|
+
/** Offsets of the identifier `name` in source[from, to), outside strings and comments (and not after a dot). */
|
|
599
|
+
function identifierSites(source, name, from, to, language) {
|
|
600
|
+
const out = [];
|
|
601
|
+
const comment = language === 'python' ? ['#'] : ['//', '/*'];
|
|
602
|
+
let i = from, prevSig = '';
|
|
603
|
+
const isId = (c) => /[\w$]/.test(c ?? '');
|
|
604
|
+
const scanTemplate = (start, end, open, close) => {
|
|
605
|
+
// Names inside ${…} (JavaScript) or {…} (Python f-strings).
|
|
606
|
+
const body = source.slice(start, end);
|
|
607
|
+
const re = new RegExp(`${open.replace(/[$]/g, '\\$').replace(/[{]/g, '\\{')}([^}]*)${close.replace(/[}]/g, '\\}')}`, 'g');
|
|
608
|
+
let m;
|
|
609
|
+
while ((m = re.exec(body))) {
|
|
610
|
+
const inner = m[1];
|
|
611
|
+
const base = start + m.index + open.length;
|
|
612
|
+
const r2 = new RegExp(`(^|[^\\w$.])(${name.replace(/\$/g, '\\$')})(?![\\w$])`, 'g');
|
|
613
|
+
let k;
|
|
614
|
+
while ((k = r2.exec(inner))) out.push(base + k.index + k[1].length);
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
while (i < to) {
|
|
618
|
+
const c = source[i];
|
|
619
|
+
if (comment.some((s) => source.startsWith(s, i))) {
|
|
620
|
+
if (source.startsWith('/*', i)) { const j = source.indexOf('*/', i + 2); i = j < 0 ? to : j + 2; }
|
|
621
|
+
else { const j = source.indexOf('\n', i); i = j < 0 ? to : j; }
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
625
|
+
const prefix = language === 'python' ? (source.slice(Math.max(0, i - 2), i).match(/[fFrRbBuU]{0,2}$/)?.[0] ?? '') : '';
|
|
626
|
+
const triple = language === 'python' && source.startsWith(c.repeat(3), i);
|
|
627
|
+
const endQ = triple ? c.repeat(3) : c;
|
|
628
|
+
let j = i + endQ.length;
|
|
629
|
+
while (j < source.length && !source.startsWith(endQ, j)) j += source[j] === '\\' ? 2 : 1;
|
|
630
|
+
const end = j;
|
|
631
|
+
if (c === '`' && language !== 'go') scanTemplate(i + 1, end, '${', '}');
|
|
632
|
+
if (/[fF]/.test(prefix)) scanTemplate(i + endQ.length, end, '{', '}');
|
|
633
|
+
i = end + endQ.length;
|
|
634
|
+
prevSig = c;
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
// A Python string prefix (r"…", f'…', rb"…") belongs to the string, not a name.
|
|
638
|
+
if (language === 'python' && /[rRbBuUfF]/.test(c) && !isId(source[i - 1])) { const m = source.slice(i, i + 3).match(/^[rRbBuUfF]{1,2}(?=["'])/); if (m) { i += m[0].length; continue; } }
|
|
639
|
+
if (isId(c) && !/\d/.test(c)) {
|
|
640
|
+
let j = i;
|
|
641
|
+
while (j < to && isId(source[j])) j++;
|
|
642
|
+
const word = source.slice(i, j);
|
|
643
|
+
// After a dot (also across lines: `x\n .name`) it is a field or method of something else.
|
|
644
|
+
if (word === name && prevSig !== '.') out.push(i);
|
|
645
|
+
i = j;
|
|
646
|
+
prevSig = 'a';
|
|
647
|
+
continue;
|
|
648
|
+
}
|
|
649
|
+
if (c === '.' && source.startsWith('...', i)) { prevSig = '…'; i += 3; continue; }
|
|
650
|
+
if (!/\s/.test(c)) prevSig = c;
|
|
651
|
+
i++;
|
|
652
|
+
}
|
|
653
|
+
return out.sort((a, b) => a - b);
|
|
654
|
+
}
|
|
655
|
+
const renameTree = (tree, from, to) => {
|
|
656
|
+
const t = cloneShape(tree);
|
|
657
|
+
// Object keys ({ days: 1 }, Go's Command{Use: …}) name a field, not this name: they are left alone.
|
|
658
|
+
const keys = new Set();
|
|
659
|
+
for (const n of nodesOf(t)) if (n.kind === 'object') for (const e of n.entries || []) if (e.key && !e.computed && !e.shorthand && e.key.kind === 'name') keys.add(e.key);
|
|
660
|
+
const idRe = new RegExp(`(^|[^\\w$.])${from.replace(/\$/g, '\\$')}(?![\\w$])`, 'g');
|
|
661
|
+
for (const n of nodesOf(t)) {
|
|
662
|
+
if (keys.has(n)) continue;
|
|
663
|
+
if (n.kind === 'object') for (const e of n.entries || []) if (e.shorthand && e.value?.kind === 'name' && e.value.name === from) { delete e.shorthand; if (!e.key) e.key = { kind: 'name', name: from }; keys.add(e.key); }
|
|
664
|
+
// Code Thunder keeps as text: its names are renamed in the text (outside quotes).
|
|
665
|
+
if (n.kind === 'code' && typeof n.text === 'string') n.text = n.text.split(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/).map((part, i) => (i % 2 ? part : part.replace(idRe, `$1${to}`))).join('');
|
|
666
|
+
if (n.kind === 'name' && n.name === from) n.name = to;
|
|
667
|
+
if (n.kind === 'lambda' && Array.isArray(n.params)) n.params = n.params.map((p) => (p === from ? to : p));
|
|
668
|
+
if (n.kind === 'pattern' && Array.isArray(n.names)) { n.names = n.names.map((p) => (p === from ? to : p)); n.text = n.text.replace(new RegExp(`\\b${from}\\b`, 'g'), to); }
|
|
669
|
+
if (n.kind === 'declare' && Array.isArray(n.names)) n.names = n.names.map((p) => (p === from ? to : p));
|
|
670
|
+
if (n.kind === 'function' && n.name === from) n.name = to;
|
|
671
|
+
// Names written inside text ("…{name}…", `…${name}…`) are kept in a throw's message and in interpolated text.
|
|
672
|
+
if (n.kind === 'throw' && typeof n.message === 'string') n.message = inBraces(n.message, from, to);
|
|
673
|
+
if (n.kind === 'literal' && n.interpolated) { if (typeof n.raw === 'string') n.raw = inBraces(n.raw, from, to); if (typeof n.value === 'string') n.value = inBraces(n.value, from, to); }
|
|
674
|
+
}
|
|
675
|
+
return t;
|
|
676
|
+
};
|
|
677
|
+
const inBraces = (text, from, to) => text.replace(/\{[^{}]*\}/g, (m) => m.replace(new RegExp(`(^|[^\\w$.])${from.replace(/\$/g, '\\$')}(?![\\w$])`, 'g'), `$1${to}`));
|
|
678
|
+
const renameShape = (shape, from, to) => shape.map((s) => ({ ...s, e: s.e ? renameTree(s.e, from, to) : s.e, c: renameShape(s.c || [], from, to), ...(s.o ? { o: renameShape(s.o, from, to) } : {}), ...(s.h ? { h: s.h.map((h) => ({ e: h.e ? renameTree(h.e, from, to) : h.e, c: renameShape(h.c, from, to) })) } : {}), ...(s.a ? { a: renameShape(s.a, from, to) } : {}) }));
|
|
679
|
+
const namesUsed = (shape) => {
|
|
680
|
+
const out = new Set();
|
|
681
|
+
const go = (list) => { for (const s of list || []) { if (s.e) for (const n of nodesOf(s.e)) if (n.kind === 'name') out.add(n.name); go(s.c); go(s.o); (s.h || []).forEach((h) => go(h.c)); go(s.a); } };
|
|
682
|
+
go(shape);
|
|
683
|
+
return out;
|
|
684
|
+
};
|
|
685
|
+
const firstUse = (steps, name) => {
|
|
686
|
+
let line = null;
|
|
687
|
+
const go = (list) => { for (const s of list || []) { if (line != null) return; if (s.expr && [...nodesOf(s.expr)].some((n) => n.kind === 'name' && n.name === name)) { line = s.line; return; } go(s.children); go(s.otherwise); (s.handlers || []).forEach((h) => go(h.steps)); go(s.always?.steps); } };
|
|
688
|
+
go(steps);
|
|
689
|
+
return line;
|
|
690
|
+
};
|
|
691
|
+
|
|
692
|
+
// ── Line edits ─────────────────────────────────────────────────────────────────────────────────────────────
|
|
693
|
+
|
|
694
|
+
const stepLines = (step) => [step.span?.startLine ?? step.line, step.span?.endLine ?? step.line];
|
|
695
|
+
function spliceLines(source, start, deleteCount, insert = []) {
|
|
696
|
+
const L = linesOf(source);
|
|
697
|
+
L.splice(start - 1, deleteCount, ...insert);
|
|
698
|
+
return L.join('\n');
|
|
699
|
+
}
|
|
700
|
+
/** A step's lines must hold that step alone (not `} else {`, not two statements on one line). */
|
|
701
|
+
function ownsLines(source, step) {
|
|
702
|
+
const [a, b] = stepLines(step);
|
|
703
|
+
const L = linesOf(source);
|
|
704
|
+
const first = L[a - 1]?.trim() ?? '';
|
|
705
|
+
const code = String(step.code ?? '').trim();
|
|
706
|
+
// Letters and digits only: the reader's code can differ from the file in punctuation and spacing.
|
|
707
|
+
const a1 = first.replace(/[^A-Za-z0-9_]+/g, ''), c1 = code.replace(/[^A-Za-z0-9_]+/g, '');
|
|
708
|
+
if (!a1 || !c1.startsWith(a1.slice(0, Math.min(a1.length, c1.length, 10)))) return false;
|
|
709
|
+
const last = L[b - 1]?.trim() ?? '';
|
|
710
|
+
if (b > a && /^\}\s*(else|catch|finally)\b/.test(last)) return false;
|
|
711
|
+
// Something after the step on its last line (another statement) means the lines are shared.
|
|
712
|
+
return true;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// ── The operations ─────────────────────────────────────────────────────────────────────────────────────────
|
|
716
|
+
|
|
717
|
+
const SIDES = { yes: 'c', no: 'o' };
|
|
718
|
+
const sayStep = (s) => s?.says ?? sayFull(s?.expr ?? { kind: 'code', text: s?.code ?? '' });
|
|
719
|
+
const q = (s) => `"${s}"`;
|
|
720
|
+
|
|
721
|
+
/** Find the literal in a step to change: by its old value, or the only literal there is. */
|
|
722
|
+
function findLiteral(tree, from) {
|
|
723
|
+
const lits = [...nodesOf(tree)].filter((n) => n.kind === 'literal' && /^(number|text|bool|null)$/.test(n.type));
|
|
724
|
+
if (from === undefined) {
|
|
725
|
+
if (lits.length === 1) return lits[0];
|
|
726
|
+
refuse(lits.length ? `This step has ${lits.length} values (${lits.map((l) => l.raw).join(', ')}); say which one with "from".` : 'This step has no value to change.');
|
|
727
|
+
}
|
|
728
|
+
const hits = lits.filter((l) => l.value === from || l.raw === String(from) || (typeof from === 'string' && l.type === 'number' && Number(from) === l.value));
|
|
729
|
+
if (hits.length === 1) return hits[0];
|
|
730
|
+
if (!hits.length) refuse(`This step has no value ${JSON.stringify(from)}${lits.length ? `; it has ${lits.map((l) => l.raw).join(', ')}` : ''}.`);
|
|
731
|
+
refuse(`The value ${JSON.stringify(from)} is in this step ${hits.length} times; the writer changes one value at a time ("at" picks which, from 0).`);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function opSetValue(ctx, edit) {
|
|
735
|
+
const { step } = ctx.at(edit.step);
|
|
736
|
+
if (!step.expr || step.expr.kind === 'code') needsAi(`The step at line ${step.line} is shown as code; Thunder has no tree for it to change exactly.`);
|
|
737
|
+
const tree = cloneShape(step.expr);
|
|
738
|
+
let lit;
|
|
739
|
+
if (edit.at != null) {
|
|
740
|
+
const lits = [...nodesOf(tree)].filter((n) => n.kind === 'literal' && (edit.from === undefined || n.value === edit.from || n.raw === String(edit.from)));
|
|
741
|
+
lit = lits[edit.at];
|
|
742
|
+
if (!lit) refuse(`There is no value number ${edit.at} like that in this step.`);
|
|
743
|
+
} else lit = findLiteral(tree, edit.from);
|
|
744
|
+
const next = literalOf(edit.to, ctx.language, lit);
|
|
745
|
+
if (next.type === lit.type && next.value === lit.value) refuse(`The value is already ${lit.raw}.`);
|
|
746
|
+
const old = lit.raw;
|
|
747
|
+
Object.keys(lit).forEach((k) => delete lit[k]);
|
|
748
|
+
Object.assign(lit, next);
|
|
749
|
+
ctx.setTree(step, tree);
|
|
750
|
+
return `Changed ${old} to ${next.raw} in ${q(sayStep(step))}`;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
const CMP_OPS = ['<', '<=', '>', '>=', '==', '!=', '===', '!=='];
|
|
754
|
+
function opSetCondition(ctx, edit) {
|
|
755
|
+
const { step } = ctx.at(edit.step);
|
|
756
|
+
const e = step.expr;
|
|
757
|
+
if (!e || !(e.kind === 'if' || (e.kind === 'loop' && e.test))) refuse(`The step at line ${step.line} is not a question (an if) or a repeat-while; only those have a condition.`);
|
|
758
|
+
if (e.kind === 'if' && e.negate) needsAi('This question is written with unless; the writer does not edit it in place.');
|
|
759
|
+
const tree = cloneShape(e);
|
|
760
|
+
let test = tree.test;
|
|
761
|
+
const clauses = () => (test.kind === 'logic' ? test.operands : [test]);
|
|
762
|
+
const pick = (i) => {
|
|
763
|
+
const cs = clauses();
|
|
764
|
+
if (i == null) { if (cs.length === 1) return { node: cs[0], set: (n) => { test = n; } }; refuse(`This question has ${cs.length} parts joined by ${test.op}; say which part with "clause" (from 0).`); }
|
|
765
|
+
if (!cs[i]) refuse(`This question has ${cs.length} part${cs.length === 1 ? '' : 's'}; there is no part ${i}.`);
|
|
766
|
+
return { node: cs[i], set: (n) => { if (test.kind === 'logic') test.operands[i] = n; else test = n; } };
|
|
767
|
+
};
|
|
768
|
+
const did = [];
|
|
769
|
+
if (edit.when != null) { test = exprFrom(edit.when, ctx.language, 'condition'); did.push(`now asks ${sayFull(test)}`); }
|
|
770
|
+
if (edit.compare != null) {
|
|
771
|
+
const { node } = pick(edit.clause);
|
|
772
|
+
const target = node.kind === 'not' ? null : node;
|
|
773
|
+
if (!target || target.kind !== 'compare') refuse('That part of the question is not a comparison, so it has no comparison to change.');
|
|
774
|
+
let op = String(edit.compare);
|
|
775
|
+
if ((ctx.language === 'typescript' || ctx.language === 'javascript') && (op === '==' || op === '!=') && /===|!==/.test(target.op)) op += '=';
|
|
776
|
+
if (!CMP_OPS.includes(op)) refuse(`${op} is not a comparison (use <, <=, >, >=, ==, !=).`);
|
|
777
|
+
if (target.op === op) refuse(`The comparison is already ${op}.`);
|
|
778
|
+
did.push(`changed ${target.op} to ${op}`);
|
|
779
|
+
target.op = op;
|
|
780
|
+
}
|
|
781
|
+
if (edit.operand != null) {
|
|
782
|
+
const { node } = pick(edit.clause);
|
|
783
|
+
const side = edit.operand.side || 'right';
|
|
784
|
+
const target = node.kind === 'compare' ? node : null;
|
|
785
|
+
if (!target) refuse('That part of the question is not a comparison, so it has no sides.');
|
|
786
|
+
if (side !== 'left' && side !== 'right') refuse('A side is "left" or "right".');
|
|
787
|
+
const next = exprFrom(edit.operand.to, ctx.language, 'value');
|
|
788
|
+
const like = target[side];
|
|
789
|
+
target[side] = next.kind === 'literal' && like.kind === 'literal' && next.type === like.type ? literalOf(next.value, ctx.language, like) : next;
|
|
790
|
+
did.push(`changed ${renderExpr(like, ctx.language)} to ${renderExpr(target[side], ctx.language)}`);
|
|
791
|
+
}
|
|
792
|
+
if (edit.negate) {
|
|
793
|
+
if (edit.clause != null) {
|
|
794
|
+
const { node, set } = pick(edit.clause);
|
|
795
|
+
set(node.kind === 'not' ? node.value : { kind: 'not', value: node });
|
|
796
|
+
} else test = test.kind === 'not' ? test.value : { kind: 'not', value: test };
|
|
797
|
+
did.push('turned the question around');
|
|
798
|
+
}
|
|
799
|
+
if (edit.addClause != null) {
|
|
800
|
+
const join = edit.addClause.join || 'and';
|
|
801
|
+
if (join !== 'and' && join !== 'or') refuse('A new part joins with "and" or "or".');
|
|
802
|
+
const part = exprFrom(edit.addClause.when, ctx.language, 'condition');
|
|
803
|
+
test = test.kind === 'logic' && test.op === join ? { ...test, operands: [...test.operands, part] } : { kind: 'logic', op: join, operands: [test, part] };
|
|
804
|
+
did.push(`added "${join} ${sayFull(part)}"`);
|
|
805
|
+
}
|
|
806
|
+
if (edit.removeClause != null) {
|
|
807
|
+
if (test.kind !== 'logic') refuse('This question has one part; remove the question instead (removeStep).');
|
|
808
|
+
const i = Number(edit.removeClause);
|
|
809
|
+
if (!test.operands[i]) refuse(`This question has ${test.operands.length} parts; there is no part ${i}.`);
|
|
810
|
+
const ops = test.operands.filter((_, k) => k !== i);
|
|
811
|
+
did.push(`removed "${sayFull(test.operands[i])}"`);
|
|
812
|
+
test = ops.length === 1 ? ops[0] : { ...test, operands: ops };
|
|
813
|
+
}
|
|
814
|
+
if (!did.length) refuse('Say what to change in the question: when, compare, operand, negate, addClause, or removeClause.');
|
|
815
|
+
tree.test = test;
|
|
816
|
+
if (sameExpr(tree, e)) refuse('Nothing would change: the question already reads that way.');
|
|
817
|
+
ctx.setTree(step, tree);
|
|
818
|
+
return `Changed the question ${q(sayStep(step))}: ${did.join(', ')}`;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function opSetGivesBack(ctx, edit) {
|
|
822
|
+
if (edit.type != null) {
|
|
823
|
+
const { item, language } = ctx;
|
|
824
|
+
const sig = signatureRange(ctx.source, item, language);
|
|
825
|
+
if (!sig) needsAi('The writer could not find where this function declares what it gives back.');
|
|
826
|
+
const src = ctx.source;
|
|
827
|
+
const bodyOpen = language === 'python' ? src.indexOf(':', sig.close) : src.indexOf('{', sig.close);
|
|
828
|
+
const between = src.slice(sig.close + 1, bodyOpen);
|
|
829
|
+
let next;
|
|
830
|
+
if (language === 'python') next = /->/.test(between) ? between.replace(/->\s*[^:]+?(\s*)$/, `-> ${edit.type}$1`) : `${between.replace(/\s*$/, '')} -> ${edit.type}`;
|
|
831
|
+
else if (language === 'typescript') next = /:/.test(between) ? between.replace(/:\s*[^{]+?(\s*)$/, `: ${edit.type}$1`) : `: ${edit.type} `;
|
|
832
|
+
else if (language === 'go') next = between.trim() ? ` ${edit.type} ` : ` ${edit.type} `;
|
|
833
|
+
else needsAi(`${langName(language)} has no declared kind of answer the writer can change.`);
|
|
834
|
+
if (between === next) refuse(`It already gives back ${edit.type}.`);
|
|
835
|
+
ctx.replaceText(sig.close + 1, bodyOpen, next);
|
|
836
|
+
ctx.expectReturns = edit.type;
|
|
837
|
+
return `Now gives back ${edit.type}`;
|
|
838
|
+
}
|
|
839
|
+
let target;
|
|
840
|
+
if (edit.step != null) target = ctx.at(edit.step).step;
|
|
841
|
+
else {
|
|
842
|
+
const rets = [];
|
|
843
|
+
const go = (list) => (list || []).forEach((s) => { if (s.expr?.kind === 'return') rets.push(s); go(s.children); go(s.otherwise); });
|
|
844
|
+
go(ctx.steps);
|
|
845
|
+
if (rets.length !== 1) refuse(`${ctx.item.name} gives back in ${rets.length} places; say which with "step".`);
|
|
846
|
+
target = rets[0];
|
|
847
|
+
}
|
|
848
|
+
if (target.expr?.kind !== 'return') refuse(`The step at line ${target.line} does not give anything back.`);
|
|
849
|
+
if (edit.value === undefined) refuse('Say the new value with "value".');
|
|
850
|
+
// Several values at once (Go and Python: `true, nil`) are read as a return statement.
|
|
851
|
+
const several = typeof edit.value === 'string' && splitTop(edit.value).length > 1 && ctx.language !== 'typescript' && ctx.language !== 'javascript';
|
|
852
|
+
const value = several ? (() => { const t = parseStatement(`return ${edit.value}`, ctx.language); if (t.kind !== 'return' || !t.value) refuse(`The value "${edit.value}" could not be read.`); return t.value; })() : exprFrom(edit.value, ctx.language, 'value');
|
|
853
|
+
const tree = { ...cloneShape(target.expr), value: value.kind === 'literal' && target.expr.value?.kind === 'literal' && value.type === target.expr.value.type ? literalOf(value.value, ctx.language, target.expr.value) : value };
|
|
854
|
+
if (sameExpr(tree, target.expr)) refuse('It already gives that back.');
|
|
855
|
+
ctx.setTree(target, tree);
|
|
856
|
+
return `Changed ${q(sayStep(target))} to give back ${renderExpr(tree.value, ctx.language)}`;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** Where a new step goes: { lineIndex (insert before this 1-based line), indent, shapeList, shapeIndex }. */
|
|
860
|
+
function placeFor(ctx, edit) {
|
|
861
|
+
const pos = ['before', 'after', 'into'].find((k) => edit[k] != null);
|
|
862
|
+
if (!pos) refuse('Say where the new step goes: before, after, or into ({ step, side: "yes" | "no", at: "start" | "end" }).');
|
|
863
|
+
if (pos === 'into') {
|
|
864
|
+
const into = typeof edit.into === 'object' && !Array.isArray(edit.into) ? edit.into : { step: edit.into };
|
|
865
|
+
const loc = ctx.at(into.step);
|
|
866
|
+
const p = loc.step;
|
|
867
|
+
const side = into.side || 'yes';
|
|
868
|
+
if (!SIDES[side]) refuse('A side is "yes" or "no".');
|
|
869
|
+
const kids = side === 'yes' ? p.children || [] : p.otherwise;
|
|
870
|
+
if (!(p.expr?.kind === 'if' || p.expr?.kind === 'loop' || (side === 'yes' && p.children))) refuse(`The step at line ${p.line} is not a question or a repeat, so it has no side to add to.`);
|
|
871
|
+
if (side === 'no' && !kids) return { pos, newElse: true, loc };
|
|
872
|
+
if (!kids?.length) needsAi(`The ${side} side of ${q(sayStep(p))} is empty in the code; the writer adds next to an existing step.`);
|
|
873
|
+
const atEnd = into.at !== 'start';
|
|
874
|
+
const anchor = atEnd ? kids[kids.length - 1] : kids[0];
|
|
875
|
+
const [a, b] = stepLines(anchor);
|
|
876
|
+
return { pos, line: atEnd ? b + 1 : a, indent: indentOf(linesOf(ctx.source)[a - 1]), shapePath: [...loc.path, ...(side === 'no' ? ['else'] : []), atEnd ? kids.length : 0], loc };
|
|
877
|
+
}
|
|
878
|
+
const loc = ctx.at(edit[pos]);
|
|
879
|
+
const [a, b] = stepLines(loc.step);
|
|
880
|
+
if (!ownsLines(ctx.source, loc.step)) needsAi(`The step at line ${loc.step.line} shares its lines with other code, so the writer cannot place a step ${pos} it.`);
|
|
881
|
+
const path = [...loc.path];
|
|
882
|
+
if (pos === 'after') path[path.length - 1] += 1;
|
|
883
|
+
return { pos, line: pos === 'after' ? b + 1 : a, indent: indentOf(linesOf(ctx.source)[a - 1]), shapePath: path, loc };
|
|
884
|
+
}
|
|
885
|
+
function insertShape(shape, path, nodes) {
|
|
886
|
+
const list = path.length === 1 ? shape : (() => {
|
|
887
|
+
const parentPath = path.slice(0, -1);
|
|
888
|
+
if (parentPath[parentPath.length - 1] === 'else') { const n = pathIn(shape, parentPath.slice(0, -1)).node; return n.o ?? (n.o = []); }
|
|
889
|
+
return pathIn(shape, parentPath).node.c;
|
|
890
|
+
})();
|
|
891
|
+
list.splice(path[path.length - 1], 0, ...nodes);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function insertSteps(ctx, edit, nodes) {
|
|
895
|
+
const place = placeFor(ctx, edit);
|
|
896
|
+
const unit = indentUnit(ctx.source, ctx.language);
|
|
897
|
+
if (place.newElse) {
|
|
898
|
+
// A new "no" side: an else block after the question's own block.
|
|
899
|
+
const p = place.loc.step;
|
|
900
|
+
const [, end] = stepLines(p);
|
|
901
|
+
const L = linesOf(ctx.source);
|
|
902
|
+
const ind = indentOf(L[p.line - 1]);
|
|
903
|
+
const body = renderBlock(nodes, ctx.language, ind + unit, unit);
|
|
904
|
+
if (ctx.language === 'python') ctx.lines(end + 1, 0, [`${ind}else:`, ...body]);
|
|
905
|
+
else {
|
|
906
|
+
if (L[end - 1].trim() !== '}') needsAi(`The question at line ${p.line} does not end with a } on its own line, so the writer cannot add its other side.`);
|
|
907
|
+
ctx.lines(end, 1, [`${ind}} else {`, ...body, `${ind}}`]);
|
|
908
|
+
}
|
|
909
|
+
const sp = pathIn(ctx.shape, place.loc.path).node;
|
|
910
|
+
sp.o = nodes;
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
ctx.lines(place.line, 0, renderBlock(nodes, ctx.language, place.indent, unit));
|
|
914
|
+
insertShape(ctx.shape, place.shapePath, nodes);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
function removeAt(ctx, loc, { replaceWithPass = true } = {}) {
|
|
918
|
+
const [a, b] = stepLines(loc.step);
|
|
919
|
+
if (!ownsLines(ctx.source, loc.step)) needsAi(`The step at line ${loc.step.line} shares its lines with other code, so the writer cannot remove it alone.`);
|
|
920
|
+
const L = linesOf(ctx.source);
|
|
921
|
+
// A Python block that would be left empty keeps a `pass`.
|
|
922
|
+
const siblings = loc.list.filter((s) => s.expr?.kind !== 'pass');
|
|
923
|
+
if (ctx.language === 'python' && siblings.length === 1 && loc.parent && replaceWithPass) ctx.lines(a, b - a + 1, [`${indentOf(L[a - 1])}pass`]);
|
|
924
|
+
else ctx.lines(a, b - a + 1, []);
|
|
925
|
+
listAt(ctx.shape, loc.path).splice(loc.path[loc.path.length - 1], 1);
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
function opAddStep(ctx, edit) {
|
|
929
|
+
if (edit.step == null && edit.steps == null) refuse('Say the new step with "step" (code, { if, then }, or { stop }).');
|
|
930
|
+
const nodes = (edit.steps ?? [edit.step]).map((s) => stepSpec(s, ctx));
|
|
931
|
+
insertSteps(ctx, edit, nodes);
|
|
932
|
+
return `Added ${nodes.map((n) => q(sayFull(n.e))).join(', ')}`;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
function opRemoveStep(ctx, edit) {
|
|
936
|
+
const loc = ctx.at(edit.step);
|
|
937
|
+
removeAt(ctx, loc);
|
|
938
|
+
return `Removed ${q(sayStep(loc.step))}${loc.step.children?.length ? ` and the ${loc.step.children.length} step${loc.step.children.length === 1 ? '' : 's'} inside it` : ''}`;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
function opMoveStep(ctx, edit) {
|
|
942
|
+
const loc = ctx.at(edit.step);
|
|
943
|
+
const pos = edit.before != null ? 'before' : edit.after != null ? 'after' : refuse('Say where it moves: before or after another step.');
|
|
944
|
+
const dest = ctx.at(edit[pos]);
|
|
945
|
+
if (dest.step === loc.step) refuse('A step cannot move next to itself.');
|
|
946
|
+
if (dest.path.join('.').startsWith(`${loc.path.join('.')}.`)) refuse('A step cannot move inside itself.');
|
|
947
|
+
if (!ownsLines(ctx.source, loc.step) || !ownsLines(ctx.source, dest.step)) needsAi('One of the steps shares its lines with other code, so the writer cannot move it alone.');
|
|
948
|
+
const [a, b] = stepLines(loc.step);
|
|
949
|
+
const [da, db] = stepLines(dest.step);
|
|
950
|
+
const L = linesOf(ctx.source);
|
|
951
|
+
const moved = L.slice(a - 1, b);
|
|
952
|
+
const fromIndent = indentOf(moved[0]), toIndent = indentOf(L[da - 1]);
|
|
953
|
+
const re = moved.map((l) => (l.startsWith(fromIndent) ? toIndent + l.slice(fromIndent.length) : l));
|
|
954
|
+
const at = pos === 'before' ? da : db + 1;
|
|
955
|
+
if (at >= a && at <= b + 1) refuse('The step is already there.');
|
|
956
|
+
// Shape: take it out, then put it in at the destination (positions are computed on the shape after removal).
|
|
957
|
+
const node = listAt(ctx.shape, loc.path)[loc.path[loc.path.length - 1]];
|
|
958
|
+
// Insert first when the destination is below, so line numbers above stay right.
|
|
959
|
+
if (at > b) { ctx.lines(at, 0, re); ctx.lines(a, b - a + 1, []); } else { ctx.lines(a, b - a + 1, []); ctx.lines(at, 0, re); }
|
|
960
|
+
const destKey = dest.path.join('.');
|
|
961
|
+
listAt(ctx.shape, loc.path).splice(loc.path[loc.path.length - 1], 1);
|
|
962
|
+
// Find the destination again in the shape by walking the old paths (the moved step is gone).
|
|
963
|
+
const destPath = [...dest.path];
|
|
964
|
+
const lp = loc.path;
|
|
965
|
+
if (lp.length <= destPath.length && lp.slice(0, -1).join('.') === destPath.slice(0, lp.length - 1).join('.') && lp[lp.length - 1] < destPath[lp.length - 1]) destPath[lp.length - 1] -= 1;
|
|
966
|
+
void destKey;
|
|
967
|
+
if (pos === 'after') destPath[destPath.length - 1] += 1;
|
|
968
|
+
if (ctx.language === 'python' && loc.list.length === 1 && loc.parent) needsAi('Moving the only step out of a Python block would leave it empty.');
|
|
969
|
+
insertShape(ctx.shape, destPath, [node]);
|
|
970
|
+
return `Moved ${q(sayStep(loc.step))} ${pos} ${q(sayStep(dest.step))}`;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
function opAddStop(ctx, edit) {
|
|
974
|
+
const stop = { e: stopTree(ctx, edit.error, edit.message), c: [] };
|
|
975
|
+
if (edit.when != null) {
|
|
976
|
+
// A new question that stops: if <when>, stop.
|
|
977
|
+
const test = exprFrom(edit.when, ctx.language, 'condition');
|
|
978
|
+
insertSteps(ctx, edit, [{ e: { kind: 'if', test }, c: [stop] }]);
|
|
979
|
+
return `Added a Stop: if ${sayFull(test)}, stop with ${q(edit.message)}`;
|
|
980
|
+
}
|
|
981
|
+
if (edit.step == null) refuse('Say where the Stop goes: a new question ("when" and before/after), or a question\'s side ("step" and "side").');
|
|
982
|
+
const loc = ctx.at(edit.step);
|
|
983
|
+
if (loc.step.expr?.kind !== 'if') refuse(`The step at line ${loc.step.line} is not a question, so it has no side to stop on.`);
|
|
984
|
+
const side = edit.side || 'yes';
|
|
985
|
+
const kids = side === 'yes' ? loc.step.children : loc.step.otherwise;
|
|
986
|
+
const last = kids?.[kids.length - 1];
|
|
987
|
+
if (last && /^(return|throw)$/.test(last.expr?.kind ?? '')) refuse(`The ${side} side of ${q(sayStep(loc.step))} already ends (${q(sayStep(last))}); a Stop after it would never be reached.`);
|
|
988
|
+
if (side === 'no' && loc.step.otherwise?.length && loc.step.otherwise.length === 1 && loc.step.otherwise[0].expr?.kind === 'if' && !ctx.source.split('\n')[loc.step.otherwise[0].line - 1].includes('{')) needsAi('The no side is an else-if chain; the writer does not add to it.');
|
|
989
|
+
insertSteps(ctx, { into: { step: edit.step, side, at: 'end' } }, [stop]);
|
|
990
|
+
return `Added a Stop on the ${side} side of ${q(sayStep(loc.step))}: ${q(edit.message)}`;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
function opRemoveStop(ctx, edit) {
|
|
994
|
+
const loc = ctx.at(edit.step);
|
|
995
|
+
const isStop = loc.step.kind === 'fail' || loc.step.expr?.kind === 'throw';
|
|
996
|
+
if (!isStop) refuse(`The step at line ${loc.step.line} is not a Stop (${q(sayStep(loc.step))}).`);
|
|
997
|
+
const parent = loc.parent;
|
|
998
|
+
if (parent && parent.expr?.kind === 'if' && parent.children?.length === 1 && parent.children[0] === loc.step && !parent.otherwise?.length) {
|
|
999
|
+
// The Stop was all its question did: the question goes too.
|
|
1000
|
+
const ploc = ctx.at([...loc.path.slice(0, -1)]);
|
|
1001
|
+
removeAt(ctx, ploc);
|
|
1002
|
+
return `Removed the Stop ${q(sayStep(loc.step))} and its question ${q(sayStep(parent))}`;
|
|
1003
|
+
}
|
|
1004
|
+
removeAt(ctx, loc);
|
|
1005
|
+
return `Removed the Stop ${q(sayStep(loc.step))}`;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
function opAddInput(ctx, edit) {
|
|
1009
|
+
const { item, language } = ctx;
|
|
1010
|
+
const name = String(edit.name ?? '');
|
|
1011
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name)) refuse(`"${name}" is not a name an input can have.`);
|
|
1012
|
+
if ((item.inputs || []).some((p) => p.name === name)) refuse(`${item.name} already has an input named ${name}.`);
|
|
1013
|
+
// A name the function already used before this change would now mean the new input: refused. A name an earlier
|
|
1014
|
+
// edit in this same change introduced (days > limit, then add the input limit) is what the input is for.
|
|
1015
|
+
if (namesUsed(ctx.originalShape()).has(name)) refuse(`${name} is already used inside ${item.name}; adding an input with that name would change what it means.`);
|
|
1016
|
+
const sig = signatureRange(ctx.source, item, language);
|
|
1017
|
+
if (!sig) needsAi('The writer could not find where this function lists its inputs.');
|
|
1018
|
+
const inner = ctx.source.slice(sig.open + 1, sig.close);
|
|
1019
|
+
if (language === 'go' && !edit.type) refuse('Go needs the input\'s type ("type").');
|
|
1020
|
+
const def = edit.default !== undefined ? renderExpr(exprFrom(edit.default, language, 'default'), language) : null;
|
|
1021
|
+
if (def != null && language === 'go') needsAi('Go has no default values for inputs.');
|
|
1022
|
+
const params = splitTop(inner).map((p) => p.trim()).filter(Boolean);
|
|
1023
|
+
const star = language === 'python' && params.some((p) => /^\*/.test(p));
|
|
1024
|
+
if (language === 'python' && !star && def == null && params.some((p) => /=/.test(p))) refuse(`In Python an input without a default cannot come after inputs with defaults; give ${name} a default.`);
|
|
1025
|
+
if (language === 'typescript' && def == null && params.some((p) => /\?\s*:|=/.test(p))) refuse(`In TypeScript a required input cannot come after optional ones; give ${name} a default.`);
|
|
1026
|
+
if (params.some((p) => /^\.\.\./.test(p) || /\.\.\.\S/.test(p))) needsAi('This function takes a variable number of inputs at the end; a new input before them would change what callers pass, so the writer does not add one.');
|
|
1027
|
+
const typed = edit.type ? (language === 'go' ? `${name} ${edit.type}` : `${name}: ${edit.type}`) : name;
|
|
1028
|
+
const text = def != null ? (language === 'python' && !edit.type ? `${typed}=${def}` : `${typed} = ${def}`) : typed;
|
|
1029
|
+
const multiline = /\n/.test(inner);
|
|
1030
|
+
const kw = star ? partsWithOffsets(ctx.source, sig.open + 1, sig.close).find((p) => /^\s*\*\*/.test(p.text)) : null;
|
|
1031
|
+
if (kw) {
|
|
1032
|
+
// Python with **kwargs: the new input goes just before it, after any *args, so callers are not affected.
|
|
1033
|
+
const at = kw.start + kw.text.match(/^\s*/)[0].length;
|
|
1034
|
+
ctx.replaceText(at, at, `${text},${kw.text.match(/^\s*/)[0] || ' '}`);
|
|
1035
|
+
} else if (multiline) {
|
|
1036
|
+
const lastLine = inner.replace(/\s+$/, '');
|
|
1037
|
+
const trailingComma = /,\s*$/.test(lastLine);
|
|
1038
|
+
const ind = indentOf(inner.split('\n').filter((l) => l.trim()).pop() || '');
|
|
1039
|
+
const insertAt = sig.open + 1 + lastLine.length;
|
|
1040
|
+
ctx.replaceText(insertAt, insertAt, `${trailingComma ? '' : ','}\n${ind}${text}${trailingComma ? ',' : ''}`);
|
|
1041
|
+
} else ctx.replaceText(sig.close, sig.close, `${params.length ? ', ' : ''}${text}`);
|
|
1042
|
+
ctx.expectInputs = { added: name, was: (item.inputs || []).map((p) => p.name) };
|
|
1043
|
+
return `Added the input ${name}${edit.type ? ` (${edit.type})` : ''}${def != null ? `, ${def} when not given` : ''}`;
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
function opRemoveInput(ctx, edit) {
|
|
1047
|
+
const { item, language } = ctx;
|
|
1048
|
+
const name = String(edit.name ?? '');
|
|
1049
|
+
const idx = (item.inputs || []).findIndex((p) => p.name === name);
|
|
1050
|
+
if (idx < 0) refuse(`${item.name} has no input named ${name}.`);
|
|
1051
|
+
if (namesUsed(ctx.shape).has(name)) refuse(`${name} is still used inside ${item.name} (line ${firstUse(ctx.steps, name)}); change those steps first.`);
|
|
1052
|
+
const sig = signatureRange(ctx.source, item, language);
|
|
1053
|
+
if (!sig) needsAi('The writer could not find where this function lists its inputs.');
|
|
1054
|
+
const parts = partsWithOffsets(ctx.source, sig.open + 1, sig.close);
|
|
1055
|
+
const pi = parts.findIndex((p) => new RegExp(`^\\s*(?:\\.\\.\\.|\\*{1,2})?${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(p.text));
|
|
1056
|
+
if (pi < 0) needsAi(`The writer could not find ${name} in the list of inputs.`);
|
|
1057
|
+
if (language === 'go' && !/\s\S/.test(parts[pi].text.trim())) needsAi(`In Go, ${name} shares its type with the next input; the writer does not split them.`);
|
|
1058
|
+
const lead = (p) => p.text.match(/^\s*/)[0];
|
|
1059
|
+
const cur = parts[pi], nextP = parts[pi + 1];
|
|
1060
|
+
let start, end;
|
|
1061
|
+
if (nextP) {
|
|
1062
|
+
if (lead(cur).includes('\n')) { start = cur.start; end = nextP.start; }
|
|
1063
|
+
else { start = cur.start + lead(cur).length; end = nextP.start + (lead(nextP).includes('\n') ? 0 : lead(nextP).length); }
|
|
1064
|
+
} else if (pi > 0) {
|
|
1065
|
+
const trail = cur.text.match(/\s*$/)[0];
|
|
1066
|
+
start = parts[pi - 1].end; end = cur.end - trail.length;
|
|
1067
|
+
} else { start = cur.start; end = cur.end; }
|
|
1068
|
+
ctx.replaceText(start, end, '');
|
|
1069
|
+
ctx.expectInputs = (item.inputs || []).map((p) => p.name).filter((n) => n !== name);
|
|
1070
|
+
return `Removed the input ${name}`;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/** The bracket ( [ or { that `at` is directly inside, looking back (strings on one line are skipped). */
|
|
1074
|
+
function innermostOpen(source, at) {
|
|
1075
|
+
let depth = 0;
|
|
1076
|
+
for (let i = at - 1; i >= 0 && at - i < 20000; i--) {
|
|
1077
|
+
const c = source[i];
|
|
1078
|
+
if (c === '"' || c === "'" || c === '`') { const j = source.lastIndexOf(c, i - 1); if (j >= 0 && !source.slice(j, i).includes('\n')) { i = j; continue; } }
|
|
1079
|
+
if (c === ')' || c === ']' || c === '}') depth++;
|
|
1080
|
+
else if (c === '(' || c === '[' || c === '{') { if (depth === 0) return c; depth--; }
|
|
1081
|
+
}
|
|
1082
|
+
return null;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/** Is offset `at` inside an open ( on its own statement (a call's arguments)? */
|
|
1086
|
+
function insideParens(source, at) {
|
|
1087
|
+
let depth = 0;
|
|
1088
|
+
for (let i = at - 1; i >= 0; i--) {
|
|
1089
|
+
const c = source[i];
|
|
1090
|
+
if (c === ')' || c === ']' || c === '}') depth++;
|
|
1091
|
+
else if (c === '(' || c === '[' || c === '{') { if (depth === 0) return c === '('; depth--; }
|
|
1092
|
+
else if (c === '\n' && depth === 0 && !/[(,\\]\s*$/.test(source.slice(Math.max(0, i - 80), i))) return false;
|
|
1093
|
+
}
|
|
1094
|
+
return false;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
function opRename(ctx, edit) {
|
|
1098
|
+
const { item, language } = ctx;
|
|
1099
|
+
const to = String(edit.to ?? '');
|
|
1100
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(to)) refuse(`"${to}" is not a name.`);
|
|
1101
|
+
const from = edit.from ?? item.name;
|
|
1102
|
+
if (from === to) refuse('The new name is the same as the old one.');
|
|
1103
|
+
if (edit.from == null || from === item.name) {
|
|
1104
|
+
// The function itself: its definition, and every call by name in the files given.
|
|
1105
|
+
if (ctx.allNames().has(to)) refuse(`${to} is already a name in these files; renaming ${from} to it would change what calls mean.`);
|
|
1106
|
+
const sites = [];
|
|
1107
|
+
for (const [path, src] of ctx.state.files) {
|
|
1108
|
+
if (!ctx.state.read(path)) continue;
|
|
1109
|
+
for (const at of identifierSites(src, from, 0, src.length, ctx.state.read(path).language)) sites.push({ path, at });
|
|
1110
|
+
}
|
|
1111
|
+
// Go's doc comment starts with the function's name by convention ("// CanRefund says …"): it follows the name.
|
|
1112
|
+
const docLine = linesOf(ctx.source)[item.line - 2];
|
|
1113
|
+
const doc = language === 'go' && docLine != null ? docLine.match(new RegExp(`^(\\s*//\\s*)${from}\\b`)) : null;
|
|
1114
|
+
if (doc) sites.push({ path: ctx.path, at: lineStarts(ctx.source)[item.line - 2] + doc[1].length, comment: true });
|
|
1115
|
+
ctx.renameEverywhere = { from, to, sites };
|
|
1116
|
+
const uses = sites.filter((s) => !s.comment).length - 1;
|
|
1117
|
+
return `Renamed ${from} to ${to}${uses > 0 ? ` (the function and ${uses} call${uses === 1 ? "" : "s"} or use${uses === 1 ? "" : "s"} of its name)` : ""}${doc ? " and in its doc comment" : ""}`;
|
|
1118
|
+
}
|
|
1119
|
+
const isInput = (item.inputs || []).some((p) => p.name === from);
|
|
1120
|
+
const used = namesUsed(ctx.shape);
|
|
1121
|
+
if (!isInput && !used.has(from)) refuse(`${from} is not an input or a name used in ${item.name}.`);
|
|
1122
|
+
if (used.has(to) || (item.inputs || []).some((p) => p.name === to)) refuse(`${to} is already used in ${item.name}; renaming ${from} to it would change what the steps mean.`);
|
|
1123
|
+
const end = functionEndLine(ctx.source, item, language) ?? (item.anchor?.bodyLines?.[1] ?? item.line);
|
|
1124
|
+
const starts = lineStarts(ctx.source);
|
|
1125
|
+
const a = starts[item.line - 1], b = end < starts.length ? starts[end] - 1 : ctx.source.length;
|
|
1126
|
+
const sites = identifierSites(ctx.source, from, a, b, language);
|
|
1127
|
+
// Keyword arguments (`f(days=1)`) and object keys (`{ days: 1 }`) are names of something else, not this one.
|
|
1128
|
+
const sig = signatureRange(ctx.source, item, language);
|
|
1129
|
+
const keep = sites.filter((s) => {
|
|
1130
|
+
if (sig && s > sig.open && s < sig.close) return true; // the input itself
|
|
1131
|
+
const after = ctx.source.slice(s + from.length, s + from.length + 3);
|
|
1132
|
+
const prev = ctx.source.slice(0, s).replace(/\s+$/, '').slice(-1);
|
|
1133
|
+
// A keyword argument (`f(days=1)`) or an object key (`{ days: 1 }`) names something else, not this one.
|
|
1134
|
+
if (language === 'python' && /^\s*=(?!=)/.test(after) && (prev === '(' || prev === ',') && insideParens(ctx.source, s)) return false;
|
|
1135
|
+
if ((language === 'typescript' || language === 'javascript') && /^\s*:/.test(after) && (prev === '{' || prev === ',')) return false;
|
|
1136
|
+
if (language === 'go' && /^\s*:(?!=)/.test(after) && (prev === '{' || prev === ',')) return false;
|
|
1137
|
+
return true;
|
|
1138
|
+
});
|
|
1139
|
+
const js = language === 'typescript' || language === 'javascript';
|
|
1140
|
+
for (const s of [...keep].reverse()) {
|
|
1141
|
+
// A shorthand property ({ value } or const { value } = …) keeps its key: { value: renamed }.
|
|
1142
|
+
const prev = ctx.source.slice(0, s).replace(/\s+$/, '').slice(-1);
|
|
1143
|
+
const next = ctx.source.slice(s + from.length).replace(/^\s+/, '')[0];
|
|
1144
|
+
const shorthand = js && (prev === '{' || prev === ',') && (next === ',' || next === '}') && innermostOpen(ctx.source, s) === '{';
|
|
1145
|
+
ctx.replaceText(s, s + from.length, shorthand ? `${from}: ${to}` : to);
|
|
1146
|
+
}
|
|
1147
|
+
ctx.shape = renameShape(ctx.shape, from, to);
|
|
1148
|
+
if (isInput) ctx.expectInputs = (item.inputs || []).map((p) => (p.name === from ? to : p.name));
|
|
1149
|
+
return `Renamed ${from} to ${to} in ${item.name} (${keep.length} place${keep.length === 1 ? '' : 's'})`;
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
function opAddFunction(state, edit) {
|
|
1153
|
+
const path = edit.file ?? [...state.files.keys()][0];
|
|
1154
|
+
if (!state.files.has(path)) refuse(`There is no file ${path} in this change.`);
|
|
1155
|
+
const rd = state.read(path);
|
|
1156
|
+
if (!rd) needsAi(`${path} is not a file Thunder reads.`);
|
|
1157
|
+
const { language } = rd;
|
|
1158
|
+
const source = state.files.get(path);
|
|
1159
|
+
if (!WRITE_STEPS_LANGUAGES.includes(language)) needsAi(`New functions are written for TypeScript, JavaScript, Python, and Go; ${path} is ${langName(language)}.`);
|
|
1160
|
+
const name = String(edit.name ?? '');
|
|
1161
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name)) refuse(`"${name}" is not a name a function can have.`);
|
|
1162
|
+
if (membersOf(rd.reading).some((m) => m.name === name)) refuse(`${path} already has a function named ${name}.`);
|
|
1163
|
+
const inputs = (edit.inputs || []).map((p) => (typeof p === 'string' ? { name: p } : p));
|
|
1164
|
+
if (language === 'go' && inputs.some((p) => !p.type)) refuse('Go needs a type for every input.');
|
|
1165
|
+
const ctx = { language, source, item: { name, line: 1 } };
|
|
1166
|
+
if (language === 'go' && edit.returns) ctx.goResults = edit.returns;
|
|
1167
|
+
const nodes = (edit.steps || []).map((s) => stepSpec(s, { ...ctx, source: `${source}\nfunc ${name}() (${edit.returns || ''}) {}` }));
|
|
1168
|
+
if (!nodes.length) refuse('A new function needs at least one step.');
|
|
1169
|
+
const unit = indentUnit(source, language);
|
|
1170
|
+
const params = inputs.map((p) => (p.type ? (language === 'go' ? `${p.name} ${p.type}` : language === 'python' ? `${p.name}: ${p.type}` : `${p.name}: ${p.type}`) : p.name)).join(', ');
|
|
1171
|
+
const exp = edit.export && (language === 'typescript' || language === 'javascript') ? 'export ' : '';
|
|
1172
|
+
const head = language === 'python' ? `def ${name}(${params})${edit.returns ? ` -> ${edit.returns}` : ''}:` : language === 'go' ? `func ${name}(${params})${edit.returns ? ` ${/,/.test(edit.returns) && !/^\(/.test(edit.returns) ? `(${edit.returns})` : edit.returns}` : ''} {` : `${exp}function ${name}(${params})${edit.returns && language === 'typescript' ? `: ${edit.returns}` : ''} {`;
|
|
1173
|
+
const body = renderBlock(nodes, language, unit, unit);
|
|
1174
|
+
const fnLines = [head, ...body, ...(language === 'python' ? [] : ['}'])];
|
|
1175
|
+
// After a given function, or at the end of the file.
|
|
1176
|
+
let at;
|
|
1177
|
+
if (edit.after != null) {
|
|
1178
|
+
const ref = parseMemberRef(edit.after);
|
|
1179
|
+
const m = memberKeys(rd.reading).find((x) => x.item.name === ref.name);
|
|
1180
|
+
if (!m) refuse(`There is no function ${ref.name} in ${path} to put it after.`);
|
|
1181
|
+
at = functionEndLine(source, m.item, language);
|
|
1182
|
+
if (at == null) needsAi(`The writer could not find where ${ref.name} ends.`);
|
|
1183
|
+
} else at = linesOf(source.replace(/\n+$/, '')).length;
|
|
1184
|
+
const L = linesOf(source);
|
|
1185
|
+
const blank = language === 'python' ? ['', ''] : [''];
|
|
1186
|
+
L.splice(at, 0, ...blank, ...fnLines);
|
|
1187
|
+
const next = L.join('\n');
|
|
1188
|
+
return { path, source: next, name, nodes, inputs: inputs.map((p) => p.name), says: `Added ${name}(${inputs.map((p) => p.name).join(', ')}) with ${nodes.length} step${nodes.length === 1 ? '' : 's'}` };
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
const OPS = { setValue: opSetValue, setCondition: opSetCondition, setGivesBack: opSetGivesBack, addStep: opAddStep, removeStep: opRemoveStep, moveStep: opMoveStep, addStop: opAddStop, removeStop: opRemoveStop, addInput: opAddInput, removeInput: opRemoveInput, rename: opRename };
|
|
1192
|
+
|
|
1193
|
+
// ── Applying one edit ──────────────────────────────────────────────────────────────────────────────────────
|
|
1194
|
+
|
|
1195
|
+
/** Apply one edit to the files in `state`; returns { files, plan, says } or throws Refused / NeedsAI. */
|
|
1196
|
+
function applyEdit(state, edit) {
|
|
1197
|
+
if (!edit || typeof edit !== 'object') refuse('An edit is an object such as { op: "setValue", member, step, to }.');
|
|
1198
|
+
if (!EDIT_OPS.includes(edit.op)) refuse(`"${edit.op}" is not a Thunder edit. The edits are: ${EDIT_OPS.join(', ')}.`);
|
|
1199
|
+
if (edit.op === 'addFunction') {
|
|
1200
|
+
const r = opAddFunction(state, edit);
|
|
1201
|
+
return { files: new Map([...state.files, [r.path, r.source]]), plan: { added: { path: r.path, name: r.name, shape: r.nodes, inputs: r.inputs } }, says: r.says };
|
|
1202
|
+
}
|
|
1203
|
+
const m = findMember(state, edit.member);
|
|
1204
|
+
if (!m.item.steps) needsAi(`Thunder has no steps for ${m.item.name} (line ${m.item.line}), so the edit cannot be placed exactly.`);
|
|
1205
|
+
let source = m.source;
|
|
1206
|
+
const ctx = {
|
|
1207
|
+
state, language: m.language, item: m.item, steps: m.item.steps, path: m.path,
|
|
1208
|
+
get source() { return source; },
|
|
1209
|
+
shape: stepShape(m.item.steps),
|
|
1210
|
+
at(sel) {
|
|
1211
|
+
if (sel == null) refuse('Say which step (its id, its line as "line:N", or its path such as "2" or "1.0").');
|
|
1212
|
+
const loc = locateStep(m.item.steps, sel, { flowSteps: m.item.steps });
|
|
1213
|
+
if (!loc) refuse(`${m.item.name} has no step ${JSON.stringify(sel)}.`);
|
|
1214
|
+
return loc;
|
|
1215
|
+
},
|
|
1216
|
+
// Steps edited by tree are written after every other kind of change is planned (their lines do not move).
|
|
1217
|
+
treeEdits: [],
|
|
1218
|
+
setTree(step, tree) { this.treeEdits.push({ step, tree }); pathIn(this.shape, stepPathOf(m.item.steps, step)).node.e = tree; },
|
|
1219
|
+
lines(start, del, insert) { source = spliceLines(source, start, del, insert); this.moved = true; },
|
|
1220
|
+
replaceText(a, b, text) { source = source.slice(0, a) + text + source.slice(b); this.moved = true; },
|
|
1221
|
+
originalShape() {
|
|
1222
|
+
if (state.original === state.files) return stepShape(m.item.steps);
|
|
1223
|
+
const o = makeState(state.original);
|
|
1224
|
+
const r = o.read(m.path);
|
|
1225
|
+
const it = r && memberKeys(r.reading).find((x) => x.key === m.key);
|
|
1226
|
+
return it ? stepShape(it.item.steps) : [];
|
|
1227
|
+
},
|
|
1228
|
+
allNames() { const s = new Set(); for (const [p] of state.files) { const r = state.read(p); if (r) for (const it of membersOf(r.reading)) s.add(it.name); } return s; },
|
|
1229
|
+
};
|
|
1230
|
+
const says = OPS[edit.op](ctx, edit); // validates the edit against the meaning tree (Refused when it does not fit)
|
|
1231
|
+
// Other languages: the edit was checked against the model above; the code is handed to an AI coding agent.
|
|
1232
|
+
if (!WRITE_STEPS_LANGUAGES.includes(m.language)) needsAi(`The deterministic writers cover TypeScript, JavaScript, Python, and Go; ${m.path} is ${langName(m.language)}.`);
|
|
1233
|
+
for (const t of ctx.treeEdits) source = writeStepTree(source, t.step, t.tree, m.language);
|
|
1234
|
+
if (ctx.goImport) source = addGoImport(source, ctx.goImport);
|
|
1235
|
+
const files = new Map(state.files);
|
|
1236
|
+
files.set(m.path, source);
|
|
1237
|
+
if (ctx.renameEverywhere) {
|
|
1238
|
+
const { from, to, sites } = ctx.renameEverywhere;
|
|
1239
|
+
for (const [path] of state.files) {
|
|
1240
|
+
const mine = sites.filter((s) => s.path === path).sort((a, b) => b.at - a.at);
|
|
1241
|
+
let src = state.files.get(path);
|
|
1242
|
+
for (const s of mine) src = src.slice(0, s.at) + to + src.slice(s.at + from.length);
|
|
1243
|
+
files.set(path, src);
|
|
1244
|
+
}
|
|
1245
|
+
return { files, plan: { renameFunction: { from, to }, member: { path: m.path, key: m.key, name: to, shape: renameShape(ctx.shape, from, to) } }, says };
|
|
1246
|
+
}
|
|
1247
|
+
return {
|
|
1248
|
+
files,
|
|
1249
|
+
plan: { member: { path: m.path, key: m.key, name: m.item.name, shape: ctx.shape, inputs: ctx.expectInputs ?? null, returns: ctx.expectReturns ?? null } },
|
|
1250
|
+
says: reworded(says, ctx.treeEdits, { path: m.path, source, language: m.language }),
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
/** "…; it now reads "If days_since is more than 10"": the edited steps' new Thunder words, read from the new code. */
|
|
1254
|
+
function reworded(says, treeEdits, f) {
|
|
1255
|
+
if (!treeEdits.length) return says;
|
|
1256
|
+
let reading;
|
|
1257
|
+
try { reading = readFile(f).reading; } catch { return says; }
|
|
1258
|
+
const now = [];
|
|
1259
|
+
const walk = (list) => (list || []).forEach((s) => { for (const t of treeEdits) if (s.line === t.step.line && s.says && s.says !== t.step.says) now.push(s.says); walk(s.children); walk(s.otherwise); });
|
|
1260
|
+
for (const it of membersOf(reading)) walk(it.steps);
|
|
1261
|
+
return now.length ? `${says}; it now reads ${now.map((x) => `"${x}"`).join(', ')}` : says;
|
|
1262
|
+
}
|
|
1263
|
+
function stepPathOf(steps, step) {
|
|
1264
|
+
let found = null;
|
|
1265
|
+
const walk = (list, path) => list.forEach((s, i) => { if (found) return; if (s === step) { found = [...path, i]; return; } if (s.children) walk(s.children, [...path, i]); if (s.otherwise) walk(s.otherwise, [...path, i, 'else']); });
|
|
1266
|
+
walk(steps, []);
|
|
1267
|
+
return found;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
// ── Proof ──────────────────────────────────────────────────────────────────────────────────────────────────
|
|
1271
|
+
|
|
1272
|
+
function firstShapeDifference(a, b, path = []) {
|
|
1273
|
+
const n = Math.max(a.length, b.length);
|
|
1274
|
+
for (let i = 0; i < n; i++) {
|
|
1275
|
+
const x = a[i], y = b[i];
|
|
1276
|
+
const here = [...path, i + 1].join('.');
|
|
1277
|
+
if (!x) return `step ${here} is extra: ${sayFull(y.e)}`;
|
|
1278
|
+
if (!y) return `step ${here} is missing: ${sayFull(x.e)}`;
|
|
1279
|
+
if (!sameExpr(x.e, y.e)) return `step ${here} reads "${sayFull(y.e)}", not "${sayFull(x.e)}"`;
|
|
1280
|
+
for (const k of ['c', 'o', 'a']) {
|
|
1281
|
+
const d = firstShapeDifference(x[k] || [], y[k] || [], [...path, i + 1]);
|
|
1282
|
+
if (d) return d;
|
|
1283
|
+
}
|
|
1284
|
+
if (JSON.stringify(normalizeExpr(x.h || [])) !== JSON.stringify(normalizeExpr(y.h || []))) return `step ${here}: what happens when something goes wrong differs`;
|
|
1285
|
+
}
|
|
1286
|
+
return null;
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
/** The last line of a function: its last step, or its body's last line. */
|
|
1290
|
+
function memberEnd(item) {
|
|
1291
|
+
let end = Math.max(item.line, item.anchor?.bodyLines?.[1] ?? 0);
|
|
1292
|
+
const walk = (list) => (list || []).forEach((s) => { end = Math.max(end, s.span?.endLine ?? s.line ?? 0); walk(s.children); walk(s.otherwise); (s.handlers || []).forEach((h) => walk(h.steps)); walk(s.always?.steps); });
|
|
1293
|
+
walk(item.steps);
|
|
1294
|
+
return end;
|
|
1295
|
+
}
|
|
1296
|
+
/** Steps with the one that holds `line` (and everything in it) replaced by a placeholder. */
|
|
1297
|
+
function maskSteps(steps, line) {
|
|
1298
|
+
return (steps || []).map((s) => {
|
|
1299
|
+
const a = s.span?.startLine ?? s.line, b = s.span?.endLine ?? s.line;
|
|
1300
|
+
if (a <= line && line <= b && !(s.children || []).concat(s.otherwise || []).some((c) => (c.span?.startLine ?? c.line) <= line && line <= (c.span?.endLine ?? c.line))) return { kind: 'code', code: '(the step the edited function is written in)', expr: { kind: 'code', text: '(the step the edited function is written in)' } };
|
|
1301
|
+
return { ...s, children: s.children ? maskSteps(s.children, line) : s.children, otherwise: s.otherwise ? maskSteps(s.otherwise, line) : s.otherwise };
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
const hasInner = (shape, names) => (shape || []).some((s) => (s.e?.kind === 'function' && names.has(s.e.name)) || hasInner(s.c, names) || hasInner(s.o, names) || hasInner(s.a, names) || (s.h || []).some((h) => hasInner(h.c, names)));
|
|
1305
|
+
const maskInner = (shape, names) => (shape || []).map((s) => (s.e?.kind === 'function' && names.has(s.e.name) ? { e: { kind: 'code', text: `(the edited function ${s.e.name})` }, c: [] } : { ...s, c: maskInner(s.c, names), ...(s.o ? { o: maskInner(s.o, names) } : {}), ...(s.a ? { a: maskInner(s.a, names) } : {}), ...(s.h ? { h: s.h.map((h) => ({ ...h, c: maskInner(h.c, names) })) } : {}) }));
|
|
1306
|
+
|
|
1307
|
+
/**
|
|
1308
|
+
* Prove a change: `before` and `after` are Maps path -> source; `plans` say what each edit intended. Returns
|
|
1309
|
+
* { ok, edited: { status, checks[] }, unchanged: { status, checked, items[] }, problems[] }.
|
|
1310
|
+
*/
|
|
1311
|
+
export function proveChange(before, after, plans) {
|
|
1312
|
+
const problems = [];
|
|
1313
|
+
const edited = { status: 'proven', checks: [] };
|
|
1314
|
+
const readOf = (files, path) => { const src = files.get(path); try { return readFile({ path, source: src }); } catch (e) { return { error: e.message }; } };
|
|
1315
|
+
const editedKeys = new Set(); // path|key in the after files
|
|
1316
|
+
const ranges = new Map(); // path -> [{ before: [first, last], after: [first, last] }] of the edited functions
|
|
1317
|
+
const renamed = plans.find((p) => p.renameFunction)?.renameFunction;
|
|
1318
|
+
for (const p of plans) {
|
|
1319
|
+
if (p.added) {
|
|
1320
|
+
const r = readOf(after, p.added.path);
|
|
1321
|
+
if (r.error) { problems.push(`${p.added.path} could not be read after the change: ${r.error}`); continue; }
|
|
1322
|
+
const it = memberKeys(r.reading).find((x) => x.item.name === p.added.name);
|
|
1323
|
+
editedKeys.add(`${p.added.path}|${it?.key}`);
|
|
1324
|
+
if (!it) { problems.push(`The new function ${p.added.name} is not read from the changed file.`); continue; }
|
|
1325
|
+
const d = firstShapeDifference(p.added.shape, stepShape(it.item.steps));
|
|
1326
|
+
if (d) problems.push(`${p.added.name}: ${d}.`);
|
|
1327
|
+
if (JSON.stringify(it.item.inputs.map((x) => x.name)) !== JSON.stringify(p.added.inputs)) problems.push(`${p.added.name} takes ${it.item.inputs.map((x) => x.name).join(', ') || 'nothing'}, not ${p.added.inputs.join(', ') || 'nothing'}.`);
|
|
1328
|
+
edited.checks.push({ member: p.added.name, file: p.added.path, result: d ? 'different' : 'exact', steps: p.added.shape.length });
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
const mm = p.member;
|
|
1332
|
+
const r = readOf(after, mm.path);
|
|
1333
|
+
if (r.error) { problems.push(`${mm.path} could not be read after the change: ${r.error}`); continue; }
|
|
1334
|
+
const key = renamed ? mm.key.replace(/^[^#]+/, mm.name) : mm.key;
|
|
1335
|
+
const it = memberKeys(r.reading).find((x) => x.key === key);
|
|
1336
|
+
editedKeys.add(`${mm.path}|${key}`);
|
|
1337
|
+
if (!it) { problems.push(`${mm.name} is no longer read from ${mm.path} after the change.`); edited.checks.push({ member: mm.name, file: mm.path, result: 'missing' }); continue; }
|
|
1338
|
+
const d = firstShapeDifference(mm.shape, stepShape(it.item.steps));
|
|
1339
|
+
if (d) problems.push(`${mm.name}: ${d}.`);
|
|
1340
|
+
const gotInputs = it.item.inputs.map((x) => x.name);
|
|
1341
|
+
const inputsOk = !mm.inputs || (Array.isArray(mm.inputs) ? JSON.stringify(gotInputs) === JSON.stringify(mm.inputs) : gotInputs.includes(mm.inputs.added) && JSON.stringify(gotInputs.filter((x) => x !== mm.inputs.added)) === JSON.stringify(mm.inputs.was));
|
|
1342
|
+
if (!inputsOk) problems.push(`${mm.name} takes ${it.item.inputs.map((x) => x.name).join(', ')} after the change, not ${Array.isArray(mm.inputs) ? mm.inputs.join(', ') : [...mm.inputs.was, mm.inputs.added].join(', ')}.`);
|
|
1343
|
+
if (mm.returns && String(it.item.returns ?? '').replace(/\s+/g, '') !== String(mm.returns).replace(/\s+/g, '') && !String(it.item.returns ?? '').includes(String(mm.returns).replace(/^\(|\)$/g, ''))) problems.push(`${mm.name} gives back ${it.item.returns ?? 'nothing declared'} after the change, not ${mm.returns}.`);
|
|
1344
|
+
edited.checks.push({ member: mm.name, file: mm.path, result: d ? 'different' : 'exact', steps: mm.shape.length });
|
|
1345
|
+
const rb = readOf(before, mm.path);
|
|
1346
|
+
const old = !rb.error && memberKeys(rb.reading).find((x) => x.key === mm.key);
|
|
1347
|
+
if (old) { if (!ranges.has(mm.path)) ranges.set(mm.path, []); ranges.get(mm.path).push({ before: [old.item.line, memberEnd(old.item)], after: [it.item.line, memberEnd(it.item)] }); }
|
|
1348
|
+
}
|
|
1349
|
+
if (problems.length) edited.status = 'failed';
|
|
1350
|
+
|
|
1351
|
+
// Everything else: the same meaning, function by function.
|
|
1352
|
+
const items = [];
|
|
1353
|
+
const editedInner = new Map();
|
|
1354
|
+
const insideEdited = new Map();
|
|
1355
|
+
const innerDefs = (shape, out) => { for (const s of shape || []) { if (s.e?.kind === 'function' && !out.has(s.e.name)) out.set(s.e.name, s.c); innerDefs(s.c, out); innerDefs(s.o, out); innerDefs(s.a, out); (s.h || []).forEach((h) => innerDefs(h.c, out)); } return out; };
|
|
1356
|
+
for (const p of plans) if (p.member) { if (!insideEdited.has(p.member.path)) insideEdited.set(p.member.path, new Map()); innerDefs(p.member.shape, insideEdited.get(p.member.path)); }
|
|
1357
|
+
for (const k of editedKeys) { const [path, key] = k.split('|'); if (!key || key === 'undefined') continue; if (!editedInner.has(path)) editedInner.set(path, new Set()); editedInner.get(path).add(key.split('#')[0]); }
|
|
1358
|
+
for (const p of plans) if (p.member && editedInner.has(p.member.path)) { editedInner.get(p.member.path).add(p.member.key.split('#')[0]); if (renamed) editedInner.get(p.member.path).add(renamed.from); }
|
|
1359
|
+
const touched = [...after.keys()].filter((p) => after.get(p) !== before.get(p));
|
|
1360
|
+
for (const path of touched) {
|
|
1361
|
+
const a = readOf(before, path), b = readOf(after, path);
|
|
1362
|
+
if (a.error || b.error) { problems.push(`${path} could not be read ${a.error ? 'before' : 'after'} the change.`); continue; }
|
|
1363
|
+
const olds = memberKeys(a.reading), news = memberKeys(b.reading);
|
|
1364
|
+
const newByKey = new Map(news.map((x) => [x.key, x]));
|
|
1365
|
+
for (const o of olds) {
|
|
1366
|
+
const k = renamed && o.item.name === renamed.from ? o.key.replace(/^[^#]+/, renamed.to) : o.key;
|
|
1367
|
+
if (editedKeys.has(`${path}|${k}`)) continue;
|
|
1368
|
+
const n = newByKey.get(k);
|
|
1369
|
+
if (!n) {
|
|
1370
|
+
const gone = (ranges.get(path) || []).find((r) => r.before[0] <= o.item.line && memberEnd(o.item) <= r.before[1]);
|
|
1371
|
+
items.push(gone ? { name: o.item.name, file: path, line: o.item.line, status: 'same', within: true, note: 'Was written inside the edited function; checked as part of its steps.' } : { name: o.item.name, file: path, status: 'missing', reason: 'Not found after the change.' });
|
|
1372
|
+
continue;
|
|
1373
|
+
}
|
|
1374
|
+
const oEnd = memberEnd(o.item);
|
|
1375
|
+
const R = ranges.get(path) || [];
|
|
1376
|
+
// A function written inside the edited one (a nested def, a callback, a method in an object) is part of the
|
|
1377
|
+
// edited function's steps, which were checked exactly above.
|
|
1378
|
+
const inside = R.find((r) => r.before[0] <= o.item.line && oEnd <= r.before[1] && !(r.before[0] === o.item.line && r.before[1] === oEnd));
|
|
1379
|
+
if (inside && !insideEdited.get(path)?.get(o.item.name)) { items.push({ name: o.item.name, file: path, line: o.item.line, status: 'same', within: true, note: 'Written inside the edited function; checked as part of its steps.' }); continue; }
|
|
1380
|
+
let expectShape = renamed ? renameShape(stepShape(o.item.steps), renamed.from, renamed.to) : stepShape(o.item.steps);
|
|
1381
|
+
let actual = stepShape(n.item.steps);
|
|
1382
|
+
// A function that holds the edited one is compared step by step, without the step the edited function is in.
|
|
1383
|
+
const around = R.find((r) => o.item.line < r.before[0] && r.before[1] <= oEnd);
|
|
1384
|
+
if (around) { expectShape = stepShape(maskSteps(o.item.steps, around.before[0])); actual = stepShape(maskSteps(n.item.steps, around.after[0])); if (renamed) expectShape = renameShape(expectShape, renamed.from, renamed.to); }
|
|
1385
|
+
// A function inside the edited one changes with it: its expected steps are the edited function's inner steps.
|
|
1386
|
+
const within = insideEdited.get(path)?.get(o.item.name);
|
|
1387
|
+
if (within) expectShape = within;
|
|
1388
|
+
// A function that holds an edited inner function is compared without it (the inner one is checked above).
|
|
1389
|
+
const inner = editedInner.get(path);
|
|
1390
|
+
const holds = !!around || (inner && (hasInner(expectShape, inner) || hasInner(actual, inner)));
|
|
1391
|
+
if (holds) { expectShape = maskInner(expectShape, inner); actual = maskInner(actual, inner); }
|
|
1392
|
+
const d = firstShapeDifference(expectShape, actual);
|
|
1393
|
+
const inputsSame = inputsKey(o.item) === inputsKey(n.item);
|
|
1394
|
+
items.push({ name: o.item.name, file: path, line: o.item.line, status: d || !inputsSame ? 'different' : 'same', ...(within ? { within: true, note: 'Inside the edited function; compared with its intended steps.' } : {}), ...(holds ? { holds: true, note: 'Holds the edited function; every other step was compared.' } : {}), ...(d ? { reason: d } : !inputsSame ? { reason: 'its inputs changed' } : {}) });
|
|
1395
|
+
}
|
|
1396
|
+
const oldKeys = new Set(olds.map((o) => (renamed && o.item.name === renamed.from ? o.key.replace(/^[^#]+/, renamed.to) : o.key)));
|
|
1397
|
+
const inEdited = (n) => (ranges.get(path) || []).some((r) => r.after[0] <= n.item.line && memberEnd(n.item) <= r.after[1]);
|
|
1398
|
+
for (const n of news) if (!oldKeys.has(n.key) && !editedKeys.has(`${path}|${n.key}`) && !inEdited(n)) items.push({ name: n.item.name, file: path, status: 'new', reason: 'A function that was not asked for.' });
|
|
1399
|
+
}
|
|
1400
|
+
// thunder same, on every touched file without the edited functions: it must say 'same' for each of the rest.
|
|
1401
|
+
// (A renamed function is compared by its trees above; `same` pairs functions by name.)
|
|
1402
|
+
if (!renamed) {
|
|
1403
|
+
const strip = (files, side) => touched.map((path) => ({ path, source: files.get(path) })).filter((f) => readableLanguage(f.path));
|
|
1404
|
+
const sm = sameMeaning(strip(before, 'old'), strip(after, 'new'));
|
|
1405
|
+
const editedNames = new Set([...editedKeys].map((k) => nameKey(k.split('|')[1].split('#')[0])));
|
|
1406
|
+
for (const it of sm.items) {
|
|
1407
|
+
if (editedNames.has(nameKey(it.name))) continue;
|
|
1408
|
+
const mine = items.find((x) => nameKey(x.name) === nameKey(it.name) && (it.old?.line == null || x.line === it.old.line)) ?? items.find((x) => nameKey(x.name) === nameKey(it.name));
|
|
1409
|
+
if (mine?.holds || mine?.within) continue; // `same` compares it whole, with the edited function in or around it
|
|
1410
|
+
if (it.status !== 'same') {
|
|
1411
|
+
// `same` may decline to call two readings the same (cannot-check) where the trees prove them identical:
|
|
1412
|
+
// identical trees are the stronger check, and are never weakened by it. Anything 'different' fails.
|
|
1413
|
+
if (it.status === 'cannot-check' && mine?.status === 'same') { mine.same = 'cannot-check'; continue; }
|
|
1414
|
+
if (mine) { mine.status = 'different'; mine.reason = it.reason; } else items.push({ name: it.name, file: it.new?.file ?? it.old?.file, status: 'different', reason: it.reason });
|
|
1415
|
+
} else if (mine) mine.same = 'same';
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
const bad = items.filter((x) => x.status !== 'same');
|
|
1419
|
+
for (const b of bad) problems.push(`${b.name} (${b.file}) ${b.status === 'missing' ? 'is missing after the change' : b.status === 'new' ? 'appeared, though it was not asked for' : `reads differently after the change: ${b.reason}`}.`);
|
|
1420
|
+
const unchanged = { status: bad.length ? 'failed' : 'same', checked: items.length, items };
|
|
1421
|
+
return { ok: !problems.length, edited, unchanged, problems };
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
// ── The prompt for an AI coding agent ──────────────────────────────────────────────────────────────────────
|
|
1425
|
+
|
|
1426
|
+
function numbered(source, a, b) {
|
|
1427
|
+
const L = linesOf(source);
|
|
1428
|
+
const w = String(b).length;
|
|
1429
|
+
return L.slice(a - 1, b).map((l, i) => `${String(a + i).padStart(w)} | ${l}`).join('\n');
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
function aiPrompt(files, edits, why) {
|
|
1433
|
+
const parts = [];
|
|
1434
|
+
parts.push('You are changing code so that it does exactly what a Thunder edit says, and nothing else.');
|
|
1435
|
+
parts.push('');
|
|
1436
|
+
const shown = new Set();
|
|
1437
|
+
for (const e of edits) {
|
|
1438
|
+
let where = null;
|
|
1439
|
+
try {
|
|
1440
|
+
if (e.op !== 'addFunction') {
|
|
1441
|
+
const state = makeState(files);
|
|
1442
|
+
const m = findMember(state, e.member);
|
|
1443
|
+
const end = functionEndLine(m.source, m.item, m.language) ?? (m.item.anchor?.bodyLines?.[1] ?? m.item.line);
|
|
1444
|
+
where = { path: m.path, language: m.language, name: m.item.name, a: m.item.line, b: end, source: m.source };
|
|
1445
|
+
} else where = { path: e.file ?? [...files.keys()][0], language: readableLanguage(e.file ?? [...files.keys()][0]), name: e.name };
|
|
1446
|
+
} catch { /* described from the edit alone */ }
|
|
1447
|
+
if (where?.a && !shown.has(`${where.path}:${where.name}`)) {
|
|
1448
|
+
shown.add(`${where.path}:${where.name}`);
|
|
1449
|
+
parts.push(`File: ${where.path} (${langName(where.language)}). Function ${where.name}, lines ${where.a}–${where.b}:`);
|
|
1450
|
+
parts.push('```');
|
|
1451
|
+
parts.push(numbered(where.source, where.a, where.b));
|
|
1452
|
+
parts.push('```');
|
|
1453
|
+
parts.push('');
|
|
1454
|
+
} else if (where && !where.a) parts.push(`File: ${where.path} (${langName(where.language)}).`);
|
|
1455
|
+
}
|
|
1456
|
+
parts.push('The change, as Thunder edits (JSON):');
|
|
1457
|
+
parts.push('```json');
|
|
1458
|
+
parts.push(JSON.stringify(edits, null, 2));
|
|
1459
|
+
parts.push('```');
|
|
1460
|
+
parts.push('');
|
|
1461
|
+
parts.push('What each edit means:');
|
|
1462
|
+
for (const e of edits) parts.push(`- ${describeEdit(e)}`);
|
|
1463
|
+
parts.push('');
|
|
1464
|
+
parts.push('Rules:');
|
|
1465
|
+
parts.push('1. Change only the lines this change needs. Keep every other line exactly as it is: comments, blank lines, formatting, indentation, quotes, and names.');
|
|
1466
|
+
parts.push('2. Do not change any other function, and no other file, unless the change cannot be made without it; if so, say which and why.');
|
|
1467
|
+
parts.push('3. Write it the way this file already writes code (its error types, quote style, naming).');
|
|
1468
|
+
parts.push('4. Return the whole updated file.');
|
|
1469
|
+
parts.push('');
|
|
1470
|
+
parts.push(`Why the Thunder compiler did not write this itself: ${why}`);
|
|
1471
|
+
parts.push('');
|
|
1472
|
+
parts.push('How the result is checked: Thunder reads the changed file again. The edited steps must read exactly as the edit says, and every other function must mean the same as before (thunder same). The result is labeled "AI-written" until a person accepts it.');
|
|
1473
|
+
return parts.join('\n');
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
/** One edit in plain words, without the code. */
|
|
1477
|
+
export function describeEdit(e) {
|
|
1478
|
+
const at = (s) => (s == null ? '' : ` (step ${Array.isArray(s) ? s.join('.') : s})`);
|
|
1479
|
+
const who = e.member ? ` in ${parseMemberRef(e.member).name}` : '';
|
|
1480
|
+
switch (e.op) {
|
|
1481
|
+
case 'setValue': return `Change the value ${e.from !== undefined ? JSON.stringify(e.from) : ''} to ${JSON.stringify(e.to)}${at(e.step)}${who}.`.replace('value to', 'value to');
|
|
1482
|
+
case 'setCondition': return `Change the question${at(e.step)}${who}: ${[e.when != null && `ask "${e.when}"`, e.compare != null && `compare with ${e.compare}`, e.operand && `make the ${e.operand.side || 'right'} side ${JSON.stringify(e.operand.to)}`, e.negate && 'turn it around (not)', e.addClause && `add "${e.addClause.join || 'and'} ${e.addClause.when}"`, e.removeClause != null && `remove part ${e.removeClause}`].filter(Boolean).join(', ')}.`;
|
|
1483
|
+
case 'addStep': return `Add the step ${JSON.stringify(e.step ?? e.steps)} ${e.before != null ? `before step ${e.before}` : e.after != null ? `after step ${e.after}` : `on the ${e.into?.side || 'yes'} side of step ${e.into?.step ?? e.into}`}${who}.`;
|
|
1484
|
+
case 'removeStep': return `Remove step ${e.step}${who} and everything inside it.`;
|
|
1485
|
+
case 'moveStep': return `Move step ${e.step} ${e.before != null ? `before step ${e.before}` : `after step ${e.after}`}${who}.`;
|
|
1486
|
+
case 'addStop': return e.when != null ? `Add a Stop${who}: if ${e.when}, stop with ${e.error ? `${e.error}: ` : ''}"${e.message}" (${e.before != null ? `before step ${e.before}` : `after step ${e.after}`}).` : `Add a Stop on the ${e.side || 'yes'} side of the question at step ${e.step}${who}: ${e.error ? `${e.error}: ` : ''}"${e.message}".`;
|
|
1487
|
+
case 'removeStop': return `Remove the Stop at step ${e.step}${who} (and its question when that is all the question does).`;
|
|
1488
|
+
case 'addInput': return `Add the input ${e.name}${e.type ? ` of type ${e.type}` : ''}${e.default !== undefined ? ` with default ${JSON.stringify(e.default)}` : ''}${who}.`;
|
|
1489
|
+
case 'removeInput': return `Remove the input ${e.name}${who}.`;
|
|
1490
|
+
case 'setGivesBack': return e.type != null ? `Declare that${who.replace(' in', '')} gives back ${e.type}.` : `Give back ${JSON.stringify(e.value)}${at(e.step)}${who}.`;
|
|
1491
|
+
case 'rename': return `Rename ${e.from ?? parseMemberRef(e.member).name} to ${e.to}${e.from ? who : ' (the function, and every call to it)'}; the meaning must not change.`;
|
|
1492
|
+
case 'addFunction': return `Add a function ${e.name}(${(e.inputs || []).map((p) => (typeof p === 'string' ? p : p.name)).join(', ')}) in ${e.file ?? 'the file'} with the steps ${JSON.stringify(e.steps)}.`;
|
|
1493
|
+
default: return JSON.stringify(e);
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
// ── Thunder text, before and after ─────────────────────────────────────────────────────────────────────────
|
|
1498
|
+
|
|
1499
|
+
function thunderLines(steps, depth = 1) {
|
|
1500
|
+
const out = [];
|
|
1501
|
+
for (const s of steps || []) {
|
|
1502
|
+
out.push(`${' '.repeat(depth)}- ${s.restates || s.kind === 'other' ? `\`${s.code}\`` : s.says}`);
|
|
1503
|
+
if (s.children?.length) { if (s.kind === 'branch') out.push(`${' '.repeat(depth + 1)}Yes:`); out.push(...thunderLines(s.children, depth + (s.kind === 'branch' ? 2 : 1))); }
|
|
1504
|
+
if (s.otherwise) { out.push(`${' '.repeat(depth + 1)}No:`); out.push(...(s.otherwise.length ? thunderLines(s.otherwise, depth + 2) : [`${' '.repeat(depth + 2)}- (nothing)`])); }
|
|
1505
|
+
}
|
|
1506
|
+
return out;
|
|
1507
|
+
}
|
|
1508
|
+
function thunderOf(files, ref) {
|
|
1509
|
+
try {
|
|
1510
|
+
const state = makeState(files);
|
|
1511
|
+
const m = findMember(state, ref);
|
|
1512
|
+
const head = `${m.item.label ?? m.item.name}${m.item.inputs?.length ? ` — you give it: ${m.item.inputs.map((p) => p.name).join(', ')}` : ''}`;
|
|
1513
|
+
return [head, ...thunderLines(m.item.steps)].join('\n');
|
|
1514
|
+
} catch { return null; }
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// ── The API ────────────────────────────────────────────────────────────────────────────────────────────────
|
|
1518
|
+
|
|
1519
|
+
function makeState(files, original = null) {
|
|
1520
|
+
const cache = new Map();
|
|
1521
|
+
return {
|
|
1522
|
+
files, original: original ?? files,
|
|
1523
|
+
read(path) {
|
|
1524
|
+
const src = files.get(path);
|
|
1525
|
+
const k = `${path}\u0000${src}`;
|
|
1526
|
+
if (!cache.has(k)) { try { cache.set(k, readableLanguage(path) ? readFile({ path, source: src }) : null); } catch { cache.set(k, null); } }
|
|
1527
|
+
return cache.get(k);
|
|
1528
|
+
},
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
const toMap = (files) => (files instanceof Map ? new Map(files) : new Map((Array.isArray(files) ? files : Object.entries(files).map(([path, source]) => ({ path, source }))).map((f) => [f.path, f.source])));
|
|
1532
|
+
|
|
1533
|
+
/**
|
|
1534
|
+
* Change software in Thunder.
|
|
1535
|
+
*
|
|
1536
|
+
* files [{ path, source }] (or { path: source }): the files the edits are for, and any whose calls a rename reaches
|
|
1537
|
+
* edits one Thunder edit or a list (applied in order), e.g. { op: 'setValue', member: 'refund.py#can_refund', step: 'line:8', to: 10 }
|
|
1538
|
+
* options { candidate?: { path: source } — check code someone else (an AI) wrote for these edits; labeled 'ai' }
|
|
1539
|
+
*
|
|
1540
|
+
* Returns { schema, status: 'written' | 'needs-ai' | 'refused', author, patch, files, before, after, proof, says, prompt?, reason? }.
|
|
1541
|
+
* Nothing is written to disk here; the caller decides (the CLI's --apply).
|
|
1542
|
+
*/
|
|
1543
|
+
export function thunderWrite(files, edits, options = {}) {
|
|
1544
|
+
const original = toMap(files);
|
|
1545
|
+
const list = Array.isArray(edits) ? edits : [edits];
|
|
1546
|
+
const base = { schema: WRITE_STEPS_SCHEMA, edits: list };
|
|
1547
|
+
const firstMember = list.find((e) => e?.member)?.member;
|
|
1548
|
+
const before = firstMember ? thunderOf(original, firstMember) : null;
|
|
1549
|
+
if (!list.length) return { ...base, status: 'refused', reason: 'No edits were given.', says: 'Nothing to change.' };
|
|
1550
|
+
|
|
1551
|
+
// Someone else (an AI) wrote the change: check it with the same proof, and label it.
|
|
1552
|
+
if (options.candidate) {
|
|
1553
|
+
const after = new Map(original);
|
|
1554
|
+
for (const [p, s] of Object.entries(options.candidate)) after.set(p, s);
|
|
1555
|
+
let plans = null;
|
|
1556
|
+
try { plans = planOnly(original, list); } catch { plans = null; }
|
|
1557
|
+
const proof = plans ? proveChange(original, after, plans) : proveChange(original, after, []);
|
|
1558
|
+
const patch = [...after.keys()].map((p) => unifiedDiff(p, original.get(p) ?? '', after.get(p))).join('');
|
|
1559
|
+
const ok = proof.ok || (!plans && proof.unchanged.status === 'same');
|
|
1560
|
+
return {
|
|
1561
|
+
...base, status: ok ? 'written' : 'refused', author: 'ai', label: 'AI-written', patch, files: Object.fromEntries(after), before, after: firstMember ? thunderOf(after, firstMember) : null,
|
|
1562
|
+
proof: { ...proof, ...(plans ? {} : { edited: { status: 'not-checked', checks: [], note: 'The intended steps could not be worked out for this edit, so the edited function is shown for a person to check.' } }) },
|
|
1563
|
+
says: ok ? `AI-written: ${list.map(describeEdit).join(' ')} ${plans ? 'Checked: the edited steps read exactly as intended, and nothing else in the file changed meaning.' : 'Checked: nothing else in the file changed meaning; the edited function needs a person to read it.'}` : `The AI-written change does not do what the edit says: ${proof.problems.join(' ')}`,
|
|
1564
|
+
...(ok ? {} : { reason: proof.problems.join(' ') }),
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
let state = makeState(original);
|
|
1569
|
+
const plans = [], said = [];
|
|
1570
|
+
for (const e of list) {
|
|
1571
|
+
try {
|
|
1572
|
+
const r = applyEdit(state, e);
|
|
1573
|
+
state = makeState(r.files, original);
|
|
1574
|
+
plans.push(r.plan);
|
|
1575
|
+
said.push(r.says);
|
|
1576
|
+
} catch (err) {
|
|
1577
|
+
if (err.refused) return { ...base, status: 'refused', reason: err.message, says: `Not changed: ${err.message}`, before };
|
|
1578
|
+
if (err.needsAi) return { ...base, status: 'needs-ai', reason: err.message, prompt: aiPrompt(original, list, err.message), says: `This change needs an AI coding agent: ${err.message} The instruction below is ready to run; its result will be labeled AI-written and checked the same way.`, before };
|
|
1579
|
+
throw err;
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
const after = state.files;
|
|
1583
|
+
const proof = proveChange(original, after, plans);
|
|
1584
|
+
if (!proof.ok) {
|
|
1585
|
+
// The writer's own patch did not prove out: never return it as written.
|
|
1586
|
+
const why = `The written code did not prove out (${proof.problems.join(' ')})`;
|
|
1587
|
+
return { ...base, status: 'needs-ai', reason: why, prompt: aiPrompt(original, list, why), says: `This change needs an AI coding agent: ${why}.`, before, rejected: { patch: [...after.keys()].map((p) => unifiedDiff(p, original.get(p), after.get(p))).join(''), proof } };
|
|
1588
|
+
}
|
|
1589
|
+
const patch = [...after.keys()].map((p) => unifiedDiff(p, original.get(p), after.get(p))).join('');
|
|
1590
|
+
const changedFiles = [...after.keys()].filter((p) => after.get(p) !== original.get(p));
|
|
1591
|
+
const others = proof.unchanged.checked;
|
|
1592
|
+
const tail = others ? `nothing else changed: ${others} other function${others === 1 ? '' : 's'} in ${changedFiles.length === 1 ? 'the file' : 'the files'} mean${others === 1 ? 's' : ''} exactly the same` : 'nothing else in the file changed';
|
|
1593
|
+
const afterRef = plans.find((p) => p.member)?.member;
|
|
1594
|
+
return {
|
|
1595
|
+
...base, status: 'written', author: 'thunder', patch, files: Object.fromEntries(changedFiles.map((p) => [p, after.get(p)])),
|
|
1596
|
+
before, after: afterRef ? thunderOf(after, { file: afterRef.path, name: afterRef.name }) : plans[0]?.added ? thunderOf(after, { file: plans[0].added.path, name: plans[0].added.name }) : null,
|
|
1597
|
+
proof: { edited: proof.edited, unchanged: proof.unchanged },
|
|
1598
|
+
says: `${said.map((x, i) => (i ? x[0].toLowerCase() + x.slice(1) : x)).join('; ')}; ${tail}.`,
|
|
1599
|
+
};
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
/** The intended steps of each edit, without keeping the written code (used to check someone else's code). */
|
|
1603
|
+
function planOnly(original, list) {
|
|
1604
|
+
let state = makeState(original);
|
|
1605
|
+
const plans = [];
|
|
1606
|
+
for (const e of list) { const r = applyEdit(state, e); state = makeState(r.files, original); plans.push(r.plan); }
|
|
1607
|
+
return plans;
|
|
1608
|
+
}
|