@skillstech/thunderlang 1.5.0 → 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 +28 -0
- package/dist/core.cjs +1036 -134
- package/dist/index.cjs +5543 -4624
- package/dist/learn.cjs +12 -1
- package/package.json +1 -1
- package/src/cli.mjs +7 -4
- package/src/emit.mjs +1 -1
- package/src/mcp.mjs +18 -1
- package/src/write-steps.mjs +152 -23
- package/src/write-words.mjs +182 -0
- package/src/write.mjs +12 -0
package/dist/learn.cjs
CHANGED
|
@@ -17250,7 +17250,7 @@ var SEMANTIC_TYPES = Object.keys(SEMANTIC);
|
|
|
17250
17250
|
var PRIMITIVE_TYPES = Object.keys(PRIMITIVE);
|
|
17251
17251
|
|
|
17252
17252
|
// src/emit.mjs
|
|
17253
|
-
var COMPILER_VERSION = "1.
|
|
17253
|
+
var COMPILER_VERSION = "1.6.0";
|
|
17254
17254
|
|
|
17255
17255
|
// src/lift.mjs
|
|
17256
17256
|
var IR_SCHEMA_VERSION = "0.1.0";
|
|
@@ -42684,6 +42684,13 @@ function scanSource(source, from, to, language) {
|
|
|
42684
42684
|
continue;
|
|
42685
42685
|
}
|
|
42686
42686
|
if (/[0-9]/.test(c)) {
|
|
42687
|
+
const based = source.slice(i, to).match(/^0([xXoObB])([0-9A-Fa-f_]+)/);
|
|
42688
|
+
if (based) {
|
|
42689
|
+
const radix = { x: 16, o: 8, b: 2 }[based[1].toLowerCase()];
|
|
42690
|
+
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]) });
|
|
42691
|
+
i += based[0].length;
|
|
42692
|
+
continue;
|
|
42693
|
+
}
|
|
42687
42694
|
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})/);
|
|
42688
42695
|
const raw = m[0];
|
|
42689
42696
|
const suffix = m[3] || "";
|
|
@@ -42719,6 +42726,10 @@ function spell(srcTok, next) {
|
|
|
42719
42726
|
return next.v;
|
|
42720
42727
|
}
|
|
42721
42728
|
if (next.t === "num") {
|
|
42729
|
+
if (srcTok.base && Number.isInteger(next.v) && next.v >= 0) {
|
|
42730
|
+
const d = next.v.toString({ x: 16, o: 8, b: 2 }[srcTok.base.toLowerCase()]);
|
|
42731
|
+
return `0${srcTok.base}${srcTok.upper ? d.toUpperCase() : d}`;
|
|
42732
|
+
}
|
|
42722
42733
|
let s = String(next.v);
|
|
42723
42734
|
if (srcTok.decimal && Number.isInteger(next.v)) s += ".0";
|
|
42724
42735
|
return s + srcTok.suffix;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skillstech/thunderlang",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "Thunder™, the human programming language: the deterministic ThunderLang™ compiler, CLI, and Language Server. No AI required. Reads code in seventeen languages into Thunder, changes TypeScript, JavaScript, Python, and Go code from Thunder with a proof, compiles rules to six languages, and executes them: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
package/src/cli.mjs
CHANGED
|
@@ -512,12 +512,13 @@ Read and understand code
|
|
|
512
512
|
thunderize <folder | owner/repo> [--out <dir>] [--json] the whole app in Thunder Text: one .thunder-text per file + APP.thunder-text
|
|
513
513
|
|
|
514
514
|
Change code
|
|
515
|
-
write <file> --edit '<json>' [--edit …] [--also <file>] [--apply] [--test "<cmd>"] [--candidate <file>] [--json]
|
|
515
|
+
write <file> --edit '<json>' [--edit …] | --edits <list.json|-> [--also <file>] [--apply] [--test "<cmd>"] [--candidate <file>] [--json]
|
|
516
516
|
Writing in Thunder: change a step, question, Stop, input, or function in Thunder; the code is
|
|
517
517
|
written as a minimal patch (TS/JS, Python, Go) and proven (the edited steps mean exactly
|
|
518
|
-
the edit; everything else means the same).
|
|
519
|
-
|
|
520
|
-
--
|
|
518
|
+
the edit; everything else means the same). Conditions and values in Thunder's words
|
|
519
|
+
("amount is at least 100", "name is nothing") or as code; steps by their line in thunder read.
|
|
520
|
+
Dry run by default; --apply saves; --test runs a command on the changed code. Other cases
|
|
521
|
+
print an instruction for an AI coding agent; --candidate checks code it wrote (AI-written).
|
|
521
522
|
write <file> --decision <name> --rule <n|otherwise> [--when "<condition>"] [--answer <Outcome>] [--write] [--json]
|
|
522
523
|
Thunder write: change a number, comparison, text value, or answer in a recovered rule;
|
|
523
524
|
previews the exact code change and the cases whose answer changes; --write saves it
|
|
@@ -751,6 +752,8 @@ function main() {
|
|
|
751
752
|
}
|
|
752
753
|
// One rule change written into every service that implements it (src/write-across-cli.mjs).
|
|
753
754
|
if (cmd === 'write' && isWriteAcross(restArgv)) { writeAcrossMain(restArgv).then((code) => { process.exitCode = code; }); return; }
|
|
755
|
+
// thunder write <file> --edits <list.json | ->: the edits from a file (or stdin), the same JSON as --edit.
|
|
756
|
+
if (cmd === 'write' && args.edits && !args.edit) args.edit = [args.edits === '-' ? readFileSync(0, 'utf8') : readFileSync(args.edits, 'utf8')];
|
|
754
757
|
if (cmd === 'write' && args.edit) {
|
|
755
758
|
try {
|
|
756
759
|
if (!file) throw new Error('Use thunder write <file> --edit \'{"op":"setValue","member":"name","step":"line:12","to":10}\' [--apply] [--test "<cmd>"].');
|
package/src/emit.mjs
CHANGED
|
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
|
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
export const COMPILER_VERSION = '1.
|
|
33
|
+
export const COMPILER_VERSION = '1.6.0';
|
|
34
34
|
export const PROOF_SCHEMA_VERSION = '0.1.0';
|
|
35
35
|
// Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
|
|
36
36
|
// Certified to key cert proofs to the compiler. Stable slug per the coordination bus.
|
package/src/mcp.mjs
CHANGED
|
@@ -19,6 +19,7 @@ import { resolveObligations } from './obligations.mjs';
|
|
|
19
19
|
import { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode } from './review-atlas.mjs';
|
|
20
20
|
import { evaluateDecision } from './runtime.mjs';
|
|
21
21
|
import { buildTrace, traceImpact, traceImpactOf, renderImpact } from './trace.mjs';
|
|
22
|
+
import { thunderWrite } from './write-steps.mjs';
|
|
22
23
|
import { readRepoDir, gitChanges } from './trace-fs.mjs';
|
|
23
24
|
import { buildIntentGraph } from './intent-graph.mjs';
|
|
24
25
|
import { buildConformance } from './conformance.mjs';
|
|
@@ -284,6 +285,22 @@ const TOOLS = [
|
|
|
284
285
|
return { ...r, text: renderImpact(r) };
|
|
285
286
|
},
|
|
286
287
|
},
|
|
288
|
+
{
|
|
289
|
+
name: 'intent_write',
|
|
290
|
+
description: 'CHANGE CODE THROUGH THUNDER, WITH PROOF (TypeScript, JavaScript, Python, Go). Give the files ({ path, source }) and one or more Thunder edits; get back a minimal patch, the new file contents, and a proof: the edited function now reads exactly as the edit says, and every other function means the same. Edits: setValue (to, or toValue in Thunder words), setCondition (when: "amount is at least 100 and not member"), addStep / removeStep / moveStep (step: code, "Give …", "Set … to …", "Stop with \"…\"", or { if, then, else }), addStop (when, message), removeStop, addInput (name, default), removeInput, setGivesBack (value), rename. Each edit names its function (member: "name" or { file, name, line }) and its step by the line thunder read shows ("line:12"); lines are the original file\'s lines for every edit in the list. Status is written, refused (with why), or needs-ai (with an instruction for a coding agent). Nothing is written to disk: apply the returned files, then run the project\'s tests.',
|
|
291
|
+
inputSchema: {
|
|
292
|
+
type: 'object', required: ['files', 'edits'],
|
|
293
|
+
properties: {
|
|
294
|
+
files: { type: 'array', minItems: 1, maxItems: 20, items: { type: 'object', required: ['path', 'source'], properties: { path: str, source: str } } },
|
|
295
|
+
edits: { description: 'one Thunder edit object, or a list applied in order', anyOf: [{ type: 'object' }, { type: 'array', items: { type: 'object' } }] },
|
|
296
|
+
},
|
|
297
|
+
},
|
|
298
|
+
run: ({ files, edits }) => {
|
|
299
|
+
if (!Array.isArray(files) || !files.length) throw new Error('Give the files as [{ path, source }].');
|
|
300
|
+
const r = thunderWrite(files.map((f) => ({ path: String(f.path), source: String(f.source) })), edits);
|
|
301
|
+
return { status: r.status, says: r.says, reason: r.reason ?? null, patch: r.patch ?? null, files: r.files ?? null, before: r.before ?? null, after: r.after ?? null, proof: r.proof ?? null, ...(r.prompt ? { prompt: r.prompt } : {}) };
|
|
302
|
+
},
|
|
303
|
+
},
|
|
287
304
|
{
|
|
288
305
|
name: 'intent_promote',
|
|
289
306
|
description: 'Turn a decision recovered from code into a readable ThunderLang contract with starter examples chosen at every rule and threshold. The examples record what the code does TODAY (computed from the recovered rule), so a person must confirm each answer; after that, intent_verify_diff can hold every change to it. Give the source code and the decision (function) name.',
|
|
@@ -322,7 +339,7 @@ const TOOLS = [
|
|
|
322
339
|
|
|
323
340
|
// Tools that are pure functions of their arguments (no filesystem, git, or process state), so they
|
|
324
341
|
// are safe to serve to remote clients such as ChatGPT. intent_prove reads the local repository.
|
|
325
|
-
export const REMOTE_SAFE_TOOLS = ['intent_check', 'intent_verify_diff', 'intent_conform', 'intent_drift', 'intent_draft', 'intent_lift', 'intent_run', 'intent_test', 'intent_graph', 'intent_explain', 'intent_read', 'intent_promote', 'intent_translate', 'intent_human'];
|
|
342
|
+
export const REMOTE_SAFE_TOOLS = ['intent_check', 'intent_verify_diff', 'intent_conform', 'intent_drift', 'intent_draft', 'intent_lift', 'intent_run', 'intent_test', 'intent_graph', 'intent_explain', 'intent_read', 'intent_promote', 'intent_translate', 'intent_human', 'intent_write'];
|
|
326
343
|
|
|
327
344
|
export const MCP_TOOLS = TOOLS.map((t) => t.name);
|
|
328
345
|
|
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
|
+
}
|