@skillstech/thunderlang 1.5.0 → 1.6.1
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 +37 -0
- package/dist/core.cjs +1135 -161
- package/dist/index.cjs +5641 -4650
- 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 +164 -24
- package/src/write-words.mjs +239 -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.1";
|
|
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.1",
|
|
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.1';
|
|
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, unknownName, unknownNameReason } 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,30 @@ 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 known(adapt(t, language), language);
|
|
255
279
|
}
|
|
256
|
-
|
|
280
|
+
if (words().tree) return words().tree;
|
|
281
|
+
if (said?.unknown) refuse(`The ${what} "${input}" could not be read: ${said.error}`);
|
|
282
|
+
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.`);
|
|
283
|
+
}
|
|
284
|
+
/** A tree written as code, refused when it uses a name the code does not have (it would fail when run). */
|
|
285
|
+
function known(tree, language) {
|
|
286
|
+
const word = unknownName(tree, language, wordsSource, wordsScope);
|
|
287
|
+
if (word) refuse(`It cannot be written: ${unknownNameReason(word, wordsScope)}`);
|
|
288
|
+
return tree;
|
|
257
289
|
}
|
|
258
290
|
/** Adapt a tree read in another language to this file's spelling (== in JavaScript is ===, quotes, true/True). */
|
|
259
291
|
function adapt(tree, language) {
|
|
@@ -271,11 +303,15 @@ function adapt(tree, language) {
|
|
|
271
303
|
function statementFrom(input, language) {
|
|
272
304
|
if (input && typeof input === 'object' && input.kind) return input;
|
|
273
305
|
if (typeof input !== 'string' || !input.trim()) refuse('Say the new step as code, for example notify(order.customer).');
|
|
306
|
+
const said = thunderStep(input, language, wordsSource, wordsScope);
|
|
307
|
+
if (said?.tree) return said.tree;
|
|
308
|
+
if (said?.error) refuse(`The step "${input}" could not be read: ${said.error}`);
|
|
274
309
|
for (const l of PARSE_ORDER(language)) {
|
|
275
310
|
const t = parseStatement(input, l);
|
|
276
311
|
if (t && t.kind !== 'code') {
|
|
277
312
|
const a = adapt(t, language);
|
|
278
|
-
try { renderStatement(a, language);
|
|
313
|
+
try { renderStatement(a, language); } catch { continue; /* try the next reading */ }
|
|
314
|
+
return known(a, language);
|
|
279
315
|
}
|
|
280
316
|
}
|
|
281
317
|
refuse(`The step "${input}" could not be read as one statement.`);
|
|
@@ -366,6 +402,9 @@ function rewriteCode(code, oldTree, newTree, language) {
|
|
|
366
402
|
const trimmed = code.trim();
|
|
367
403
|
if (trimmed.endsWith('{') && !head.endsWith('{')) head = `${head} {`;
|
|
368
404
|
if (!trimmed.endsWith(';') && head.endsWith(';') && !/[{:]$/.test(trimmed)) head = head.replace(/;$/, '');
|
|
405
|
+
// The code being replaced may stop before the block's colon (an elif's condition is kept as "if …"): the colon
|
|
406
|
+
// that opens the block stays in the file, so the new head must not bring a second one.
|
|
407
|
+
if (language === 'python' && head.endsWith(':') && !trimmed.endsWith(':')) head = head.slice(0, -1);
|
|
369
408
|
attempts.push(head);
|
|
370
409
|
} catch { /* the writer cannot say it */ }
|
|
371
410
|
for (const a of attempts) {
|
|
@@ -386,7 +425,11 @@ function headLines(step) {
|
|
|
386
425
|
|
|
387
426
|
/** Replace a step's head in the file with code for `newTree`. Returns the new source. */
|
|
388
427
|
function writeStepTree(source, step, newTree, language) {
|
|
389
|
-
|
|
428
|
+
let [a, b] = headLines(step);
|
|
429
|
+
// A comment or blank line between a question and its first step belongs to neither: the head stops before it.
|
|
430
|
+
const SL = linesOf(source);
|
|
431
|
+
const comment = language === 'python' ? /^\s*(#.*)?$/ : /^\s*(\/\/.*)?$/;
|
|
432
|
+
while (b > a && comment.test(SL[b - 1] ?? '')) b--;
|
|
390
433
|
const starts = lineStarts(source);
|
|
391
434
|
const from = starts[a - 1], to = b < starts.length ? starts[b] - 1 : source.length;
|
|
392
435
|
const region = source.slice(from, to);
|
|
@@ -445,6 +488,7 @@ function renderBlock(steps, language, indent, unit) {
|
|
|
445
488
|
/** A step a person described, as a shape node: a statement, or { if, then, else }, or { stop, error }. */
|
|
446
489
|
function stepSpec(spec, ctx) {
|
|
447
490
|
const { language } = ctx;
|
|
491
|
+
if (typeof spec === 'string') { const said = thunderStep(spec, language, wordsSource, wordsScope); if (said?.stop != null) return { e: stopTree(ctx, null, said.stop), c: [] }; }
|
|
448
492
|
if (typeof spec === 'string' || spec?.kind) return { e: statementFrom(spec, language), c: [] };
|
|
449
493
|
if (spec && typeof spec === 'object' && 'if' in spec) {
|
|
450
494
|
const test = exprFrom(spec.if, language, 'condition');
|
|
@@ -751,9 +795,16 @@ function opSetValue(ctx, edit) {
|
|
|
751
795
|
lit = lits[edit.at];
|
|
752
796
|
if (!lit) refuse(`There is no value number ${edit.at} like that in this step.`);
|
|
753
797
|
} else lit = findLiteral(tree, edit.from);
|
|
754
|
-
|
|
755
|
-
|
|
798
|
+
// `to` is a plain value (10, "platinum", true); `toValue` is Thunder's words or code (placeholder, the length of words).
|
|
799
|
+
const next = edit.toValue != null ? exprFrom(edit.toValue, ctx.language, 'value') : literalOf(edit.to, ctx.language, lit);
|
|
800
|
+
if (next.kind === 'literal' && next.type === lit.type && next.value === lit.value) refuse(`The value is already ${lit.raw}.`);
|
|
756
801
|
const old = lit.raw;
|
|
802
|
+
if (next.kind !== 'literal') {
|
|
803
|
+
Object.keys(lit).forEach((k) => delete lit[k]);
|
|
804
|
+
Object.assign(lit, cloneShape(next));
|
|
805
|
+
ctx.setTree(step, tree);
|
|
806
|
+
return `Changed ${old} to ${sayFull(next)} in ${q(sayStep(step))}`;
|
|
807
|
+
}
|
|
757
808
|
Object.keys(lit).forEach((k) => delete lit[k]);
|
|
758
809
|
Object.assign(lit, next);
|
|
759
810
|
ctx.setTree(step, tree);
|
|
@@ -867,6 +918,15 @@ function opSetGivesBack(ctx, edit) {
|
|
|
867
918
|
}
|
|
868
919
|
|
|
869
920
|
/** Where a new step goes: { lineIndex (insert before this 1-based line), indent, shapeList, shapeIndex }. */
|
|
921
|
+
/** The first line of a step, counting the decorators written above it (@wraps(method) above a def). */
|
|
922
|
+
function withDecorators(source, a) {
|
|
923
|
+
const L = linesOf(source);
|
|
924
|
+
const ind = indentOf(L[a - 1] ?? '');
|
|
925
|
+
let first = a;
|
|
926
|
+
while (first > 1 && /^\s*@/.test(L[first - 2]) && indentOf(L[first - 2]) === ind) first--;
|
|
927
|
+
return first;
|
|
928
|
+
}
|
|
929
|
+
|
|
870
930
|
function placeFor(ctx, edit) {
|
|
871
931
|
const pos = ['before', 'after', 'into'].find((k) => edit[k] != null);
|
|
872
932
|
if (!pos) refuse('Say where the new step goes: before, after, or into ({ step, side: "yes" | "no", at: "start" | "end" }).');
|
|
@@ -890,12 +950,12 @@ function placeFor(ctx, edit) {
|
|
|
890
950
|
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
951
|
const path = [...loc.path];
|
|
892
952
|
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 };
|
|
953
|
+
return { pos, line: pos === 'after' ? b + 1 : withDecorators(ctx.source, a), indent: indentOf(linesOf(ctx.source)[a - 1]), shapePath: path, loc };
|
|
894
954
|
}
|
|
895
955
|
function insertShape(shape, path, nodes) {
|
|
896
956
|
const list = path.length === 1 ? shape : (() => {
|
|
897
957
|
const parentPath = path.slice(0, -1);
|
|
898
|
-
if (parentPath[parentPath.length - 1]
|
|
958
|
+
if (isSide(parentPath[parentPath.length - 1])) return sideOf(pathIn(shape, parentPath.slice(0, -1)).node, parentPath[parentPath.length - 1]);
|
|
899
959
|
return pathIn(shape, parentPath).node.c;
|
|
900
960
|
})();
|
|
901
961
|
list.splice(path[path.length - 1], 0, ...nodes);
|
|
@@ -924,13 +984,25 @@ function insertSteps(ctx, edit, nodes) {
|
|
|
924
984
|
insertShape(ctx.shape, place.shapePath, nodes);
|
|
925
985
|
}
|
|
926
986
|
|
|
987
|
+
/** Is the code just above line `a` (1-based) the end of a Python docstring (a line ending in a quote, not a colon)? */
|
|
988
|
+
function docstringBefore(L, a) {
|
|
989
|
+
for (let i = a - 2; i >= 0; i--) {
|
|
990
|
+
const t = L[i].trim();
|
|
991
|
+
if (!t || t.startsWith('#')) continue;
|
|
992
|
+
return /['"]$/.test(t);
|
|
993
|
+
}
|
|
994
|
+
return false;
|
|
995
|
+
}
|
|
996
|
+
|
|
927
997
|
function removeAt(ctx, loc, { replaceWithPass = true } = {}) {
|
|
928
|
-
const [
|
|
998
|
+
const [a0, b] = stepLines(loc.step);
|
|
999
|
+
const a = withDecorators(ctx.source, a0);
|
|
929
1000
|
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
1001
|
const L = linesOf(ctx.source);
|
|
931
|
-
// A Python block that would be left empty keeps a `pass
|
|
1002
|
+
// A Python block that would be left empty keeps a `pass`: a question's side, a loop, or the function's own body
|
|
1003
|
+
// (unless a docstring is still there to fill it).
|
|
932
1004
|
const siblings = loc.list.filter((s) => s.expr?.kind !== 'pass');
|
|
933
|
-
if (ctx.language === 'python' && siblings.length === 1 && loc.parent
|
|
1005
|
+
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
1006
|
else ctx.lines(a, b - a + 1, []);
|
|
935
1007
|
listAt(ctx.shape, loc.path).splice(loc.path[loc.path.length - 1], 1);
|
|
936
1008
|
}
|
|
@@ -955,8 +1027,10 @@ function opMoveStep(ctx, edit) {
|
|
|
955
1027
|
if (dest.step === loc.step) refuse('A step cannot move next to itself.');
|
|
956
1028
|
if (dest.path.join('.').startsWith(`${loc.path.join('.')}.`)) refuse('A step cannot move inside itself.');
|
|
957
1029
|
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
|
|
1030
|
+
const [a0, b] = stepLines(loc.step);
|
|
1031
|
+
const a = withDecorators(ctx.source, a0);
|
|
1032
|
+
const [da0, db] = stepLines(dest.step);
|
|
1033
|
+
const da = withDecorators(ctx.source, da0);
|
|
960
1034
|
const L = linesOf(ctx.source);
|
|
961
1035
|
const moved = L.slice(a - 1, b);
|
|
962
1036
|
const fromIndent = indentOf(moved[0]), toIndent = indentOf(L[da - 1]);
|
|
@@ -1174,6 +1248,9 @@ function opAddFunction(state, edit) {
|
|
|
1174
1248
|
if (language === 'go' && inputs.some((p) => !p.type)) refuse('Go needs a type for every input.');
|
|
1175
1249
|
const ctx = { language, source, item: { name, line: 1 } };
|
|
1176
1250
|
if (language === 'go' && edit.returns) ctx.goResults = edit.returns;
|
|
1251
|
+
// The new function's names are its inputs and the file's names.
|
|
1252
|
+
wordsScope = `${name}(${inputs.map((p) => p.name).join(', ')})`;
|
|
1253
|
+
wordsSource = `${wordsScope}\n${source}`;
|
|
1177
1254
|
const nodes = (edit.steps || []).map((s) => stepSpec(s, { ...ctx, source: `${source}\nfunc ${name}() (${edit.returns || ''}) {}` }));
|
|
1178
1255
|
if (!nodes.length) refuse('A new function needs at least one step.');
|
|
1179
1256
|
const unit = indentUnit(source, language);
|
|
@@ -1211,6 +1288,8 @@ function applyEdit(state, edit) {
|
|
|
1211
1288
|
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
1289
|
}
|
|
1213
1290
|
const m = findMember(state, edit.member);
|
|
1291
|
+
wordsSource = m.source;
|
|
1292
|
+
wordsScope = m.source.split('\n').slice(Math.max(0, m.item.line - 1), memberEnd(m.item)).join('\n');
|
|
1214
1293
|
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
1294
|
let source = m.source;
|
|
1216
1295
|
const ctx = {
|
|
@@ -1279,7 +1358,7 @@ function reworded(says, treeEdits, f, member) {
|
|
|
1279
1358
|
}
|
|
1280
1359
|
function stepPathOf(steps, step) {
|
|
1281
1360
|
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']); });
|
|
1361
|
+
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
1362
|
walk(steps, []);
|
|
1284
1363
|
return found;
|
|
1285
1364
|
}
|
|
@@ -1332,6 +1411,17 @@ export function proveChange(before, after, plans) {
|
|
|
1332
1411
|
const editedKeys = new Set(); // path|key in the after files
|
|
1333
1412
|
const ranges = new Map(); // path -> [{ before: [first, last], after: [first, last] }] of the edited functions
|
|
1334
1413
|
const renamed = plans.find((p) => p.renameFunction)?.renameFunction;
|
|
1414
|
+
// Several edits to one function: each edit's plan was made on the code after the edits before it, so only the last
|
|
1415
|
+
// plan says what the function's steps must finally be. What the earlier edits said about its inputs or answer
|
|
1416
|
+
// (an added input) still holds, unless a later edit says it again.
|
|
1417
|
+
const last = new Map();
|
|
1418
|
+
for (const p of plans) {
|
|
1419
|
+
if (p.added) continue;
|
|
1420
|
+
const k = `${p.member.path}|${p.member.key}`;
|
|
1421
|
+
const prev = last.get(k)?.member;
|
|
1422
|
+
last.set(k, { ...p, member: { ...p.member, inputs: p.member.inputs ?? prev?.inputs, returns: p.member.returns ?? prev?.returns } });
|
|
1423
|
+
}
|
|
1424
|
+
plans = [...plans.filter((p) => p.added), ...last.values()];
|
|
1335
1425
|
for (const p of plans) {
|
|
1336
1426
|
if (p.added) {
|
|
1337
1427
|
const r = readOf(after, p.added.path);
|
|
@@ -1495,7 +1585,7 @@ export function describeEdit(e) {
|
|
|
1495
1585
|
const at = (s) => (s == null ? '' : ` (step ${Array.isArray(s) ? s.join('.') : s})`);
|
|
1496
1586
|
const who = e.member ? ` in ${parseMemberRef(e.member).name}` : '';
|
|
1497
1587
|
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');
|
|
1588
|
+
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
1589
|
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
1590
|
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
1591
|
case 'removeStep': return `Remove step ${e.step}${who} and everything inside it.`;
|
|
@@ -1584,8 +1674,11 @@ export function thunderWrite(files, edits, options = {}) {
|
|
|
1584
1674
|
|
|
1585
1675
|
let state = makeState(original);
|
|
1586
1676
|
const plans = [], said = [];
|
|
1587
|
-
for (const
|
|
1677
|
+
for (const raw of list) {
|
|
1588
1678
|
try {
|
|
1679
|
+
// Lines in an edit list are the original file's lines (as thunder read showed them): an earlier edit that adds
|
|
1680
|
+
// or removes lines (an input on its own line, a new Stop) moves the lines below it, so they are followed.
|
|
1681
|
+
const e = followLines(raw, original, state.files);
|
|
1589
1682
|
const r = applyEdit(state, e);
|
|
1590
1683
|
state = makeState(r.files, original);
|
|
1591
1684
|
plans.push(r.plan);
|
|
@@ -1620,6 +1713,53 @@ export function thunderWrite(files, edits, options = {}) {
|
|
|
1620
1713
|
function planOnly(original, list) {
|
|
1621
1714
|
let state = makeState(original);
|
|
1622
1715
|
const plans = [];
|
|
1623
|
-
for (const
|
|
1716
|
+
for (const raw of list) { const r = applyEdit(state, followLines(raw, original, state.files)); state = makeState(r.files, original); plans.push(r.plan); }
|
|
1624
1717
|
return plans;
|
|
1625
1718
|
}
|
|
1719
|
+
|
|
1720
|
+
/**
|
|
1721
|
+
* Where line `n` of `before` is in `after` (1-based), or null when an edit rewrote it. Lines above and below the
|
|
1722
|
+
* changed region keep their place (shifted by the lines added or removed); a line inside it is found again only by
|
|
1723
|
+
* its exact text, when that text is there once on each side.
|
|
1724
|
+
*/
|
|
1725
|
+
export function followLine(before, after, n, { start = false } = {}) {
|
|
1726
|
+
if (before === after) return n;
|
|
1727
|
+
const a = before.split('\n'), b = after.split('\n');
|
|
1728
|
+
let p = 0;
|
|
1729
|
+
while (p < a.length && p < b.length && a[p] === b[p]) p++;
|
|
1730
|
+
let q = 0;
|
|
1731
|
+
while (q < a.length - p && q < b.length - p && a[a.length - 1 - q] === b[b.length - 1 - q]) q++;
|
|
1732
|
+
if (n <= p) return n;
|
|
1733
|
+
// Where something starts (a function's first line) stays put when everything above it is unchanged, even if the
|
|
1734
|
+
// line itself was rewritten (an input added to its signature).
|
|
1735
|
+
if (start && n === p + 1) return n;
|
|
1736
|
+
if (n > a.length - q) return n + (b.length - a.length);
|
|
1737
|
+
const text = a[n - 1];
|
|
1738
|
+
if (!text.trim()) return null;
|
|
1739
|
+
const inA = a.slice(p, a.length - q).filter((l) => l === text).length;
|
|
1740
|
+
const hits = [];
|
|
1741
|
+
for (let i = p; i < b.length - q; i++) if (b[i] === text) hits.push(i + 1);
|
|
1742
|
+
return inA === 1 && hits.length === 1 ? hits[0] : null;
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
function followLines(edit, original, current) {
|
|
1746
|
+
if (!edit || typeof edit !== 'object' || original === current) return edit;
|
|
1747
|
+
// The file the edit is for: named in the member ({ file } or "path#name"), or the only file given.
|
|
1748
|
+
let path = typeof edit.member === 'object' ? edit.member?.file : typeof edit.member === 'string' && edit.member.includes('#') ? edit.member.split('#')[0] : null;
|
|
1749
|
+
if (!path || !original.has(path)) {
|
|
1750
|
+
const changed = [...original.keys()].filter((p) => original.get(p) !== current.get(p));
|
|
1751
|
+
if (original.size === 1) path = [...original.keys()][0];
|
|
1752
|
+
else if (changed.length === 1) path = changed[0];
|
|
1753
|
+
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.');
|
|
1754
|
+
}
|
|
1755
|
+
if (!path || !original.has(path) || !current.has(path) || original.get(path) === current.get(path)) return edit;
|
|
1756
|
+
const move = (n, opts) => {
|
|
1757
|
+
const to = followLine(original.get(path), current.get(path), n, opts);
|
|
1758
|
+
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.`);
|
|
1759
|
+
return to;
|
|
1760
|
+
};
|
|
1761
|
+
const out = { ...edit };
|
|
1762
|
+
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]))}`; }
|
|
1763
|
+
if (typeof out.member === 'object' && out.member?.line) out.member = { ...out.member, line: move(out.member.line, { start: true }) };
|
|
1764
|
+
return out;
|
|
1765
|
+
}
|