@skillstech/thunderlang 0.5.2 → 0.5.5
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 +132 -0
- package/dist/core.cjs +10204 -6621
- package/dist/index.cjs +3867 -1771
- package/package.json +1 -1
- package/src/anchor.d.mts +12 -0
- package/src/anchor.mjs +127 -0
- package/src/cli.mjs +148 -39
- package/src/codegen.mjs +27 -9
- package/src/core.d.ts +24 -0
- package/src/core.mjs +19 -1
- package/src/emit.mjs +1 -1
- package/src/index.d.ts +26 -0
- package/src/index.mjs +14 -0
- package/src/mcp.mjs +19 -32
- package/src/model.d.mts +18 -0
- package/src/model.mjs +456 -0
- package/src/obligations.d.mts +9 -0
- package/src/obligations.mjs +35 -0
- package/src/plain-contract.d.mts +30 -0
- package/src/plain-contract.mjs +339 -0
- package/src/promote.mjs +19 -5
- package/src/read.d.mts +25 -1
- package/src/read.mjs +415 -23
- package/src/review-atlas.d.mts +19 -0
- package/src/review-atlas.mjs +136 -0
- package/src/same.d.mts +10 -0
- package/src/same.mjs +160 -0
- package/src/steps.d.mts +2 -0
- package/src/steps.mjs +599 -0
- package/src/target-types.mjs +39 -4
- package/src/testing.mjs +12 -9
- package/src/thunder-repo.mjs +96 -0
- package/src/thunderize.d.mts +14 -0
- package/src/thunderize.mjs +82 -0
- package/src/visual.d.mts +40 -0
- package/src/visual.mjs +304 -0
- package/src/write.d.mts +24 -0
- package/src/write.mjs +263 -0
package/src/visual.mjs
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// thunder-visual-v1: the visual grammar of Thunder V1, as data.
|
|
2
|
+
//
|
|
3
|
+
// Thunder is written for the people who read software, not for the computer that runs it. The picture is the main
|
|
4
|
+
// form; Thunder Text is the same thing in structured words for those who want detail; the original code is always
|
|
5
|
+
// one click away. This module is the single source of truth for how Thunder looks: every view (thunderlang.dev,
|
|
6
|
+
// OpenThunder, the VS Code extension) renders from it and does not re-decide shapes, colors, or wording.
|
|
7
|
+
// See docs/spec.md (Thunder V1).
|
|
8
|
+
import { plainFromReading, renderPlainContract } from './plain-contract.mjs';
|
|
9
|
+
|
|
10
|
+
export const VISUAL_SCHEMA = 'thunder-visual-v1';
|
|
11
|
+
|
|
12
|
+
export const PRINCIPLE = 'We are no longer writing code for the computer. We are writing code for humans.';
|
|
13
|
+
|
|
14
|
+
/** The forms one piece of software can take in Thunder, in the order a reader meets them. */
|
|
15
|
+
export const FORMS = [
|
|
16
|
+
{ id: 'picture', name: 'Thunder', role: 'main', says: 'The visual form: cards, steps, and maps. What most people read.' },
|
|
17
|
+
{ id: 'text', name: 'Thunder Text', role: 'detail', says: 'The same meaning in structured words, for reading in detail, reviewing, and storing.' },
|
|
18
|
+
{ id: 'meaning', name: 'The meaning', role: 'model', says: 'The one reading both views are made from. The picture and Thunder Text are two views of it, never translations of each other.' },
|
|
19
|
+
{ id: 'source', name: 'Original code', role: 'evidence', says: 'The code in its own language. Always one click away (View original).' },
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Zoom levels. Read in Thunder (OpenThunder ADR 0035) walks App > File > Action > Rule > Original; the Thunder Atlas
|
|
24
|
+
* (ADR 0033) adds Area between App and File for large apps. `atlas` gives the Atlas level for each.
|
|
25
|
+
*/
|
|
26
|
+
export const ZOOM = [
|
|
27
|
+
{ level: 0, name: 'App', from: 'A product or a repository', element: 'app', atlas: 'Z0' },
|
|
28
|
+
{ level: 1, name: 'Area', from: 'A feature area, service, package, or folder (Atlas; optional in Read in Thunder)', element: 'area', atlas: 'Z1' },
|
|
29
|
+
{ level: 2, name: 'File', from: 'A file, module, or class', element: 'file', atlas: 'Z2' },
|
|
30
|
+
{ level: 3, name: 'Action', from: 'A door into the app: an endpoint or a screen, and the handler behind it', element: 'action', atlas: 'Z3' },
|
|
31
|
+
{ level: 4, name: 'Rule', from: 'One decision (a Thunder card) or the steps of a function', element: 'decision', atlas: 'Z3' },
|
|
32
|
+
{ level: 5, name: 'Original', from: 'The exact lines in the original language', element: 'source', atlas: 'Z4' },
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Color roles. Each kind of word keeps one hue everywhere it appears (picture, text, legend). Hex values are for the
|
|
37
|
+
* dark theme; a light theme may darken them but must keep the same role per hue. Color is never the only signal:
|
|
38
|
+
* every colored thing also has a mark, a word, or a shape.
|
|
39
|
+
*/
|
|
40
|
+
export const COLORS = {
|
|
41
|
+
structure: { hex: '#C4B5FD', name: 'violet', for: 'Structure words: when, otherwise, all of these, for each' },
|
|
42
|
+
question: { hex: '#7FB2FF', name: 'blue', for: "A decision's question and branches (If)" },
|
|
43
|
+
fact: { hex: '#FCD34D', name: 'yellow', for: 'Facts a rule reads, values a step works out, routes' },
|
|
44
|
+
comparison: { hex: '#F472B6', name: 'pink', for: 'Comparisons and checks: at least, at most, is set' },
|
|
45
|
+
amount: { hex: '#FDBA74', name: 'orange', for: 'Amounts and numbers' },
|
|
46
|
+
outcome: { hex: '#67E8F9', name: 'cyan', for: 'Outcomes and what a function hands back' },
|
|
47
|
+
name: { hex: '#BEF264', name: 'lime', for: 'Example names' },
|
|
48
|
+
failure: { hex: '#FDBA74', name: 'orange', for: 'Ways a function fails (always with the ✕ mark and the word Fails, which tell it apart from amounts)' },
|
|
49
|
+
pass: { hex: '#34D399', name: 'green', for: 'ONLY a check that ran and passed' },
|
|
50
|
+
fail: { hex: '#F87171', name: 'red', for: 'ONLY a check that ran and failed' },
|
|
51
|
+
unread: { hex: '#9CA3AF', name: 'grey, dashed', for: 'Not established: not read, not confirmed, or not run' },
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** Line styles carry trust. Solid means established; dashed means not established (never a guess drawn solid). */
|
|
55
|
+
export const LINES = {
|
|
56
|
+
solid: 'From code (read exactly) or confirmed by a person',
|
|
57
|
+
dashed: 'Not established: not read, only partly read, an AI summary, or not yet run',
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Where a piece of Thunder came from. Every element shows exactly one, as a chip. Chips are neutral grey with a solid
|
|
62
|
+
* or dashed outline: color stays reserved for word roles, so a chip never borrows a role's hue. Labels are the words
|
|
63
|
+
* agreed with OpenThunder (ADR 0035).
|
|
64
|
+
*/
|
|
65
|
+
export const PROVENANCE = {
|
|
66
|
+
'from-code': { label: 'From code', line: 'solid', says: 'Read exactly from the source by the Thunder compiler, with no AI.' },
|
|
67
|
+
confirmed: { label: 'Confirmed', line: 'solid', says: 'A person confirmed this reading is what the software should do.' },
|
|
68
|
+
'authors-note': { label: "Author's note", line: 'solid', says: "The code author's own words (docstring or doc comment), verbatim. A statement, not a reading." },
|
|
69
|
+
'ai-summary': { label: 'AI summary', line: 'dashed', says: 'Written by AI to explain. Never evidence; the exact reading is shown beneath it.' },
|
|
70
|
+
'not-read': { label: 'Not read yet', line: 'dashed', says: 'Thunder could not read this yet. The original code is shown instead, never a guess.' },
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** Step marks: shape first, color second. `show: 'code'` means the original code is shown instead of words. */
|
|
74
|
+
export const STEP_MARKS = {
|
|
75
|
+
check: { mark: '✓', label: 'Check', color: 'comparison', show: 'words' },
|
|
76
|
+
branch: { mark: '◇', label: 'If', color: 'question', show: 'words' },
|
|
77
|
+
loop: { mark: '↻', label: 'For each', color: 'structure', show: 'words' },
|
|
78
|
+
set: { mark: '=', label: 'Works out', color: 'fact', show: 'words' },
|
|
79
|
+
call: { mark: '→', label: 'Calls', color: 'outcome', show: 'words' },
|
|
80
|
+
return: { mark: '⇥', label: 'Gives back', color: 'outcome', show: 'words' },
|
|
81
|
+
fail: { mark: '✕', label: 'Fails', color: 'failure', show: 'words' },
|
|
82
|
+
try: { mark: '⛉', label: 'Tries', color: 'structure', show: 'words' },
|
|
83
|
+
restates: { mark: '·', label: 'Code', color: 'unread', show: 'code', line: 'dashed' },
|
|
84
|
+
other: { mark: '·', label: 'Not read yet', color: 'unread', show: 'code', line: 'dashed' },
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Every element a reader meets when software is shown in Thunder. `status` is honest about the compiler today:
|
|
89
|
+
* 'available' (the reader produces it), 'partial' (some languages), 'planned' (defined here, not produced yet).
|
|
90
|
+
*/
|
|
91
|
+
export const ELEMENTS = {
|
|
92
|
+
app: { zoom: 0, name: 'App', shape: 'map', status: 'available', shows: 'Its folders or areas, how many actions, decisions, and functions each holds, and what could not be read yet.', text: 'App <name>' },
|
|
93
|
+
area: { zoom: 1, name: 'Area', shape: 'map-region', status: 'available', shows: 'A folder, package, or service, with its files.', text: 'Area <name>' },
|
|
94
|
+
file: { zoom: 2, name: 'File', shape: 'stack', status: 'available', shows: 'What you can do here: every action and function in the file, in order.', text: 'File <path>' },
|
|
95
|
+
'data-shape': { zoom: 2, name: 'Data shape', shape: 'table-card', status: 'planned', shows: 'A record, class, enum, or database table: its fields, their kinds, and the allowed values.', text: 'A <Name> has\n <field>, <kind>' },
|
|
96
|
+
action: { zoom: 3, name: 'Action', shape: 'steps-card', badge: 'route', status: 'available', shows: 'A door into the app (an endpoint with its method and path, or a screen), then what its handler does as steps.', text: 'When someone calls <METHOD> <path>' },
|
|
97
|
+
decision: { zoom: 4, name: 'Thunder card', shape: 'card', status: 'available', shows: 'One decision: its question, the facts it reads, each rule, the outcome otherwise, and examples you can ask.', text: '<Question>?\n <Outcome> when ...\n Otherwise, <Outcome>.' },
|
|
98
|
+
function: { zoom: 4, name: 'Steps card', shape: 'steps-card', status: 'available', shows: 'What a function does, as a short list of steps with one level of nesting.', text: 'What <name> does\n - <step>' },
|
|
99
|
+
'not-read': { zoom: 4, name: 'Not-read-yet card', shape: 'dashed-card', line: 'dashed', status: 'available', shows: 'A function Thunder cannot read well yet, with its original code.', text: 'Not read: <name> (see the code)' },
|
|
100
|
+
error: { zoom: 4, name: 'Failure', shape: 'chip', mark: '✕', color: 'failure', status: 'available', shows: 'A way the code can fail, by name.', text: 'Can fail with <Name>' },
|
|
101
|
+
test: { zoom: 4, name: 'Test', shape: 'chip', mark: '⚑', color: 'structure', status: 'available', shows: 'A test that exists. Green or red only once it has run.', text: 'Test: <name>' },
|
|
102
|
+
event: { zoom: 3, name: 'Trigger', shape: 'steps-card', badge: 'when', status: 'planned', shows: 'Something that runs when an event happens (a database trigger, a message handler, a schedule).', text: 'When <event>, it\n - <step>' },
|
|
103
|
+
source: { zoom: 5, name: 'Original code', shape: 'code', status: 'available', shows: 'The exact lines, highlighted, in the original language.', text: '(the original code)' },
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** The languages Thunder reads, and how each one's constructs become Thunder elements. */
|
|
107
|
+
export const LANGUAGES = {
|
|
108
|
+
python: { name: 'Python', status: 'available', action: '@app.get / @router.post (FastAPI), @app.route (Flask)', decision: 'a def that returns fixed answers', doc: 'docstring', 'data-shape': '@dataclass, pydantic BaseModel, Enum (planned)' },
|
|
109
|
+
typescript: { name: 'TypeScript', status: 'available', action: 'NestJS @Get/@Post, Express router.post(...)', decision: 'a function that returns fixed answers', doc: '/** JSDoc */', 'data-shape': 'interface, type, enum (planned)' },
|
|
110
|
+
javascript: { name: 'JavaScript', status: 'available', action: 'Express app.get / router.post(...)', decision: 'a function that returns fixed answers', doc: '/** JSDoc */', 'data-shape': 'classes (planned)' },
|
|
111
|
+
go: { name: 'Go', status: 'available', action: 'not yet (net/http, Gin planned)', decision: 'a func that returns fixed answers', doc: '// comment above the func', 'data-shape': 'struct, const iota (planned)' },
|
|
112
|
+
rust: { name: 'Rust', status: 'available', action: 'not yet (Actix, Axum planned)', decision: 'a fn with match or if returning fixed answers', doc: '/// doc comment', 'data-shape': 'struct, enum (planned)' },
|
|
113
|
+
csharp: { name: 'C#', status: 'available', action: '[HttpGet] / [HttpPost]', decision: 'a method that returns fixed answers', doc: '/// <summary>', 'data-shape': 'class, record, enum (planned)' },
|
|
114
|
+
java: { name: 'Java', status: 'available', action: '@GetMapping / @PostMapping (Spring)', decision: 'a method that returns fixed answers', doc: '/** Javadoc */', 'data-shape': 'class, record, enum (planned)' },
|
|
115
|
+
kotlin: { name: 'Kotlin', status: 'available', action: 'Spring annotations', decision: 'a fun with when or if returning fixed answers', doc: '/** KDoc */', 'data-shape': 'data class, enum class (planned)' },
|
|
116
|
+
php: { name: 'PHP', status: 'available', action: '#[Route] (Symfony)', decision: 'a function that returns fixed answers', doc: '/** PHPDoc */', 'data-shape': 'class, enum (planned)' },
|
|
117
|
+
ruby: { name: 'Ruby', status: 'available', action: 'Sinatra get/post blocks (Rails routes.rb planned)', decision: 'a def that returns fixed answers', doc: '# comment above the def', 'data-shape': 'class, Struct (planned)' },
|
|
118
|
+
sql: { name: 'SQL', status: 'planned', action: '(none: SQL is reached through the app)', decision: 'CHECK constraints, CASE expressions, IF in procedures', doc: '-- comment above, COMMENT ON', 'data-shape': 'CREATE TABLE / VIEW', event: 'CREATE TRIGGER', steps: 'SELECT / INSERT / UPDATE / DELETE: which data, filtered by which conditions, changed how' },
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/** Rules every Thunder view follows. A view that breaks one is wrong, however good it looks. */
|
|
122
|
+
export const RULES = [
|
|
123
|
+
'Show the picture first, Thunder Text second, and the original code one click away.',
|
|
124
|
+
'Never draw a guess. What Thunder cannot read is shown as Not read yet, dashed, with the original code.',
|
|
125
|
+
'Green and red mean only a check that ran and passed or failed.',
|
|
126
|
+
"Every element shows where it came from: From code, Confirmed, Author's note, AI summary, or Not read yet.",
|
|
127
|
+
"An AI summary is labeled, dashed, and always sits above the exact reading it summarizes, never instead of it.",
|
|
128
|
+
"The author's note (a docstring) is shown as the author's statement, verbatim, separate from what the code does.",
|
|
129
|
+
'Say the action that is really possible: Propose rule change until a change is written back and checked; never Update code.',
|
|
130
|
+
'Use the reader\'s words: plain names, no syntax. A step that would only restate the code shows the code instead.',
|
|
131
|
+
];
|
|
132
|
+
|
|
133
|
+
const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* How to draw one reader item (from readCode) in Thunder. Views call this instead of deciding shape and labels.
|
|
137
|
+
* Returns { element, shape, line, title, badge?, provenance, doc? }.
|
|
138
|
+
*/
|
|
139
|
+
export function visualFor(item) {
|
|
140
|
+
if (!item || typeof item !== 'object') throw new Error('visualFor needs a reader item.');
|
|
141
|
+
const base = { provenance: item.provenance === 'confirmed' ? 'confirmed' : 'from-code', ...(item.doc ? { doc: { text: item.doc, provenance: 'authors-note' } } : {}) };
|
|
142
|
+
if (item.kind === 'error') return { element: 'error', shape: 'chip', line: 'solid', mark: '✕', color: 'failure', title: `Can fail with ${item.name}`, ...base };
|
|
143
|
+
if (item.kind === 'test') return { element: 'test', shape: 'chip', line: 'solid', mark: '⚑', color: 'structure', title: `Test: ${item.name}`, ...base };
|
|
144
|
+
const badge = item.route ? { kind: 'route', text: `${item.route.method} ${item.route.path}`.trim() } : undefined;
|
|
145
|
+
if (item.kind === 'decision') {
|
|
146
|
+
const card = safePlain(item);
|
|
147
|
+
return { element: 'decision', shape: 'card', line: item.status === 'partial' ? 'dashed' : 'solid', title: card?.question || `How ${words(item.name)} decides`, ...(badge ? { badge } : {}), ...(item.status === 'partial' ? { note: 'Partly read' } : {}), ...base };
|
|
148
|
+
}
|
|
149
|
+
const readable = (item.stepsReadable ?? 0) >= 0.5 && item.steps?.length;
|
|
150
|
+
if (!readable) return { element: 'not-read', shape: 'dashed-card', line: 'dashed', title: `What ${words(item.name)} does`, ...(badge ? { badge } : {}), ...base, provenance: 'not-read' };
|
|
151
|
+
return { element: item.route ? 'action' : 'function', shape: 'steps-card', line: 'solid', title: item.route ? `When someone calls ${badge.text}` : `What ${words(item.name)} does`, ...(badge ? { badge } : {}), ...base };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** How to draw one step: its mark, label, color role, and whether to show words or the original code. */
|
|
155
|
+
export function visualForStep(step) {
|
|
156
|
+
const key = step?.restates ? 'restates' : STEP_MARKS[step?.kind] ? step.kind : 'other';
|
|
157
|
+
const m = STEP_MARKS[key];
|
|
158
|
+
return { mark: m.mark, label: m.label, color: m.color, show: m.show, line: m.line || 'solid', text: m.show === 'code' ? step.code ?? step.says : step.says };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function safePlain(item) {
|
|
162
|
+
try { return plainFromReading(item); } catch { return null; }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Thunder Text for one reader item: the same meaning as the picture, in structured words. Decisions use the
|
|
167
|
+
* Thunder Text contract form (.thunder-plain); functions and actions use the steps form. Code that Thunder only
|
|
168
|
+
* restates or cannot read is quoted as code, never paraphrased.
|
|
169
|
+
*/
|
|
170
|
+
export function thunderText(item) {
|
|
171
|
+
const v = visualFor(item);
|
|
172
|
+
if (item.kind === 'error' || item.kind === 'test') return `${v.title}\n`;
|
|
173
|
+
if (item.kind === 'decision') {
|
|
174
|
+
const card = safePlain(item);
|
|
175
|
+
if (card) {
|
|
176
|
+
if (item.doc && !card.why) card.why = item.doc; // the author's reason becomes the contract's Why: line
|
|
177
|
+
return renderPlainContract(card).replace(/\n+Examples\s*$/, '\n'); // a read decision has no examples yet
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const out = [v.title];
|
|
181
|
+
if (item.doc) out.push(` Author's note: "${item.doc}"`);
|
|
182
|
+
if (item.inputs?.length) out.push(` Takes ${item.inputs.map((p) => words(p.name)).join(', ')}`);
|
|
183
|
+
const steps = item.steps || [];
|
|
184
|
+
const lines = (list, depth) => {
|
|
185
|
+
for (const st of list) {
|
|
186
|
+
const s = visualForStep(st);
|
|
187
|
+
const pad = ' '.repeat(depth + 1);
|
|
188
|
+
out.push(s.show === 'code' ? `${pad}- \`${s.text}\` (code, not explained)` : `${pad}- ${s.text}`);
|
|
189
|
+
if (st.children?.length) lines(st.children, depth + 1);
|
|
190
|
+
// Every branch is printed: the other side of an If, each error handler, and what always runs at the end.
|
|
191
|
+
if (st.otherwise?.length) {
|
|
192
|
+
out.push(`${pad} Otherwise:`);
|
|
193
|
+
lines(st.otherwise, depth + 2);
|
|
194
|
+
}
|
|
195
|
+
for (const h of st.handlers || []) { out.push(`${pad} ${h.says}:`); lines(h.steps, depth + 2); }
|
|
196
|
+
if (st.always) { out.push(`${pad} Always, at the end:`); lines(st.always.steps, depth + 2); }
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
if (steps.length) lines(steps, 0);
|
|
200
|
+
else if (item.kind === 'decision' && item.rules?.length) {
|
|
201
|
+
for (const r of item.rules) out.push(` - ${r.result} when ${r.says ?? r.when}`);
|
|
202
|
+
if (item.otherwise) out.push(` - Otherwise, ${item.otherwise.result}`);
|
|
203
|
+
} else out.push(' Not read: see the original code.');
|
|
204
|
+
return `${out.join('\n')}\n`;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The Thunder symbols (V1.1): one shape per kind of thing, drawn as stroke paths on a 44 x 44 grid, so every product
|
|
209
|
+
* draws the same symbol. `paths` are SVG path data; `circles` are [cx, cy, r]; `fill` marks a solid dot. A kid learns
|
|
210
|
+
* the six `beginner` symbols first; the rest appear as they are needed.
|
|
211
|
+
*/
|
|
212
|
+
export const SYMBOLS = {
|
|
213
|
+
app: { name: 'App', says: 'The whole program, as a map.', color: 'structure', paths: ['M6 11 L16 7 L28 11 L38 7 V33 L28 37 L16 33 L6 37 Z', 'M16 7 V33 M28 11 V37'] },
|
|
214
|
+
area: { name: 'Area', says: 'A part of the app that belongs together.', color: 'structure', paths: ['M5 13 H17 L21 17 H39 V35 H5 Z'] },
|
|
215
|
+
file: { name: 'File', says: 'One page of the program.', color: 'structure', paths: ['M11 5 H27 L35 13 V39 H11 Z', 'M27 5 V13 H35', 'M16 22 H30 M16 28 H30 M16 34 H24'] },
|
|
216
|
+
thing: { name: 'Thing', says: 'Something the app knows about. It knows stuff and can do stuff.', color: 'outcome', beginner: true, paths: ['M22 5 L38 13 V31 L22 39 L6 31 V13 Z', 'M6 13 L22 21 L38 13 M22 21 V39'] },
|
|
217
|
+
data: { name: 'Data', says: 'Information: a record of facts, or a list of allowed choices.', color: 'outcome', beginner: true, paths: ['M8 10 C8 6 36 6 36 10 V34 C36 38 8 38 8 34 Z', 'M8 10 C8 14 36 14 36 10', 'M8 22 C8 26 36 26 36 22'] },
|
|
218
|
+
record: { name: 'Record', says: 'A Thing that only remembers facts, like an ID card.', color: 'outcome', group: 'data', paths: ['M9 10 H35 A4 4 0 0 1 39 14 V30 A4 4 0 0 1 35 34 H9 A4 4 0 0 1 5 30 V14 A4 4 0 0 1 9 10 Z', 'M11 29 H19 M24 18 H34 M24 24 H34 M24 30 H30'], circles: [[15, 20, 4]] },
|
|
219
|
+
choices: { name: 'Choices', says: 'Only one of these values is allowed.', color: 'outcome', group: 'data', paths: ['M10 7 H34 A4 4 0 0 1 34 15 H10 A4 4 0 0 1 10 7 Z', 'M10 18 H34 A4 4 0 0 1 34 26 H10 A4 4 0 0 1 10 18 Z', 'M10 29 H34 A4 4 0 0 1 34 37 H10 A4 4 0 0 1 10 29 Z'], circles: [[12, 22, 1.8]], fill: true },
|
|
220
|
+
action: { name: 'Action', says: 'A door into the app: something a person can do.', color: 'fact', beginner: true, paths: ['M11 39 V6 H33 V39', 'M6 39 H38'], circles: [[27, 23, 1.8]], fill: true },
|
|
221
|
+
rule: { name: 'Rule', says: 'A decision: look at some facts, pick one answer.', color: 'question', beginner: true, paths: ['M22 4 L38 20 L22 36 L6 20 Z', 'M22 36 V41 M15 29 L9 37 M29 29 L35 37'] },
|
|
222
|
+
steps: { name: 'Steps', says: 'A how-to: do this, then this, then this.', color: 'structure', beginner: true, paths: ['M10 5 H34 A4 4 0 0 1 38 9 V35 A4 4 0 0 1 34 39 H10 A4 4 0 0 1 6 35 V9 A4 4 0 0 1 10 5 Z', 'M13 14 H14 M19 14 H31 M13 22 H14 M19 22 H31 M13 30 H14 M19 30 H27'] },
|
|
223
|
+
setup: { name: 'Starts with', says: 'What a new Thing has when it is made.', color: 'structure', paths: ['M22 5 V15 M22 29 V39 M5 22 H15 M29 22 H39 M10 10 L16 16 M28 28 L34 34 M34 10 L28 16 M16 28 L10 34'] },
|
|
224
|
+
stop: { name: 'Stop', says: 'Something is wrong, so it stops and says why.', color: 'failure', beginner: true, paths: ['M15 5 H29 L39 15 V29 L29 39 H15 L5 29 V15 Z', 'M16 22 H28'] },
|
|
225
|
+
'not-read': { name: 'Not read yet', says: "Thunder shows the code, because it can't explain it yet.", color: 'unread', dashed: true, paths: ['M11 5 H33 V39 H11 Z', 'M17 22 H27'] },
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
/** What a step does, in a kid's words (model flow nodes carry `does`). Shape first, color second. */
|
|
229
|
+
export const DOES = {
|
|
230
|
+
start: { label: 'Starts', mark: '▶', color: 'fact' },
|
|
231
|
+
find: { label: 'Finds', mark: '⌕', color: 'fact' },
|
|
232
|
+
'keep-only': { label: 'Keeps only', mark: '⏚', color: 'fact' },
|
|
233
|
+
check: { label: 'Checks', mark: '✓', color: 'comparison' },
|
|
234
|
+
decide: { label: 'Asks', mark: '◇', color: 'question' },
|
|
235
|
+
calculate: { label: 'Works out', mark: '=', color: 'fact' },
|
|
236
|
+
save: { label: 'Saves', mark: '⤓', color: 'outcome' },
|
|
237
|
+
send: { label: 'Tells someone', mark: '✉', color: 'outcome' },
|
|
238
|
+
ask: { label: 'Asks another part', mark: '⇄', color: 'outcome' },
|
|
239
|
+
repeat: { label: 'For each', mark: '↻', color: 'structure' },
|
|
240
|
+
answer: { label: 'Gives back', mark: '⇥', color: 'outcome' },
|
|
241
|
+
stop: { label: 'Stops', mark: '■', color: 'failure', symbol: 'stop' },
|
|
242
|
+
do: { label: 'Does', mark: '→', color: 'outcome' },
|
|
243
|
+
code: { label: 'Not read yet', mark: '·', color: 'unread', dashed: true },
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
/** The six concepts a beginner learns first; the model keeps all of SYMBOLS. */
|
|
247
|
+
export const BEGINNER = ['thing', 'action', 'rule', 'steps', 'data', 'stop'];
|
|
248
|
+
|
|
249
|
+
/** The whole grammar in one object, for views that want to render a legend or validate themselves against it. */
|
|
250
|
+
export const THUNDER_VISUAL = { schema: VISUAL_SCHEMA, principle: PRINCIPLE, forms: FORMS, zoom: ZOOM, colors: COLORS, lines: LINES, provenance: PROVENANCE, steps: STEP_MARKS, elements: ELEMENTS, languages: LANGUAGES, rules: RULES, symbols: SYMBOLS, does: DOES, beginner: BEGINNER };
|
|
251
|
+
|
|
252
|
+
// ── Thunder Text colors: each word's role, decided by the compiler so every view colors it the same way ──────
|
|
253
|
+
|
|
254
|
+
const STRUCTURE_WORDS = /^(?:Ask:|Yes:|No:|Otherwise:|Otherwise,|Always, at the end:|For each:|When done:|You give it:|You get back:|Takes|Author's note:|It knows|It can|One of:|We need|Examples|Why:|When someone calls|What|Thing|Record|Choices|Area|File|App|Not read)(?=\s|$)/;
|
|
255
|
+
const COMPARISON_RE = /\b(?:is at least|is at most|is less than|is more than|is not in|is in|is not|at least|at most|less than|more than|under|over|exactly|whether|is set|is not set|is empty|is not empty|has no|has|is)\b/;
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Split one line of Thunder Text into tokens tagged with a COLORS role, so views color Thunder Text like an IDE
|
|
259
|
+
* without guessing: { text, role } where role is a COLORS key, or null for plain text. Line numbers ("(line 12)")
|
|
260
|
+
* are role 'unread' (quiet). Deterministic; whitespace is preserved, so joining the texts gives the line back.
|
|
261
|
+
*/
|
|
262
|
+
export function thunderTokens(line) {
|
|
263
|
+
const out = [];
|
|
264
|
+
const push = (text, role = null) => { if (text) out.push({ text, role }); };
|
|
265
|
+
let rest = String(line);
|
|
266
|
+
const lead = rest.match(/^\s*(?:- )?/)[0];
|
|
267
|
+
push(lead.includes('-') ? lead.slice(0, lead.indexOf('-')) : lead, null);
|
|
268
|
+
if (lead.includes('-')) push('- ', 'structure');
|
|
269
|
+
rest = rest.slice(lead.length);
|
|
270
|
+
const lineNo = rest.match(/\s+\(line \d+\)\s*$/);
|
|
271
|
+
const tail = lineNo ? lineNo[0] : '';
|
|
272
|
+
if (lineNo) rest = rest.slice(0, rest.length - tail.length);
|
|
273
|
+
// Whole-line kinds first.
|
|
274
|
+
let m;
|
|
275
|
+
if ((m = rest.match(/^(Stop|Fails with)(:?\s*)([\w.]*)(:?\s*)(.*)$/)) && (/^Stop/.test(rest) || /^Fails with/.test(rest))) {
|
|
276
|
+
push(m[1], 'failure'); push(m[2]); push(m[3], 'failure'); push(m[4]); words(m[5]);
|
|
277
|
+
} else if ((m = rest.match(/^(Answer:|Gives back|Returns)(\s*)(.*)$/))) {
|
|
278
|
+
push(m[1], 'structure'); push(m[2]); push(m[3], 'outcome');
|
|
279
|
+
} else if ((m = rest.match(/^(Ask:)(\s*)(.*)$/))) {
|
|
280
|
+
push(m[1], 'structure'); push(m[2]); words(m[3], 'question');
|
|
281
|
+
} else if ((m = rest.match(/^`(.*)`(.*)$/))) {
|
|
282
|
+
push(`\`${m[1]}\``, 'unread'); push(m[2], 'unread');
|
|
283
|
+
} else {
|
|
284
|
+
const s = rest.match(STRUCTURE_WORDS);
|
|
285
|
+
if (s) { push(s[0], 'structure'); words(rest.slice(s[0].length)); } else words(rest);
|
|
286
|
+
}
|
|
287
|
+
push(tail, 'unread');
|
|
288
|
+
return out;
|
|
289
|
+
|
|
290
|
+
// Inside a phrase: comparisons pink, numbers and money orange, quoted text lime, structure words violet.
|
|
291
|
+
function words(text, base = null) {
|
|
292
|
+
const re = /("[^"]*")|(\$?-?\d[\d,]*(?:\.\d+)?%?)|\b(and|or|not|if|otherwise|for each|in|from|to|of)\b|\b(is at least|is at most|is less than|is more than|is not in|is in|is not set|is set|is not empty|is empty|is not|at least|at most|less than|more than|exactly|whether|has no)\b/g;
|
|
293
|
+
let last = 0, x;
|
|
294
|
+
while ((x = re.exec(text))) {
|
|
295
|
+
push(text.slice(last, x.index), base);
|
|
296
|
+
if (x[1]) push(x[1], 'name');
|
|
297
|
+
else if (x[2]) push(x[2], 'amount');
|
|
298
|
+
else if (x[3]) push(x[3], 'structure');
|
|
299
|
+
else push(x[4], 'comparison');
|
|
300
|
+
last = x.index + x[0].length;
|
|
301
|
+
}
|
|
302
|
+
push(text.slice(last), base);
|
|
303
|
+
}
|
|
304
|
+
}
|
package/src/write.d.mts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export const WRITE_SCHEMA: 'thunder-write-v1';
|
|
2
|
+
export interface ChangedCase { inputs: Record<string, string | number | boolean>; before: string; after: string }
|
|
3
|
+
export interface ChangedCases { checked: number; changed: ChangedCase[]; note: string }
|
|
4
|
+
export interface WriteChange { line: number; column: number; before: string; after: string }
|
|
5
|
+
export function writeRule(args: {
|
|
6
|
+
source: string; language?: string; file?: string; decision: string; line?: number | null;
|
|
7
|
+
/** 1-based rule number, or 'otherwise' for the fallback answer. */
|
|
8
|
+
rule: number | 'otherwise';
|
|
9
|
+
/** The rule's new condition in Thunder form (amount < 75). Only numbers, comparisons, and text may change. */
|
|
10
|
+
when?: string | null;
|
|
11
|
+
/** The rule's new answer (Review). */
|
|
12
|
+
answer?: string | null;
|
|
13
|
+
}):
|
|
14
|
+
| { schema: 'thunder-write-v1'; ok: true; source: string; problems: []; decision: string; rule: number | 'otherwise'; change: WriteChange[]; before: string; after: string; cases: ChangedCases }
|
|
15
|
+
| { schema: 'thunder-write-v1'; ok: false; source: string; problems: string[] };
|
|
16
|
+
export function changedCases(before: unknown, after: unknown): ChangedCases;
|
|
17
|
+
export type RulePart =
|
|
18
|
+
| { kind: 'number'; value: number }
|
|
19
|
+
| { kind: 'text'; value: string }
|
|
20
|
+
| { kind: 'comparison'; value: '<' | '<=' | '>' | '>=' | '==' | '!='; words: string }
|
|
21
|
+
| { kind: 'fixed'; value: string; words: string };
|
|
22
|
+
export const COMPARISON_CHOICES: Array<{ op: '<' | '<=' | '>' | '>=' | '==' | '!='; words: string }>;
|
|
23
|
+
export function ruleParts(when: string): RulePart[];
|
|
24
|
+
export function joinRuleParts(parts: RulePart[]): string;
|
package/src/write.mjs
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// Thunder write: change a rule in the Thunder picture and only the matching code changes.
|
|
2
|
+
//
|
|
3
|
+
// A recovered decision reads "if amount is at most 100, the answer is Approve". Thunder write lets a person
|
|
4
|
+
// change a number (100 -> 75), a comparison (at most -> under), a text value ("gold" -> "platinum"), or an
|
|
5
|
+
// answer (Approve -> Review), and writes exactly those characters back into the original file, keeping the
|
|
6
|
+
// file's own spelling (=== stays ===, 100.0 stays a decimal, 100m keeps its suffix, quotes keep their style).
|
|
7
|
+
//
|
|
8
|
+
// Every write is checked by reading the file again: the edited rule must now read exactly as intended, and
|
|
9
|
+
// every other rule, answer, and function in the file must read exactly as before. Otherwise nothing changes.
|
|
10
|
+
// It also runs the old and the new rule on boundary inputs and lists the cases whose answer changes.
|
|
11
|
+
//
|
|
12
|
+
// Deterministic and browser-safe. It edits text only; it never runs the code it edits.
|
|
13
|
+
import { readCode, sayCondition } from './read.mjs';
|
|
14
|
+
import { tokenize } from './expr.mjs';
|
|
15
|
+
import { recoverModel } from './promote.mjs';
|
|
16
|
+
|
|
17
|
+
export const WRITE_SCHEMA = 'thunder-write-v1';
|
|
18
|
+
|
|
19
|
+
const CMP = new Set(['<', '<=', '>', '>=', '==', '!=']);
|
|
20
|
+
const editable = (t) => t.t === 'num' || t.t === 'str' || (t.t === 'op' && CMP.has(t.v));
|
|
21
|
+
const category = (t) => (t.t === 'op' ? 'cmp' : t.t);
|
|
22
|
+
const sameTok = (a, b) => a.t === b.t && a.v === b.v;
|
|
23
|
+
const normWhen = (w) => tokenize(w).map((t) => (t.t === 'str' ? JSON.stringify(t.v) : String(t.v))).join(' ');
|
|
24
|
+
|
|
25
|
+
const COMMENT = { python: ['#'], ruby: ['#'], php: ['#', '//', '/*'] };
|
|
26
|
+
const commentStarts = (language) => COMMENT[language] || ['//', '/*'];
|
|
27
|
+
|
|
28
|
+
/** Numbers, comparison operators, and text literals in a slice of the original file, with exact offsets. */
|
|
29
|
+
function scanSource(source, from, to, language) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const starts = commentStarts(language);
|
|
32
|
+
let i = from;
|
|
33
|
+
while (i < to) {
|
|
34
|
+
const c = source[i];
|
|
35
|
+
if (starts.some((s) => source.startsWith(s, i))) {
|
|
36
|
+
if (source.startsWith('/*', i)) { const j = source.indexOf('*/', i + 2); i = j < 0 ? to : j + 2; }
|
|
37
|
+
else { const j = source.indexOf('\n', i); i = j < 0 ? to : j; }
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
41
|
+
let j = i + 1;
|
|
42
|
+
while (j < source.length && source[j] !== c && source[j] !== '\n') j += source[j] === '\\' ? 2 : 1;
|
|
43
|
+
if (source[j] === c) out.push({ t: 'str', v: source.slice(i + 1, j), start: i, end: j + 1, raw: source.slice(i, j + 1), quote: c });
|
|
44
|
+
i = j + 1;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (/[A-Za-z_$]/.test(c)) { // identifiers (and digits inside them) are not values
|
|
48
|
+
let j = i;
|
|
49
|
+
while (j < to && /[A-Za-z0-9_$]/.test(source[j])) j++;
|
|
50
|
+
out.push({ t: 'id', v: source.slice(i, j), start: i, end: j });
|
|
51
|
+
i = j;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (/[0-9]/.test(c)) {
|
|
55
|
+
const m = source.slice(i, to).match(/^[0-9][0-9_]*(\.[0-9][0-9_]*)?([eE][+-]?[0-9]+)?(f64|f32|i32|i64|u32|u64|[fFdDmMlLuU]{0,2})/);
|
|
56
|
+
const raw = m[0];
|
|
57
|
+
const suffix = m[3] || '';
|
|
58
|
+
out.push({ t: 'num', v: Number(raw.slice(0, raw.length - suffix.length).replace(/_/g, '')), start: i, end: i + raw.length, raw, suffix, decimal: !!m[1] });
|
|
59
|
+
i += raw.length;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const op = ['===', '!==', '<=>', '==', '!=', '<=', '>=', '->', '=>', '<<', '>>', '<-', '<', '>'].find((o) => source.startsWith(o, i));
|
|
63
|
+
if (op) {
|
|
64
|
+
if (!['<=>', '->', '=>', '<<', '>>', '<-'].includes(op)) out.push({ t: 'op', v: op === '===' ? '==' : op === '!==' ? '!=' : op, start: i, end: i + op.length, raw: op });
|
|
65
|
+
i += op.length;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
i++;
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const matches = (src, t) => src.t === t.t && (t.t === 'num' ? src.v === t.v : src.v === t.v);
|
|
74
|
+
|
|
75
|
+
/** Find the source tokens that are the rule's numbers, comparisons, and text, in order. */
|
|
76
|
+
function locate(srcToks, wanted) {
|
|
77
|
+
const found = [];
|
|
78
|
+
let k = 0;
|
|
79
|
+
for (const s of srcToks) {
|
|
80
|
+
if (k < wanted.length && matches(s, wanted[k])) { found.push(s); k++; }
|
|
81
|
+
}
|
|
82
|
+
return k === wanted.length ? found : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function spell(srcTok, next) {
|
|
86
|
+
if (next.t === 'op') {
|
|
87
|
+
if (srcTok.raw === '===' || srcTok.raw === '!==') return next.v === '==' ? '===' : next.v === '!=' ? '!==' : next.v;
|
|
88
|
+
return next.v;
|
|
89
|
+
}
|
|
90
|
+
if (next.t === 'num') {
|
|
91
|
+
let s = String(next.v);
|
|
92
|
+
if (srcTok.decimal && Number.isInteger(next.v)) s += '.0';
|
|
93
|
+
return s + srcTok.suffix;
|
|
94
|
+
}
|
|
95
|
+
return srcTok.quote + next.v + srcTok.quote;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const lineStartsOf = (source) => { const out = [0]; for (let i = 0; i < source.length; i++) if (source[i] === '\n') out.push(i + 1); return out; };
|
|
99
|
+
|
|
100
|
+
function findDecision(reading, name, line) {
|
|
101
|
+
const ds = reading.items.filter((i) => i.kind === 'decision' && i.name === name);
|
|
102
|
+
if (!ds.length) return null;
|
|
103
|
+
if (line == null) return ds[0];
|
|
104
|
+
return ds.reduce((best, d) => (Math.abs(d.line - line) < Math.abs(best.line - line) ? d : best));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The character range of a rule (its condition line through the line before the next rule or the fallback).
|
|
108
|
+
function ruleRegion(source, decision, index) {
|
|
109
|
+
const starts = lineStartsOf(source);
|
|
110
|
+
const lines = [...decision.rules.map((r) => r.line), decision.otherwise.line];
|
|
111
|
+
const first = index === 'otherwise' ? decision.otherwise.line : decision.rules[index].line;
|
|
112
|
+
const later = lines.filter((l) => l > first);
|
|
113
|
+
const last = index === 'otherwise' ? first : Math.max(first, (later.length ? Math.min(...later) : first + 1) - 1);
|
|
114
|
+
return [starts[first - 1] ?? source.length, starts[last] != null ? starts[last] - 1 : source.length];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const view = (it) => JSON.stringify({ kind: it.kind, name: it.name, says: it.says, thunder: it.thunder, rules: it.rules?.map((r) => [r.when, r.result]), otherwise: it.otherwise?.result, guards: it.guards?.map((g) => g.says ?? g.when) });
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Change one rule of a recovered decision and write it back to the original code.
|
|
121
|
+
*
|
|
122
|
+
* rule: 1-based rule number, or 'otherwise' for the fallback answer.
|
|
123
|
+
* when: the rule's new condition, in Thunder form (amount < 75). Numbers, comparisons, and text may change.
|
|
124
|
+
* answer: the rule's new answer (Review).
|
|
125
|
+
*
|
|
126
|
+
* Returns { schema, ok, source, problems, change, before, after, cases }. When ok is false, `source` is the
|
|
127
|
+
* original, untouched, and `problems` says why in plain words.
|
|
128
|
+
*/
|
|
129
|
+
export function writeRule({ source, language, file = '', decision: name, line = null, rule, when = null, answer = null }) {
|
|
130
|
+
const fail = (...problems) => ({ schema: WRITE_SCHEMA, ok: false, source, problems });
|
|
131
|
+
if (when == null && answer == null) return fail('Say what to change: a new condition (when) or a new answer.');
|
|
132
|
+
const reading = readCode(source, { language, file });
|
|
133
|
+
const lang = reading.language;
|
|
134
|
+
const d = findDecision(reading, name, line);
|
|
135
|
+
if (!d) return fail(`No decision named ${name} was found. Thunder write changes decisions: functions that choose between fixed answers.`);
|
|
136
|
+
const index = rule === 'otherwise' ? 'otherwise' : Number(rule) - 1;
|
|
137
|
+
if (index !== 'otherwise' && !(Number.isInteger(index) && d.rules[index])) return fail(`${name} has ${d.rules.length} rule${d.rules.length === 1 ? '' : 's'}; there is no rule ${rule}.`);
|
|
138
|
+
if (index === 'otherwise' && when != null) return fail('The fallback answer has no condition to change. Change its answer instead.');
|
|
139
|
+
const target = index === 'otherwise' ? d.otherwise : d.rules[index];
|
|
140
|
+
const [from, to] = ruleRegion(source, d, index);
|
|
141
|
+
const srcToks = scanSource(source, from, to, lang);
|
|
142
|
+
const edits = []; // { start, end, text }
|
|
143
|
+
|
|
144
|
+
// 1. The condition: only numbers, comparisons, and text values may change; the shape must stay the same.
|
|
145
|
+
let newWhen = target.when;
|
|
146
|
+
if (when != null) {
|
|
147
|
+
let oldT, newT;
|
|
148
|
+
try { oldT = tokenize(target.when); newT = tokenize(when); } catch (e) { return fail(`The new condition could not be read: ${e.message}`); }
|
|
149
|
+
const structural = oldT.length !== newT.length || oldT.some((t, i) => !sameTok(t, newT[i]) && !(editable(t) && editable(newT[i]) && category(t) === category(newT[i])));
|
|
150
|
+
if (structural) return fail(`Thunder write can change a number, a comparison, or a text value in a rule. "${when}" also changes the rule's shape (names, and/or, or parentheses). Use Propose rule change for that.`);
|
|
151
|
+
const wanted = oldT.filter(editable);
|
|
152
|
+
const found = locate(srcToks, wanted);
|
|
153
|
+
if (!found) return fail(`The values in "${sayCondition(target.when)}" could not be found exactly in the code at line ${target.line}, so it is not safe to write them back.`);
|
|
154
|
+
let k = 0;
|
|
155
|
+
oldT.forEach((t, i) => {
|
|
156
|
+
if (!editable(t)) return;
|
|
157
|
+
const s = found[k++];
|
|
158
|
+
const next = newT[i];
|
|
159
|
+
if (sameTok(t, next)) return;
|
|
160
|
+
if (next.t === 'str' && (next.v.includes(s.quote) || next.v.includes('\\'))) return edits.push({ bad: `The text ${JSON.stringify(next.v)} contains a quote or backslash; write it in the code directly.` });
|
|
161
|
+
edits.push({ start: s.start, end: s.end, text: spell(s, next), was: s.raw });
|
|
162
|
+
});
|
|
163
|
+
newWhen = normWhen(when);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// 2. The answer: reuse a spelling this function already returns, or change the text of a string answer.
|
|
167
|
+
if (answer != null && answer !== target.result) {
|
|
168
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(answer)) return fail(`The answer must be a name such as Approve or Review; "${answer}" is not.`);
|
|
169
|
+
const reads = (t, result) => (t.t === 'str' && t.v === result) || (t.t === 'id' && t.v === result);
|
|
170
|
+
const sites = srcToks.filter((t) => reads(t, target.result));
|
|
171
|
+
if (sites.length !== 1) return fail(`The answer ${target.result} could not be found exactly once near line ${target.line}, so it is not safe to change.`);
|
|
172
|
+
const site = sites[0];
|
|
173
|
+
// An answer spelled elsewhere in this decision, for example Decision.REVIEW or "Review".
|
|
174
|
+
const others = [...d.rules.map((_, i) => i), 'otherwise'].filter((i) => i !== index && (i === 'otherwise' ? d.otherwise : d.rules[i]).result === answer);
|
|
175
|
+
let text = null;
|
|
176
|
+
for (const i of others) {
|
|
177
|
+
const [a, b] = ruleRegion(source, d, i);
|
|
178
|
+
const t = scanSource(source, a, b, lang).find((x) => reads(x, answer));
|
|
179
|
+
if (t && t.t === site.t) { text = t.raw ?? t.v; break; }
|
|
180
|
+
}
|
|
181
|
+
if (text == null && site.t === 'str') text = site.quote + answer + site.quote;
|
|
182
|
+
if (text == null) return fail(`${name} does not return ${answer} anywhere yet, and its answers are code names (such as ${site.v}), so Thunder write will not invent one. Add ${answer} in the code first, or use Propose rule change.`);
|
|
183
|
+
edits.push({ start: site.start, end: site.end, text, was: site.raw ?? site.v });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const bad = edits.find((e) => e.bad);
|
|
187
|
+
if (bad) return fail(bad.bad);
|
|
188
|
+
const real = edits.filter((e) => source.slice(e.start, e.end) !== e.text).sort((a, b) => b.start - a.start);
|
|
189
|
+
if (!real.length) return fail('Nothing would change: the rule already reads that way.');
|
|
190
|
+
let next = source;
|
|
191
|
+
for (const e of real) next = next.slice(0, e.start) + e.text + next.slice(e.end);
|
|
192
|
+
|
|
193
|
+
// 3. Verify by reading the file again.
|
|
194
|
+
const problems = [];
|
|
195
|
+
let after;
|
|
196
|
+
try { after = readCode(next, { language: lang, file }); } catch (e) { return fail(`The changed file could not be read: ${e.message}`); }
|
|
197
|
+
const d2 = findDecision(after, name, d.line);
|
|
198
|
+
if (!d2) return fail(`${name} is no longer read as a decision after the change.`);
|
|
199
|
+
const wantResult = answer ?? target.result;
|
|
200
|
+
if (d2.rules.length !== d.rules.length) problems.push('The number of rules changed.');
|
|
201
|
+
d.rules.forEach((r, i) => {
|
|
202
|
+
const r2 = d2.rules[i];
|
|
203
|
+
if (!r2) return;
|
|
204
|
+
const w = i === index ? newWhen : normWhen(r.when);
|
|
205
|
+
const res = i === index ? wantResult : r.result;
|
|
206
|
+
if (normWhen(r2.when) !== w) problems.push(`Rule ${i + 1} reads "${sayCondition(r2.when)}" after the change, not "${sayCondition(w)}".`);
|
|
207
|
+
if (r2.result !== res) problems.push(`Rule ${i + 1} answers ${r2.result} after the change, not ${res}.`);
|
|
208
|
+
});
|
|
209
|
+
const wantOtherwise = index === 'otherwise' ? wantResult : d.otherwise.result;
|
|
210
|
+
if (d2.otherwise?.result !== wantOtherwise) problems.push(`The fallback answers ${d2.otherwise?.result} after the change, not ${wantOtherwise}.`);
|
|
211
|
+
const others = reading.items.filter((i) => i !== d), others2 = after.items.filter((i) => i !== d2);
|
|
212
|
+
if (others.length !== others2.length) problems.push('Another part of the file reads differently after the change.');
|
|
213
|
+
else others.forEach((o, i) => { if (view(o) !== view(others2[i])) problems.push(`${o.name} (line ${o.line}) reads differently after the change.`); });
|
|
214
|
+
if (problems.length) return fail(...problems);
|
|
215
|
+
|
|
216
|
+
const starts = lineStartsOf(source);
|
|
217
|
+
const lineOf = (off) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const m = (lo + hi + 1) >> 1; if (starts[m] <= off) lo = m; else hi = m - 1; } return lo + 1; };
|
|
218
|
+
const change = real.slice().reverse().map((e) => ({ line: lineOf(e.start), column: e.start - starts[lineOf(e.start) - 1] + 1, before: e.was, after: e.text }));
|
|
219
|
+
const label = (r) => (r === 'otherwise' ? 'Otherwise' : `If ${sayCondition(r.when)}`);
|
|
220
|
+
const beforeRule = index === 'otherwise' ? `Otherwise, the answer is ${target.result}` : `${label(target)}, the answer is ${target.result}`;
|
|
221
|
+
const afterRule = index === 'otherwise' ? `Otherwise, the answer is ${wantResult}` : `If ${sayCondition(newWhen)}, the answer is ${wantResult}`;
|
|
222
|
+
return { schema: WRITE_SCHEMA, ok: true, source: next, problems: [], decision: name, rule: index === 'otherwise' ? 'otherwise' : index + 1, change, before: beforeRule, after: afterRule, cases: changedCases(d, d2) };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Run the old and the new decision on the same boundary inputs (both sides of every threshold, every text
|
|
227
|
+
* value) and list the inputs whose answer changes. This covers the inputs checked, not every possible input.
|
|
228
|
+
*/
|
|
229
|
+
export function changedCases(before, after) {
|
|
230
|
+
const a = recoverModel(before, { extraConditions: after.rules.map((r) => r.when) });
|
|
231
|
+
const b = recoverModel(after, { extraConditions: before.rules.map((r) => r.when) });
|
|
232
|
+
if (!a.ok || !b.ok) return { checked: 0, changed: [], note: `The cases could not be compared: ${(a.ok ? b : a).reason}` };
|
|
233
|
+
const lookup = new Map(b.all.map((x) => [JSON.stringify(x.a), x.r.result]));
|
|
234
|
+
const changed = [];
|
|
235
|
+
for (const x of a.all) {
|
|
236
|
+
const next = lookup.get(JSON.stringify(x.a));
|
|
237
|
+
if (next !== undefined && next !== x.r.result) changed.push({ inputs: x.a, before: x.r.result, after: next });
|
|
238
|
+
}
|
|
239
|
+
return { checked: a.all.length, changed, note: `Checked ${a.all.length} boundary input${a.all.length === 1 ? '' : 's'}; ${changed.length} now get${changed.length === 1 ? 's' : ''} a different answer. These are the values on each side of every limit, not every possible input.` };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const CMP_WORDS = { '<=': 'at most', '<': 'less than', '>=': 'at least', '>': 'more than', '==': 'is', '!=': 'is not' };
|
|
243
|
+
/** The comparisons a person can choose between, in plain words. */
|
|
244
|
+
export const COMPARISON_CHOICES = Object.entries(CMP_WORDS).map(([op, words]) => ({ op, words }));
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* A rule's condition split into the parts a person sees: names and words stay fixed; numbers, comparisons, and
|
|
248
|
+
* text values can change. Joining the parts back with `joinRuleParts` gives a condition `writeRule` accepts.
|
|
249
|
+
*/
|
|
250
|
+
export function ruleParts(when) {
|
|
251
|
+
return tokenize(when).map((t) => {
|
|
252
|
+
if (t.t === 'num') return { kind: 'number', value: t.v };
|
|
253
|
+
if (t.t === 'str') return { kind: 'text', value: t.v };
|
|
254
|
+
if (t.t === 'op' && CMP.has(t.v)) return { kind: 'comparison', value: t.v, words: CMP_WORDS[t.v] };
|
|
255
|
+
if (t.t === 'bool') return { kind: 'fixed', value: String(t.v), words: String(t.v) };
|
|
256
|
+
if (t.t === 'kw') return { kind: 'fixed', value: t.v, words: t.v };
|
|
257
|
+
return { kind: 'fixed', value: String(t.v), words: String(t.v) };
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function joinRuleParts(parts) {
|
|
262
|
+
return parts.map((p) => (p.kind === 'text' ? JSON.stringify(String(p.value)) : String(p.value))).join(' ').replace(/\( /g, '(').replace(/ \)/g, ')');
|
|
263
|
+
}
|