@skillstech/thunderlang 1.4.3 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/dist/core.cjs +1437 -292
- package/dist/index.cjs +6013 -4774
- package/dist/learn.cjs +409 -155
- package/package.json +1 -1
- package/src/cli.mjs +8 -5
- package/src/emit.mjs +1 -1
- package/src/mcp.mjs +20 -3
- package/src/passport.mjs +9 -2
- package/src/read-repo-fs.mjs +3 -2
- package/src/trace-cli.mjs +3 -3
- package/src/trace-data.mjs +219 -0
- package/src/trace-fs.mjs +10 -3
- package/src/trace.mjs +207 -16
- package/src/write-steps.mjs +152 -23
- package/src/write-words.mjs +182 -0
- package/src/write.mjs +12 -0
package/src/write-steps.mjs
CHANGED
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
// A patch that fails its proof is never returned as written.
|
|
31
31
|
//
|
|
32
32
|
// Deterministic and browser-safe (no Node APIs): it edits text and reads it; it never runs the code it edits.
|
|
33
|
+
import { thunderTree, thunderStep, looksThunder } from './write-words.mjs';
|
|
33
34
|
import { readCode } from './read.mjs';
|
|
34
35
|
import { readableLanguage } from './read-repo.mjs';
|
|
35
36
|
import { parseExpr, parseStatement, parseStatementSpans, renderExpr, renderStatement, sameExpr, normalizeExpr, nodesOf, sayFull, blockEnd } from './meaning.mjs';
|
|
@@ -153,6 +154,8 @@ function locateStep(steps, sel, { flowSteps } = {}) {
|
|
|
153
154
|
all.push({ step: s, list, index: i, path: [...path, i], parent });
|
|
154
155
|
if (s.children) walk(s.children, [...path, i], s);
|
|
155
156
|
if (s.otherwise) walk(s.otherwise, [...path, i, 'else'], s);
|
|
157
|
+
(s.handlers || []).forEach((h, k) => walk(h.steps || [], [...path, i, `h:${k}`], s));
|
|
158
|
+
if (s.always?.steps) walk(s.always.steps, [...path, i, 'always'], s);
|
|
156
159
|
});
|
|
157
160
|
walk(steps || [], [], null);
|
|
158
161
|
if (Array.isArray(sel)) return all.find((x) => x.path.join('.') === sel.join('.')) ?? null;
|
|
@@ -166,13 +169,17 @@ function locateStep(steps, sel, { flowSteps } = {}) {
|
|
|
166
169
|
if (/^\d+$/.test(String(sel))) return all.find((x) => x.path.join('.') === String(sel)) ?? null;
|
|
167
170
|
return null;
|
|
168
171
|
}
|
|
172
|
+
// Path words that enter another list of a step than its own block: 'else' (the other side of a question), 'h:N'
|
|
173
|
+
// (the Nth error handler of a try: except / catch), 'always' (finally).
|
|
174
|
+
const isSide = (p) => p === 'else' || p === 'always' || (typeof p === 'string' && p.startsWith('h:'));
|
|
175
|
+
const sideOf = (node, p) => (p === 'else' ? (node.o ?? (node.o = [])) : p === 'always' ? (node.a ?? (node.a = [])) : node.h[Number(p.slice(2))].c);
|
|
169
176
|
const pathIn = (shape, path) => {
|
|
170
177
|
let list = shape, node = null;
|
|
171
178
|
for (let i = 0; i < path.length; i++) {
|
|
172
179
|
const p = path[i];
|
|
173
|
-
if (p
|
|
180
|
+
if (isSide(p)) { list = sideOf(node, p); continue; }
|
|
174
181
|
node = list[p];
|
|
175
|
-
if (i < path.length - 1 && path[i + 1]
|
|
182
|
+
if (i < path.length - 1 && !isSide(path[i + 1])) list = node.c;
|
|
176
183
|
}
|
|
177
184
|
return { list, node, index: path[path.length - 1] };
|
|
178
185
|
};
|
|
@@ -180,7 +187,7 @@ const listAt = (shape, path) => {
|
|
|
180
187
|
// The list holding the step at `path`.
|
|
181
188
|
if (path.length === 1) return shape;
|
|
182
189
|
const parentPath = path.slice(0, -1);
|
|
183
|
-
if (parentPath[parentPath.length - 1]
|
|
190
|
+
if (isSide(parentPath[parentPath.length - 1])) return sideOf(pathIn(shape, parentPath.slice(0, -1)).node, parentPath[parentPath.length - 1]);
|
|
184
191
|
return pathIn(shape, parentPath).node.c;
|
|
185
192
|
};
|
|
186
193
|
|
|
@@ -230,9 +237,19 @@ function literalOf(value, language, like = null) {
|
|
|
230
237
|
if (typeof value === 'number') {
|
|
231
238
|
if (!Number.isFinite(value)) refuse(`${value} is not a number that can be written.`);
|
|
232
239
|
let raw = String(value);
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
240
|
+
const was = like?.type === 'number' ? String(like.raw) : '';
|
|
241
|
+
// The file's own way of writing the number: 0xFF stays hex, 0o17 octal, 0b101 binary, 1_000 keeps its groups.
|
|
242
|
+
const base = was.match(/^0([xXoObB])/);
|
|
243
|
+
if (base) {
|
|
244
|
+
if (!Number.isInteger(value) || value < 0) refuse(`${value} cannot be written as a ${{ x: 'hex', o: 'octal', b: 'binary' }[base[1].toLowerCase()]} number like ${was}.`);
|
|
245
|
+
const digits = value.toString({ x: 16, o: 8, b: 2 }[base[1].toLowerCase()]);
|
|
246
|
+
return { kind: 'literal', type: 'number', value, raw: `0${base[1]}${/[A-F]/.test(was.slice(2)) ? digits.toUpperCase() : digits}` };
|
|
247
|
+
}
|
|
248
|
+
if (was.includes('_') && Number.isInteger(value)) raw = String(value).replace(/\B(?=(\d{3})+(?!\d))/g, '_');
|
|
249
|
+
if (/\.\d/.test(was) && Number.isInteger(value)) raw += '.0';
|
|
250
|
+
// A type suffix written after the digits (100m, 2.5f, 10L, 7n, 3u): kept. Other letters are not a suffix.
|
|
251
|
+
const suffix = was.match(/\d([mMfFdDlLnuU]|ul|UL|lu|LU)$/)?.[1] ?? '';
|
|
252
|
+
if (suffix) raw += suffix;
|
|
236
253
|
return { kind: 'literal', type: 'number', value, raw };
|
|
237
254
|
}
|
|
238
255
|
if (typeof value === 'string') {
|
|
@@ -245,15 +262,23 @@ function literalOf(value, language, like = null) {
|
|
|
245
262
|
}
|
|
246
263
|
|
|
247
264
|
const PARSE_ORDER = (lang) => [lang, ...WRITE_STEPS_LANGUAGES.filter((l) => l !== lang)];
|
|
248
|
-
|
|
265
|
+
// The file the current edit is in: Thunder's words are matched against the names written there (write-words.mjs).
|
|
266
|
+
let wordsSource = '', wordsScope = '';
|
|
267
|
+
// Python's `is` compares identity; `x is 5` or `x is true` is Thunder's "is" (equals), not code.
|
|
268
|
+
const misreadIs = (t) => t?.kind === 'compare' && (t.op === 'is' || t.op === 'is not') && !(t.right?.kind === 'literal' && t.right.type === 'null');
|
|
269
|
+
/** An expression a person wrote (in Thunder's words or as code in the file's language), as a tree for this file. */
|
|
249
270
|
function exprFrom(input, language, what = 'expression') {
|
|
250
271
|
if (input && typeof input === 'object' && input.kind) return input;
|
|
251
272
|
if (typeof input !== 'string') return literalOf(input, language);
|
|
273
|
+
let said = null;
|
|
274
|
+
const words = () => (said ??= thunderTree(input, language, wordsSource, wordsScope));
|
|
275
|
+
if (looksThunder(input) && words().tree) return words().tree;
|
|
252
276
|
for (const l of PARSE_ORDER(language)) {
|
|
253
277
|
const t = parseExpr(input, l);
|
|
254
|
-
if (t && t.kind !== 'code') return adapt(t, language);
|
|
278
|
+
if (t && t.kind !== 'code' && !misreadIs(t)) return adapt(t, language);
|
|
255
279
|
}
|
|
256
|
-
|
|
280
|
+
if (words().tree) return words().tree;
|
|
281
|
+
refuse(`The ${what} "${input}" could not be read${said?.error ? ` (${said.error})` : ''}. Write it in Thunder's words, for example "days is more than 10 and not member's vip", or as code.`);
|
|
257
282
|
}
|
|
258
283
|
/** Adapt a tree read in another language to this file's spelling (== in JavaScript is ===, quotes, true/True). */
|
|
259
284
|
function adapt(tree, language) {
|
|
@@ -271,6 +296,9 @@ function adapt(tree, language) {
|
|
|
271
296
|
function statementFrom(input, language) {
|
|
272
297
|
if (input && typeof input === 'object' && input.kind) return input;
|
|
273
298
|
if (typeof input !== 'string' || !input.trim()) refuse('Say the new step as code, for example notify(order.customer).');
|
|
299
|
+
const said = thunderStep(input, language, wordsSource, wordsScope);
|
|
300
|
+
if (said?.tree) return said.tree;
|
|
301
|
+
if (said?.error) refuse(`The step "${input}" could not be read: ${said.error}`);
|
|
274
302
|
for (const l of PARSE_ORDER(language)) {
|
|
275
303
|
const t = parseStatement(input, l);
|
|
276
304
|
if (t && t.kind !== 'code') {
|
|
@@ -366,6 +394,9 @@ function rewriteCode(code, oldTree, newTree, language) {
|
|
|
366
394
|
const trimmed = code.trim();
|
|
367
395
|
if (trimmed.endsWith('{') && !head.endsWith('{')) head = `${head} {`;
|
|
368
396
|
if (!trimmed.endsWith(';') && head.endsWith(';') && !/[{:]$/.test(trimmed)) head = head.replace(/;$/, '');
|
|
397
|
+
// The code being replaced may stop before the block's colon (an elif's condition is kept as "if …"): the colon
|
|
398
|
+
// that opens the block stays in the file, so the new head must not bring a second one.
|
|
399
|
+
if (language === 'python' && head.endsWith(':') && !trimmed.endsWith(':')) head = head.slice(0, -1);
|
|
369
400
|
attempts.push(head);
|
|
370
401
|
} catch { /* the writer cannot say it */ }
|
|
371
402
|
for (const a of attempts) {
|
|
@@ -386,7 +417,11 @@ function headLines(step) {
|
|
|
386
417
|
|
|
387
418
|
/** Replace a step's head in the file with code for `newTree`. Returns the new source. */
|
|
388
419
|
function writeStepTree(source, step, newTree, language) {
|
|
389
|
-
|
|
420
|
+
let [a, b] = headLines(step);
|
|
421
|
+
// A comment or blank line between a question and its first step belongs to neither: the head stops before it.
|
|
422
|
+
const SL = linesOf(source);
|
|
423
|
+
const comment = language === 'python' ? /^\s*(#.*)?$/ : /^\s*(\/\/.*)?$/;
|
|
424
|
+
while (b > a && comment.test(SL[b - 1] ?? '')) b--;
|
|
390
425
|
const starts = lineStarts(source);
|
|
391
426
|
const from = starts[a - 1], to = b < starts.length ? starts[b] - 1 : source.length;
|
|
392
427
|
const region = source.slice(from, to);
|
|
@@ -445,6 +480,7 @@ function renderBlock(steps, language, indent, unit) {
|
|
|
445
480
|
/** A step a person described, as a shape node: a statement, or { if, then, else }, or { stop, error }. */
|
|
446
481
|
function stepSpec(spec, ctx) {
|
|
447
482
|
const { language } = ctx;
|
|
483
|
+
if (typeof spec === 'string') { const said = thunderStep(spec, language, wordsSource, wordsScope); if (said?.stop != null) return { e: stopTree(ctx, null, said.stop), c: [] }; }
|
|
448
484
|
if (typeof spec === 'string' || spec?.kind) return { e: statementFrom(spec, language), c: [] };
|
|
449
485
|
if (spec && typeof spec === 'object' && 'if' in spec) {
|
|
450
486
|
const test = exprFrom(spec.if, language, 'condition');
|
|
@@ -751,9 +787,16 @@ function opSetValue(ctx, edit) {
|
|
|
751
787
|
lit = lits[edit.at];
|
|
752
788
|
if (!lit) refuse(`There is no value number ${edit.at} like that in this step.`);
|
|
753
789
|
} else lit = findLiteral(tree, edit.from);
|
|
754
|
-
|
|
755
|
-
|
|
790
|
+
// `to` is a plain value (10, "platinum", true); `toValue` is Thunder's words or code (placeholder, the length of words).
|
|
791
|
+
const next = edit.toValue != null ? exprFrom(edit.toValue, ctx.language, 'value') : literalOf(edit.to, ctx.language, lit);
|
|
792
|
+
if (next.kind === 'literal' && next.type === lit.type && next.value === lit.value) refuse(`The value is already ${lit.raw}.`);
|
|
756
793
|
const old = lit.raw;
|
|
794
|
+
if (next.kind !== 'literal') {
|
|
795
|
+
Object.keys(lit).forEach((k) => delete lit[k]);
|
|
796
|
+
Object.assign(lit, cloneShape(next));
|
|
797
|
+
ctx.setTree(step, tree);
|
|
798
|
+
return `Changed ${old} to ${sayFull(next)} in ${q(sayStep(step))}`;
|
|
799
|
+
}
|
|
757
800
|
Object.keys(lit).forEach((k) => delete lit[k]);
|
|
758
801
|
Object.assign(lit, next);
|
|
759
802
|
ctx.setTree(step, tree);
|
|
@@ -867,6 +910,15 @@ function opSetGivesBack(ctx, edit) {
|
|
|
867
910
|
}
|
|
868
911
|
|
|
869
912
|
/** Where a new step goes: { lineIndex (insert before this 1-based line), indent, shapeList, shapeIndex }. */
|
|
913
|
+
/** The first line of a step, counting the decorators written above it (@wraps(method) above a def). */
|
|
914
|
+
function withDecorators(source, a) {
|
|
915
|
+
const L = linesOf(source);
|
|
916
|
+
const ind = indentOf(L[a - 1] ?? '');
|
|
917
|
+
let first = a;
|
|
918
|
+
while (first > 1 && /^\s*@/.test(L[first - 2]) && indentOf(L[first - 2]) === ind) first--;
|
|
919
|
+
return first;
|
|
920
|
+
}
|
|
921
|
+
|
|
870
922
|
function placeFor(ctx, edit) {
|
|
871
923
|
const pos = ['before', 'after', 'into'].find((k) => edit[k] != null);
|
|
872
924
|
if (!pos) refuse('Say where the new step goes: before, after, or into ({ step, side: "yes" | "no", at: "start" | "end" }).');
|
|
@@ -890,12 +942,12 @@ function placeFor(ctx, edit) {
|
|
|
890
942
|
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.`);
|
|
891
943
|
const path = [...loc.path];
|
|
892
944
|
if (pos === 'after') path[path.length - 1] += 1;
|
|
893
|
-
return { pos, line: pos === 'after' ? b + 1 : a, indent: indentOf(linesOf(ctx.source)[a - 1]), shapePath: path, loc };
|
|
945
|
+
return { pos, line: pos === 'after' ? b + 1 : withDecorators(ctx.source, a), indent: indentOf(linesOf(ctx.source)[a - 1]), shapePath: path, loc };
|
|
894
946
|
}
|
|
895
947
|
function insertShape(shape, path, nodes) {
|
|
896
948
|
const list = path.length === 1 ? shape : (() => {
|
|
897
949
|
const parentPath = path.slice(0, -1);
|
|
898
|
-
if (parentPath[parentPath.length - 1]
|
|
950
|
+
if (isSide(parentPath[parentPath.length - 1])) return sideOf(pathIn(shape, parentPath.slice(0, -1)).node, parentPath[parentPath.length - 1]);
|
|
899
951
|
return pathIn(shape, parentPath).node.c;
|
|
900
952
|
})();
|
|
901
953
|
list.splice(path[path.length - 1], 0, ...nodes);
|
|
@@ -924,13 +976,25 @@ function insertSteps(ctx, edit, nodes) {
|
|
|
924
976
|
insertShape(ctx.shape, place.shapePath, nodes);
|
|
925
977
|
}
|
|
926
978
|
|
|
979
|
+
/** Is the code just above line `a` (1-based) the end of a Python docstring (a line ending in a quote, not a colon)? */
|
|
980
|
+
function docstringBefore(L, a) {
|
|
981
|
+
for (let i = a - 2; i >= 0; i--) {
|
|
982
|
+
const t = L[i].trim();
|
|
983
|
+
if (!t || t.startsWith('#')) continue;
|
|
984
|
+
return /['"]$/.test(t);
|
|
985
|
+
}
|
|
986
|
+
return false;
|
|
987
|
+
}
|
|
988
|
+
|
|
927
989
|
function removeAt(ctx, loc, { replaceWithPass = true } = {}) {
|
|
928
|
-
const [
|
|
990
|
+
const [a0, b] = stepLines(loc.step);
|
|
991
|
+
const a = withDecorators(ctx.source, a0);
|
|
929
992
|
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.`);
|
|
930
993
|
const L = linesOf(ctx.source);
|
|
931
|
-
// A Python block that would be left empty keeps a `pass
|
|
994
|
+
// A Python block that would be left empty keeps a `pass`: a question's side, a loop, or the function's own body
|
|
995
|
+
// (unless a docstring is still there to fill it).
|
|
932
996
|
const siblings = loc.list.filter((s) => s.expr?.kind !== 'pass');
|
|
933
|
-
if (ctx.language === 'python' && siblings.length === 1 && loc.parent
|
|
997
|
+
if (ctx.language === 'python' && siblings.length === 1 && replaceWithPass && (loc.parent || !docstringBefore(L, a))) ctx.lines(a, b - a + 1, [`${indentOf(L[a - 1])}pass`]);
|
|
934
998
|
else ctx.lines(a, b - a + 1, []);
|
|
935
999
|
listAt(ctx.shape, loc.path).splice(loc.path[loc.path.length - 1], 1);
|
|
936
1000
|
}
|
|
@@ -955,8 +1019,10 @@ function opMoveStep(ctx, edit) {
|
|
|
955
1019
|
if (dest.step === loc.step) refuse('A step cannot move next to itself.');
|
|
956
1020
|
if (dest.path.join('.').startsWith(`${loc.path.join('.')}.`)) refuse('A step cannot move inside itself.');
|
|
957
1021
|
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.');
|
|
958
|
-
const [
|
|
959
|
-
const
|
|
1022
|
+
const [a0, b] = stepLines(loc.step);
|
|
1023
|
+
const a = withDecorators(ctx.source, a0);
|
|
1024
|
+
const [da0, db] = stepLines(dest.step);
|
|
1025
|
+
const da = withDecorators(ctx.source, da0);
|
|
960
1026
|
const L = linesOf(ctx.source);
|
|
961
1027
|
const moved = L.slice(a - 1, b);
|
|
962
1028
|
const fromIndent = indentOf(moved[0]), toIndent = indentOf(L[da - 1]);
|
|
@@ -1211,6 +1277,8 @@ function applyEdit(state, edit) {
|
|
|
1211
1277
|
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 };
|
|
1212
1278
|
}
|
|
1213
1279
|
const m = findMember(state, edit.member);
|
|
1280
|
+
wordsSource = m.source;
|
|
1281
|
+
wordsScope = m.source.split('\n').slice(Math.max(0, m.item.line - 1), memberEnd(m.item)).join('\n');
|
|
1214
1282
|
if (!m.item.steps) needsAi(`Thunder has no steps for ${m.item.name} (line ${m.item.line}), so the edit cannot be placed exactly.`);
|
|
1215
1283
|
let source = m.source;
|
|
1216
1284
|
const ctx = {
|
|
@@ -1279,7 +1347,7 @@ function reworded(says, treeEdits, f, member) {
|
|
|
1279
1347
|
}
|
|
1280
1348
|
function stepPathOf(steps, step) {
|
|
1281
1349
|
let found = null;
|
|
1282
|
-
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']); });
|
|
1350
|
+
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']); (s.handlers || []).forEach((h, k) => walk(h.steps || [], [...path, i, `h:${k}`])); if (s.always?.steps) walk(s.always.steps, [...path, i, 'always']); });
|
|
1283
1351
|
walk(steps, []);
|
|
1284
1352
|
return found;
|
|
1285
1353
|
}
|
|
@@ -1332,6 +1400,17 @@ export function proveChange(before, after, plans) {
|
|
|
1332
1400
|
const editedKeys = new Set(); // path|key in the after files
|
|
1333
1401
|
const ranges = new Map(); // path -> [{ before: [first, last], after: [first, last] }] of the edited functions
|
|
1334
1402
|
const renamed = plans.find((p) => p.renameFunction)?.renameFunction;
|
|
1403
|
+
// Several edits to one function: each edit's plan was made on the code after the edits before it, so only the last
|
|
1404
|
+
// plan says what the function's steps must finally be. What the earlier edits said about its inputs or answer
|
|
1405
|
+
// (an added input) still holds, unless a later edit says it again.
|
|
1406
|
+
const last = new Map();
|
|
1407
|
+
for (const p of plans) {
|
|
1408
|
+
if (p.added) continue;
|
|
1409
|
+
const k = `${p.member.path}|${p.member.key}`;
|
|
1410
|
+
const prev = last.get(k)?.member;
|
|
1411
|
+
last.set(k, { ...p, member: { ...p.member, inputs: p.member.inputs ?? prev?.inputs, returns: p.member.returns ?? prev?.returns } });
|
|
1412
|
+
}
|
|
1413
|
+
plans = [...plans.filter((p) => p.added), ...last.values()];
|
|
1335
1414
|
for (const p of plans) {
|
|
1336
1415
|
if (p.added) {
|
|
1337
1416
|
const r = readOf(after, p.added.path);
|
|
@@ -1495,7 +1574,7 @@ export function describeEdit(e) {
|
|
|
1495
1574
|
const at = (s) => (s == null ? '' : ` (step ${Array.isArray(s) ? s.join('.') : s})`);
|
|
1496
1575
|
const who = e.member ? ` in ${parseMemberRef(e.member).name}` : '';
|
|
1497
1576
|
switch (e.op) {
|
|
1498
|
-
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');
|
|
1577
|
+
case 'setValue': return `Change the value ${e.from !== undefined ? JSON.stringify(e.from) : ''} to ${e.toValue != null ? e.toValue : JSON.stringify(e.to)}${at(e.step)}${who}.`.replace('value to', 'value to');
|
|
1499
1578
|
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(', ')}.`;
|
|
1500
1579
|
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}.`;
|
|
1501
1580
|
case 'removeStep': return `Remove step ${e.step}${who} and everything inside it.`;
|
|
@@ -1584,8 +1663,11 @@ export function thunderWrite(files, edits, options = {}) {
|
|
|
1584
1663
|
|
|
1585
1664
|
let state = makeState(original);
|
|
1586
1665
|
const plans = [], said = [];
|
|
1587
|
-
for (const
|
|
1666
|
+
for (const raw of list) {
|
|
1588
1667
|
try {
|
|
1668
|
+
// Lines in an edit list are the original file's lines (as thunder read showed them): an earlier edit that adds
|
|
1669
|
+
// or removes lines (an input on its own line, a new Stop) moves the lines below it, so they are followed.
|
|
1670
|
+
const e = followLines(raw, original, state.files);
|
|
1589
1671
|
const r = applyEdit(state, e);
|
|
1590
1672
|
state = makeState(r.files, original);
|
|
1591
1673
|
plans.push(r.plan);
|
|
@@ -1620,6 +1702,53 @@ export function thunderWrite(files, edits, options = {}) {
|
|
|
1620
1702
|
function planOnly(original, list) {
|
|
1621
1703
|
let state = makeState(original);
|
|
1622
1704
|
const plans = [];
|
|
1623
|
-
for (const
|
|
1705
|
+
for (const raw of list) { const r = applyEdit(state, followLines(raw, original, state.files)); state = makeState(r.files, original); plans.push(r.plan); }
|
|
1624
1706
|
return plans;
|
|
1625
1707
|
}
|
|
1708
|
+
|
|
1709
|
+
/**
|
|
1710
|
+
* Where line `n` of `before` is in `after` (1-based), or null when an edit rewrote it. Lines above and below the
|
|
1711
|
+
* changed region keep their place (shifted by the lines added or removed); a line inside it is found again only by
|
|
1712
|
+
* its exact text, when that text is there once on each side.
|
|
1713
|
+
*/
|
|
1714
|
+
export function followLine(before, after, n, { start = false } = {}) {
|
|
1715
|
+
if (before === after) return n;
|
|
1716
|
+
const a = before.split('\n'), b = after.split('\n');
|
|
1717
|
+
let p = 0;
|
|
1718
|
+
while (p < a.length && p < b.length && a[p] === b[p]) p++;
|
|
1719
|
+
let q = 0;
|
|
1720
|
+
while (q < a.length - p && q < b.length - p && a[a.length - 1 - q] === b[b.length - 1 - q]) q++;
|
|
1721
|
+
if (n <= p) return n;
|
|
1722
|
+
// Where something starts (a function's first line) stays put when everything above it is unchanged, even if the
|
|
1723
|
+
// line itself was rewritten (an input added to its signature).
|
|
1724
|
+
if (start && n === p + 1) return n;
|
|
1725
|
+
if (n > a.length - q) return n + (b.length - a.length);
|
|
1726
|
+
const text = a[n - 1];
|
|
1727
|
+
if (!text.trim()) return null;
|
|
1728
|
+
const inA = a.slice(p, a.length - q).filter((l) => l === text).length;
|
|
1729
|
+
const hits = [];
|
|
1730
|
+
for (let i = p; i < b.length - q; i++) if (b[i] === text) hits.push(i + 1);
|
|
1731
|
+
return inA === 1 && hits.length === 1 ? hits[0] : null;
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
function followLines(edit, original, current) {
|
|
1735
|
+
if (!edit || typeof edit !== 'object' || original === current) return edit;
|
|
1736
|
+
// The file the edit is for: named in the member ({ file } or "path#name"), or the only file given.
|
|
1737
|
+
let path = typeof edit.member === 'object' ? edit.member?.file : typeof edit.member === 'string' && edit.member.includes('#') ? edit.member.split('#')[0] : null;
|
|
1738
|
+
if (!path || !original.has(path)) {
|
|
1739
|
+
const changed = [...original.keys()].filter((p) => original.get(p) !== current.get(p));
|
|
1740
|
+
if (original.size === 1) path = [...original.keys()][0];
|
|
1741
|
+
else if (changed.length === 1) path = changed[0];
|
|
1742
|
+
else if (changed.length > 1 && ['step', 'before', 'after'].some((k) => /^line:\d+$/.test(String(edit[k] ?? '')))) refuse('Several files changed in this list and this edit does not name its file; give its member as { file, name } so its lines can be followed.');
|
|
1743
|
+
}
|
|
1744
|
+
if (!path || !original.has(path) || !current.has(path) || original.get(path) === current.get(path)) return edit;
|
|
1745
|
+
const move = (n, opts) => {
|
|
1746
|
+
const to = followLine(original.get(path), current.get(path), n, opts);
|
|
1747
|
+
if (to == null) refuse(`Line ${n} was rewritten by an earlier edit in this list, so it cannot be found again; give that edit after this one, or address the step by its new line.`);
|
|
1748
|
+
return to;
|
|
1749
|
+
};
|
|
1750
|
+
const out = { ...edit };
|
|
1751
|
+
for (const k of ['step', 'before', 'after']) { const m = typeof out[k] === 'string' && out[k].match(/^line:(\d+)$/); if (m) out[k] = `line:${move(Number(m[1]))}`; }
|
|
1752
|
+
if (typeof out.member === 'object' && out.member?.line) out.member = { ...out.member, line: move(out.member.line, { start: true }) };
|
|
1753
|
+
return out;
|
|
1754
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Thunder write in Thunder's own words: a condition, a value, or a step written the way Thunder reads code
|
|
2
|
+
// ("amount is at least 100", "the length of words is 0", "name is nothing", Stop with "Amount must be positive")
|
|
3
|
+
// becomes the meaning tree (thunder-expr-v1) that thunder write turns into code for the file's language.
|
|
4
|
+
//
|
|
5
|
+
// thunderTree("total is below 0 and not member", "python", source) -> total < 0 and not member
|
|
6
|
+
// thunderStep('Give the length of words', "go", source) -> return len(words)
|
|
7
|
+
//
|
|
8
|
+
// Names are the code's own names said as words: `max_length`, `maxLength`, and "max length" are the same name, matched
|
|
9
|
+
// against the names written in the file. A Thunder word with no fixed meaning in the target language (a position
|
|
10
|
+
// "item 1 of", money, percent, dates) is refused rather than guessed. Browser-safe; nothing is run.
|
|
11
|
+
import { ExprParser } from './core/parser.mjs';
|
|
12
|
+
import { tokenizeLine } from './core/lexer.mjs';
|
|
13
|
+
|
|
14
|
+
/** The words a code name is made of: max_length, maxLength, MaxLength -> "max length". */
|
|
15
|
+
export const nameWords = (id) => id.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').replace(/_+/g, ' ').trim().toLowerCase();
|
|
16
|
+
|
|
17
|
+
const KEYWORDS = new Set(['def', 'return', 'if', 'elif', 'else', 'for', 'while', 'in', 'is', 'not', 'and', 'or', 'None', 'True', 'False', 'class', 'import', 'from', 'as', 'with', 'try', 'except', 'finally', 'raise', 'lambda', 'pass', 'break', 'continue', 'yield', 'function', 'const', 'let', 'var', 'new', 'this', 'null', 'undefined', 'true', 'false', 'typeof', 'instanceof', 'throw', 'catch', 'switch', 'case', 'default', 'func', 'package', 'nil', 'type', 'struct', 'interface', 'go', 'defer', 'chan', 'map', 'range', 'export', 'async', 'await', 'self', 'cls']);
|
|
18
|
+
|
|
19
|
+
// Code with its comments and text values blanked out: a word in a docstring ("Value of ...") is not a name.
|
|
20
|
+
const codeOnly = (src) => String(src ?? '')
|
|
21
|
+
.replace(/"""[\s\S]*?"""|'''[\s\S]*?'''/g, ' ')
|
|
22
|
+
.replace(/\/\*[\s\S]*?\*\//g, ' ')
|
|
23
|
+
.replace(/`(?:\\[\s\S]|[^`\\])*`|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'/g, ' ')
|
|
24
|
+
.replace(/(#|\/\/)[^\n]*/g, ' ');
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Every name written in the code, by its words: Map("max length" -> "max_length"). The names in `scope` (the edited
|
|
28
|
+
* function's own code) come first; then the rest of the file. A word that is itself a name (`value`) is that name,
|
|
29
|
+
* never another spelling of the same words (`Value`).
|
|
30
|
+
*/
|
|
31
|
+
function namesOf(source, scope) {
|
|
32
|
+
const byWords = new Map(), exact = new Set();
|
|
33
|
+
for (const text of [scope, source]) {
|
|
34
|
+
for (const m of codeOnly(text).matchAll(/\b[A-Za-z_][A-Za-z0-9_]*\b/g)) {
|
|
35
|
+
const id = m[0];
|
|
36
|
+
if (KEYWORDS.has(id)) continue;
|
|
37
|
+
exact.add(id);
|
|
38
|
+
const w = nameWords(id);
|
|
39
|
+
if (w && !byWords.has(w)) byWords.set(w, id);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
for (const id of exact) byWords.set(id, id);
|
|
43
|
+
for (const [w, id] of byWords) if (exact.has(w)) byWords.set(w, w);
|
|
44
|
+
return byWords;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Words and shapes only Thunder uses: when one is in the text, it is read as Thunder before it is read as code.
|
|
48
|
+
const THUNDER_MARKERS = /\b(is (not )?(at least|at most|more than|less than|greater than|fewer than|below|above|under|over|nothing|missing|between|true|false|empty)|the (length|number|count|lowercase|uppercase|first|last|sum|total|trimmed) of|contains|starts with|ends with|plus|minus|times|divided by|equals)\b|'s\b/i;
|
|
49
|
+
|
|
50
|
+
const lit = (type, value, raw) => ({ kind: 'literal', type, value, raw });
|
|
51
|
+
const NULL_RAW = { python: 'None', go: 'nil', typescript: 'null', javascript: 'null' };
|
|
52
|
+
|
|
53
|
+
class Unsaid extends Error {}
|
|
54
|
+
const no = (why) => { throw new Unsaid(why); };
|
|
55
|
+
|
|
56
|
+
/** A Core expression (core/parser.mjs) as a meaning tree for `language`. */
|
|
57
|
+
function toTree(n, language, names) {
|
|
58
|
+
const T = (x) => toTree(x, language, names);
|
|
59
|
+
const py = language === 'python', go = language === 'go', js = language === 'typescript' || language === 'javascript';
|
|
60
|
+
const call = (callee, args) => ({ kind: 'call', callee, args });
|
|
61
|
+
const member = (object, property) => ({ kind: 'member', object, property });
|
|
62
|
+
const nm = (name) => ({ kind: 'name', name });
|
|
63
|
+
switch (n.k) {
|
|
64
|
+
case 'paren': return T(n.e);
|
|
65
|
+
case 'num': return lit('number', Number(n.text), n.text);
|
|
66
|
+
case 'str':
|
|
67
|
+
if (n.parts.some((p) => typeof p !== 'string')) no('a text with values inside it ({…})');
|
|
68
|
+
return lit('text', n.parts.join(''), JSON.stringify(n.parts.join('')));
|
|
69
|
+
case 'bool': return lit('bool', n.v, py ? (n.v ? 'True' : 'False') : String(n.v));
|
|
70
|
+
case 'nothing': return lit('null', null, NULL_RAW[language]);
|
|
71
|
+
case 'name': {
|
|
72
|
+
const id = names.get(n.name) ?? (/^[A-Za-z_]\w*$/.test(n.name) ? n.name : null);
|
|
73
|
+
if (!id) no(`"${n.name}" (no name in the file is said that way)`);
|
|
74
|
+
return nm(id);
|
|
75
|
+
}
|
|
76
|
+
case 'field': case 'dot': {
|
|
77
|
+
if (n.args) no('a call written with a dot');
|
|
78
|
+
const prop = n.k === 'field' ? n.name : n.attr;
|
|
79
|
+
return member(T(n.obj), names.get(prop) ?? prop.replace(/ /g, '_'));
|
|
80
|
+
}
|
|
81
|
+
case 'neg': return { kind: 'unary', op: '-', value: T(n.e) };
|
|
82
|
+
case 'not': return { kind: 'not', value: T(n.e) };
|
|
83
|
+
case 'bin': {
|
|
84
|
+
if (n.op === 'and' || n.op === 'or') {
|
|
85
|
+
const operands = [];
|
|
86
|
+
for (const side of [n.l, n.r]) { const t = T(side); if (t.kind === 'logic' && t.op === n.op) operands.push(...t.operands); else operands.push(t); }
|
|
87
|
+
return { kind: 'logic', op: n.op, operands };
|
|
88
|
+
}
|
|
89
|
+
const op = { '+': '+', '-': '-', '*': '*', '/': '/', mod: '%', '%': '%' }[n.op];
|
|
90
|
+
if (!op) no(`"${n.op}"`);
|
|
91
|
+
return { kind: 'binary', op, left: T(n.l), right: T(n.r) };
|
|
92
|
+
}
|
|
93
|
+
case 'cmp': {
|
|
94
|
+
// "member is true" means equal to true, not truthy (in Python 1 and "x" are truthy): `member is True` in Python,
|
|
95
|
+
// `=== true` in JavaScript. A person who means truthy writes "member" or "not member".
|
|
96
|
+
if (py && (n.op === '==' || n.op === '!=') && n.r.k === 'bool') return { kind: 'compare', op: n.op === '==' ? 'is' : 'is not', left: T(n.l), right: T(n.r) };
|
|
97
|
+
const op = n.op === '==' ? (js ? '===' : '==') : n.op === '!=' ? (js ? '!==' : '!=') : n.op;
|
|
98
|
+
return { kind: 'compare', op, left: T(n.l), right: T(n.r) };
|
|
99
|
+
}
|
|
100
|
+
case 'isNothing': {
|
|
101
|
+
// "is nothing": Python's `is None`; JavaScript's `== null` (null or undefined); Go's `== nil`.
|
|
102
|
+
const op = py ? (n.neg ? 'is not' : 'is') : n.neg ? '!=' : '==';
|
|
103
|
+
return { kind: 'compare', op, left: T(n.e), right: lit('null', null, NULL_RAW[language]) };
|
|
104
|
+
}
|
|
105
|
+
case 'between': {
|
|
106
|
+
const e = T(n.e);
|
|
107
|
+
return { kind: 'logic', op: 'and', operands: [{ kind: 'compare', op: '>=', left: e, right: T(n.lo) }, { kind: 'compare', op: '<=', left: e, right: T(n.hi) }] };
|
|
108
|
+
}
|
|
109
|
+
case 'contains': {
|
|
110
|
+
if (py) return { kind: 'compare', op: 'in', left: T(n.r), right: T(n.l) };
|
|
111
|
+
if (js) return call(member(T(n.l), 'includes'), [T(n.r)]);
|
|
112
|
+
no('"contains" in Go (strings.Contains or slices.Contains depends on the value)');
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
case 'affix': {
|
|
116
|
+
const l = T(n.l), r = T(n.r);
|
|
117
|
+
if (py) return call(member(l, n.end ? 'endswith' : 'startswith'), [r]);
|
|
118
|
+
if (js) return call(member(l, n.end ? 'endsWith' : 'startsWith'), [r]);
|
|
119
|
+
return call(member(nm('strings'), n.end ? 'HasSuffix' : 'HasPrefix'), [l, r]);
|
|
120
|
+
}
|
|
121
|
+
case 'op': {
|
|
122
|
+
const a = T(n.arg);
|
|
123
|
+
if (n.op === 'length' || n.op === 'count') return js ? member(a, 'length') : call(nm('len'), [a]);
|
|
124
|
+
if (n.op === 'lowercase') return py ? call(member(a, 'lower'), []) : js ? call(member(a, 'toLowerCase'), []) : call(member(nm('strings'), 'ToLower'), [a]);
|
|
125
|
+
if (n.op === 'uppercase') return py ? call(member(a, 'upper'), []) : js ? call(member(a, 'toUpperCase'), []) : call(member(nm('strings'), 'ToUpper'), [a]);
|
|
126
|
+
if (n.op === 'trimmed') return py ? call(member(a, 'strip'), []) : js ? call(member(a, 'trim'), []) : call(member(nm('strings'), 'TrimSpace'), [a]);
|
|
127
|
+
if (n.op === 'first') return { kind: 'index', object: a, index: lit('number', 0, '0') };
|
|
128
|
+
if (n.op === 'last') return py ? { kind: 'index', object: a, index: { kind: 'unary', op: '-', value: lit('number', 1, '1') } } : { kind: 'index', object: a, index: { kind: 'binary', op: '-', left: js ? member(a, 'length') : call(nm('len'), [a]), right: lit('number', 1, '1') } };
|
|
129
|
+
no(`"the ${n.word} of"`);
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
default: no(`"${n.k}"`);
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function parseThunder(text, source, scope) {
|
|
138
|
+
const names = namesOf(source, scope);
|
|
139
|
+
const known = new Map([...names.keys()].map((k) => [k, 'var']));
|
|
140
|
+
const ep = new ExprParser({ known, fields: new Set(names.keys()), records: new Set(), recordFields: new Map(), funcInputs: new Map(), recordText: new Map(), screens: new Map() });
|
|
141
|
+
const lexed = tokenizeLine(String(text), 1);
|
|
142
|
+
const tokens = Array.isArray(lexed) ? lexed : lexed.tokens;
|
|
143
|
+
return { node: ep.parse(tokens, 1), names };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* A condition or value in Thunder's words, as a meaning tree for `language`, or { error } when it is not Thunder or
|
|
148
|
+
* cannot be said in that language. `source`: the file, whose names the words are matched against.
|
|
149
|
+
*/
|
|
150
|
+
export function thunderTree(text, language, source, scope = '') {
|
|
151
|
+
let parsed;
|
|
152
|
+
try { parsed = parseThunder(text, source, scope); } catch (e) { return { error: String(e.message).replace(/^Line 1: /, '').split('\n')[0] }; }
|
|
153
|
+
try { return { tree: toTree(parsed.node, language, parsed.names) }; } catch (e) {
|
|
154
|
+
if (e instanceof Unsaid) return { error: `Thunder write cannot say ${e.message} in ${language} yet.` };
|
|
155
|
+
throw e;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Does the text use words only Thunder uses (so it is read as Thunder before it is read as code)? */
|
|
160
|
+
export const looksThunder = (text) => typeof text === 'string' && THUNDER_MARKERS.test(text);
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* A step in Thunder's words: `Give <value>`, `Set <name> to <value>`, or `Stop with "<message>"`.
|
|
164
|
+
* Returns { tree } (a return or an assignment), { stop: message }, { error }, or null when it is not one of these.
|
|
165
|
+
*/
|
|
166
|
+
export function thunderStep(text, language, source, scope = '') {
|
|
167
|
+
const t = String(text).trim();
|
|
168
|
+
let m;
|
|
169
|
+
if ((m = t.match(/^stop with\s+(["'])(.*)\1\s*$/i))) return { stop: m[2] };
|
|
170
|
+
if ((m = t.match(/^give(?: back)?\s+(.+)$/i))) {
|
|
171
|
+
const v = thunderTree(m[1], language, source, scope);
|
|
172
|
+
return v.tree ? { tree: { kind: 'return', value: v.tree } } : { error: v.error };
|
|
173
|
+
}
|
|
174
|
+
if ((m = t.match(/^set\s+(.+?)\s+to\s+(.+)$/i))) {
|
|
175
|
+
const target = thunderTree(m[1], language, source, scope), value = thunderTree(m[2], language, source, scope);
|
|
176
|
+
if (!target.tree) return { error: target.error };
|
|
177
|
+
if (!value.tree) return { error: value.error };
|
|
178
|
+
if (target.tree.kind !== 'name' && target.tree.kind !== 'member') return { error: `"${m[1]}" is not a name to set.` };
|
|
179
|
+
return { tree: { kind: 'assign', op: '=', target: target.tree, value: value.tree } };
|
|
180
|
+
}
|
|
181
|
+
return null;
|
|
182
|
+
}
|
package/src/write.mjs
CHANGED
|
@@ -53,6 +53,14 @@ function scanSource(source, from, to, language) {
|
|
|
53
53
|
continue;
|
|
54
54
|
}
|
|
55
55
|
if (/[0-9]/.test(c)) {
|
|
56
|
+
// 0xFF, 0o17, 0b101: one number, written back in the same base.
|
|
57
|
+
const based = source.slice(i, to).match(/^0([xXoObB])([0-9A-Fa-f_]+)/);
|
|
58
|
+
if (based) {
|
|
59
|
+
const radix = { x: 16, o: 8, b: 2 }[based[1].toLowerCase()];
|
|
60
|
+
out.push({ t: 'num', v: parseInt(based[2].replace(/_/g, ''), radix), start: i, end: i + based[0].length, raw: based[0], suffix: '', decimal: false, base: based[1], upper: /[A-F]/.test(based[2]) });
|
|
61
|
+
i += based[0].length;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
56
64
|
const m = source.slice(i, to).match(/^[0-9][0-9_]*(\.[0-9][0-9_]*)?([eE][+-]?[0-9]+)?(f64|f32|i32|i64|u32|u64|[fFdDmMlLuU]{0,2})/);
|
|
57
65
|
const raw = m[0];
|
|
58
66
|
const suffix = m[3] || '';
|
|
@@ -89,6 +97,10 @@ function spell(srcTok, next) {
|
|
|
89
97
|
return next.v;
|
|
90
98
|
}
|
|
91
99
|
if (next.t === 'num') {
|
|
100
|
+
if (srcTok.base && Number.isInteger(next.v) && next.v >= 0) {
|
|
101
|
+
const d = next.v.toString({ x: 16, o: 8, b: 2 }[srcTok.base.toLowerCase()]);
|
|
102
|
+
return `0${srcTok.base}${srcTok.upper ? d.toUpperCase() : d}`;
|
|
103
|
+
}
|
|
92
104
|
let s = String(next.v);
|
|
93
105
|
if (srcTok.decimal && Number.isInteger(next.v)) s += '.0';
|
|
94
106
|
return s + srcTok.suffix;
|