@skillstech/thunderlang 1.3.0 → 1.4.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 +59 -0
- package/dist/core.cjs +4751 -1067
- package/dist/index.cjs +3676 -189
- package/dist/learn.cjs +3161 -163
- package/package.json +6 -2
- package/src/cli-home.mjs +1 -1
- package/src/cli.mjs +23 -0
- package/src/core.d.ts +41 -0
- package/src/core.mjs +13 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +4 -1
- package/src/flow/access.mjs +1451 -0
- package/src/flow/ts-parse.mjs +772 -0
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/libraries.mjs +22 -1
- package/src/model.mjs +22 -1
- package/src/passport-cli.mjs +101 -0
- package/src/passport-fs.d.mts +9 -0
- package/src/passport-fs.mjs +180 -0
- package/src/passport.d.mts +46 -0
- package/src/passport.mjs +255 -0
- package/src/program.d.mts +31 -0
- package/src/program.mjs +14 -0
- package/src/read.mjs +37 -1
- package/src/review.mjs +31 -3
- package/src/say-less.mjs +16 -2
- package/src/steps.mjs +13 -1
- package/src/things-langs.mjs +20 -3
- package/src/write-across-cli.mjs +143 -0
- package/src/write-across.mjs +168 -0
package/src/passport.mjs
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// Thunder Software Passport (thunder-passport-v1): a portable evidence record for a feature or a change.
|
|
2
|
+
//
|
|
3
|
+
// It is not a certificate that the code is correct. It is an evidence manifest: every claim names its basis (a
|
|
4
|
+
// command and its exit code, or a source location), what it does not cover, and the exact files (by content hash)
|
|
5
|
+
// it depended on. When one of those files changes, the claim is stale, and checkPassport says so.
|
|
6
|
+
//
|
|
7
|
+
// This file is the pure, browser-safe half: it assembles a passport from what was read and run, renders it, and
|
|
8
|
+
// checks it against current file contents. Reading folders, git, and running commands is in passport-fs.mjs.
|
|
9
|
+
import { sha256 } from './hash.mjs';
|
|
10
|
+
import { thunderModel, modelText } from './model.mjs';
|
|
11
|
+
import { buildTrace, isTestFile } from './trace.mjs';
|
|
12
|
+
import { thunderReview } from './review.mjs';
|
|
13
|
+
|
|
14
|
+
export const PASSPORT_SCHEMA = 'thunder-passport-v1';
|
|
15
|
+
|
|
16
|
+
/** What nothing in a passport establishes unless an evidence item says otherwise. Always listed. */
|
|
17
|
+
export const ALWAYS_NOT_VERIFIED = [
|
|
18
|
+
'Deployment: how it is configured and run in a real environment.',
|
|
19
|
+
'External services: real providers, their answers, and their outages (tests use what the code was given).',
|
|
20
|
+
'More than one process or machine: anything kept in memory is not shared between copies.',
|
|
21
|
+
'Load and timing: behavior under many requests at once, beyond what the tests ran.',
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
const MAX_BEHAVIOR = 60;
|
|
25
|
+
const fileHash = (source) => sha256(String(source)); // 'sha256:<hex>'
|
|
26
|
+
|
|
27
|
+
const EFFECT = { find: 'reads', save: 'writes', send: 'sends', ask: 'calls another part', redirect: 'sends the person to' };
|
|
28
|
+
function effectKind(node) {
|
|
29
|
+
if (node.does === 'save' && /^(Deletes|Removes)\b/.test(node.text || '')) return 'deletes';
|
|
30
|
+
return EFFECT[node.does] ?? null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Assemble a passport from parts already read (and, for a change, their base versions), runs already made, and a
|
|
35
|
+
* purpose. Pure and deterministic: the same inputs (with the same `builtAt`) give the same passport.
|
|
36
|
+
* parts: [{ name, path, sha?, dirty?, files: [{ path, source, manifest? }], packages?: [{ name, version?, from }],
|
|
37
|
+
* changes?: [{ file, status: 'added'|'changed'|'removed', ranges: [[a, b]…], old?: string|null }] }]
|
|
38
|
+
* change: { base, head } when this is a change (each part's `changes` then say what changed); null for a snapshot
|
|
39
|
+
* runs: [{ command, part: name|null, cwd, exitCode, output }] (output: what it printed, both streams)
|
|
40
|
+
* purpose: { text, source } or null
|
|
41
|
+
* extra: evidence items supplied by other tools (an access-flow result, a conformance run…), already in shape
|
|
42
|
+
*/
|
|
43
|
+
export function assemblePassport({ parts, change = null, runs = [], purpose = null, extra = [], builtAt = new Date().toISOString(), thunder = null }) {
|
|
44
|
+
const hashes = new Map(); // `${part}/${file}` -> { part, file, sha256 }
|
|
45
|
+
for (const p of parts) for (const f of p.files) hashes.set(`${p.name}/${f.path}`, { part: p.name, file: f.path, sha256: fileHash(f.source) });
|
|
46
|
+
const inputOf = (part, file) => hashes.get(`${part}/${file}`) ?? { part, file, sha256: null };
|
|
47
|
+
const partInputs = (name) => [...hashes.values()].filter((h) => h.part === name);
|
|
48
|
+
|
|
49
|
+
const models = new Map(parts.map((p) => [p.name, thunderModel(p.files.filter((f) => !f.manifest), { name: p.name })]));
|
|
50
|
+
const changed = (p, file) => (p.changes ?? []).find((c) => c.file === file);
|
|
51
|
+
|
|
52
|
+
// Behavior: in a change, the actions and rules whose lines the change touched (or in an added file); in a
|
|
53
|
+
// snapshot, every action and rule. Test code is evidence, not behavior.
|
|
54
|
+
const behavior = [], effects = [], notRead = [];
|
|
55
|
+
for (const p of parts) {
|
|
56
|
+
const model = models.get(p.name);
|
|
57
|
+
for (const m of model.members) {
|
|
58
|
+
if (m.kind === 'setup' || isTestFile(m.file)) continue;
|
|
59
|
+
const c = change ? changed(p, m.file) : null;
|
|
60
|
+
if (change && !(c && (c.status === 'added' || c.ranges.some(([a, b]) => a <= m.lines[1] && b >= m.lines[0])))) continue;
|
|
61
|
+
const item = { part: p.name, file: m.file, lines: m.lines, name: m.label, kind: m.kind, ...(c ? { change: c.status } : {}) };
|
|
62
|
+
if (m.kind === 'not-read') { notRead.push({ part: p.name, file: m.file, line: m.lines[0], what: `${m.label}: Thunder does not read this yet` }); continue; }
|
|
63
|
+
let text = '';
|
|
64
|
+
try { text = modelText(model, m.id).trim(); } catch { text = ''; }
|
|
65
|
+
behavior.push({ ...item, text });
|
|
66
|
+
for (const nd of m.flow?.nodes ?? []) {
|
|
67
|
+
const kind = effectKind(nd);
|
|
68
|
+
if (kind) effects.push({ part: p.name, file: m.file, line: nd.line ?? m.lines[0], in: m.label, kind, says: nd.text, how: 'detected', basis: 'read from code; nothing was run' });
|
|
69
|
+
if (nd.does === 'code' && nd.line != null) notRead.push({ part: p.name, file: m.file, line: nd.line, what: `shown as code: ${String(nd.text).slice(0, 100)}` });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const u of model.unknowns ?? []) {
|
|
73
|
+
if (isTestFile(u.file)) continue;
|
|
74
|
+
const c = change ? changed(p, u.file) : null;
|
|
75
|
+
if (change && !(c && (c.status === 'added' || c.ranges.some(([a, b]) => u.line >= a && u.line <= b)))) continue;
|
|
76
|
+
const owner = model.members.find((m) => m.file === u.file && m.lines[0] <= u.line && m.lines[1] >= u.line);
|
|
77
|
+
notRead.push({ part: p.name, file: u.file, line: u.line, what: owner ? `${owner.label}: ${u.why}` : u.why });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const order = (a, b) => `${a.part}/${a.file}`.localeCompare(`${b.part}/${b.file}`) || ((a.lines?.[0] ?? a.line ?? 0) - (b.lines?.[0] ?? b.line ?? 0));
|
|
81
|
+
behavior.sort(order); effects.sort(order); notRead.sort(order);
|
|
82
|
+
{ const seen = new Set(); notRead.splice(0, notRead.length, ...notRead.filter((x) => { const k = `${x.part}/${x.file}:${x.line}`; if (seen.has(k)) return false; seen.add(k); return true; })); }
|
|
83
|
+
const shownBehavior = behavior.slice(0, MAX_BEHAVIOR);
|
|
84
|
+
|
|
85
|
+
// Dependencies: every file read (with its hash), the links between the parts, packages, and services called.
|
|
86
|
+
const trace = buildTrace(parts.map((p) => ({ name: p.name, sha: p.sha ?? null, dirty: !!p.dirty, files: p.files.filter((f) => !f.manifest) })));
|
|
87
|
+
const links = trace.links.map((l) => ({ kind: l.kind, says: l.kind === 'http' ? `${l.from.repo} calls ${l.to.repo}: ${l.method} ${l.path} (handled by ${l.to.label ?? l.route})` : `${l.from.repo} publishes ${l.event}, and ${l.to.repo} listens`, from: l.from.cite, to: l.to.cite }));
|
|
88
|
+
const services = [];
|
|
89
|
+
for (const r of trace.repos) for (const q of r.requests ?? []) if (q.base && q.base !== 'this app') services.push({ part: r.name, calls: `${q.method} ${q.base}${q.path}`, at: `${r.name}:${q.file}:${q.line}` });
|
|
90
|
+
|
|
91
|
+
// Evidence.
|
|
92
|
+
const evidence = [];
|
|
93
|
+
const add = (x) => evidence.push({ id: `e${evidence.length + 1}`, ...x });
|
|
94
|
+
for (const r of runs) {
|
|
95
|
+
const passed = r.exitCode === 0;
|
|
96
|
+
const tail = String(r.output ?? '').replace(/\s+$/, '').split('\n').slice(-12).join('\n');
|
|
97
|
+
add({
|
|
98
|
+
kind: 'test-run', status: passed ? 'passed' : 'failed',
|
|
99
|
+
claim: `\`${r.command}\`${r.part ? ` in ${r.part}` : ''} exited with ${r.exitCode}${passed ? '' : ' (a failure)'}.`,
|
|
100
|
+
basis: { command: r.command, cwd: r.cwd, exitCode: r.exitCode, outputDigest: fileHash(r.output ?? ''), outputTail: tail },
|
|
101
|
+
scope: 'Only what these tests exercise. Thunder did not measure which lines or paths they cover.',
|
|
102
|
+
inputs: r.part ? partInputs(r.part) : [...hashes.values()],
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
for (const l of trace.links) {
|
|
106
|
+
add({
|
|
107
|
+
kind: 'trace-link', status: 'read',
|
|
108
|
+
claim: l.kind === 'http' ? `${l.from.repo} calls ${l.to.repo} with ${l.method} ${l.path}, and ${l.to.repo} handles it.` : `${l.from.repo} publishes "${l.event}", and ${l.to.repo} listens for it.`,
|
|
109
|
+
basis: { from: l.from.cite, to: l.to.cite, rules: `thunder-trace rules v${trace.rulesVersion}` },
|
|
110
|
+
scope: 'Read from code; nothing was run. It does not show that the call succeeds or what it answers.',
|
|
111
|
+
inputs: [inputOf(l.from.repo, l.from.file), inputOf(l.to.repo, l.to.file)],
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
let review = null;
|
|
115
|
+
if (change) {
|
|
116
|
+
const oldFiles = [], newFiles = [], changedInputs = [];
|
|
117
|
+
for (const p of parts) for (const c of p.changes ?? []) {
|
|
118
|
+
if (c.old != null) oldFiles.push({ path: `${p.name}/${c.file}`, source: c.old });
|
|
119
|
+
const now = p.files.find((f) => f.path === c.file);
|
|
120
|
+
if (now && c.status !== 'removed') { newFiles.push({ path: `${p.name}/${c.file}`, source: now.source }); changedInputs.push(inputOf(p.name, c.file)); }
|
|
121
|
+
}
|
|
122
|
+
review = thunderReview(oldFiles, newFiles);
|
|
123
|
+
add({
|
|
124
|
+
kind: 'review', status: 'read',
|
|
125
|
+
claim: `What the change does, read from both versions: ${review.says}`,
|
|
126
|
+
basis: { base: change.base, head: change.head, schema: review.schema, meaning: review.summary.meaning, risk: review.summary.risk, form: review.summary.form },
|
|
127
|
+
scope: 'What the code says before and after; not whether it runs or is right.',
|
|
128
|
+
inputs: changedInputs,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
for (const x of extra) add({ ...x, inputs: (x.inputs ?? []).map((i) => (i.sha256 ? i : inputOf(i.part, i.file))) });
|
|
132
|
+
|
|
133
|
+
// Unknowns: what Thunder could not read or link, the parts no test ran in, and what nothing here verified.
|
|
134
|
+
const tested = new Set(runs.filter((r) => r.part).map((r) => r.part));
|
|
135
|
+
const anyUnscoped = runs.some((r) => !r.part);
|
|
136
|
+
const untested = anyUnscoped ? [] : parts.filter((p) => !tested.has(p.name)).map((p) => ({ part: p.name, what: `No tests were run in ${p.name}.` }));
|
|
137
|
+
const notLinked = trace.notLinked.map((n) => ({ kind: n.kind, call: n.call, at: n.from.cite, why: n.why }));
|
|
138
|
+
const unknowns = {
|
|
139
|
+
notRead, notLinked, untested,
|
|
140
|
+
...(behavior.length > MAX_BEHAVIOR ? { notShown: `${behavior.length - MAX_BEHAVIOR} more actions and rules are not listed (the first ${MAX_BEHAVIOR} are).` } : {}),
|
|
141
|
+
notVerified: [...ALWAYS_NOT_VERIFIED, ...runs.filter((r) => r.exitCode !== 0).map((r) => `\`${r.command}\` failed, so what it tests is not verified.`)],
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const changedFiles = change ? parts.flatMap((p) => (p.changes ?? []).map((c) => ({ part: p.name, file: c.file, status: c.status }))) : [];
|
|
145
|
+
const body = {
|
|
146
|
+
schema: PASSPORT_SCHEMA,
|
|
147
|
+
subject: { kind: change ? 'change' : 'feature', parts: parts.map((p) => ({ name: p.name, path: p.path ?? p.name, sha: p.sha ?? null, dirty: !!p.dirty })) },
|
|
148
|
+
purpose: purpose?.text ? { stated: true, text: purpose.text, source: purpose.source ?? 'given when the passport was built' } : { stated: false, text: 'not stated', source: null },
|
|
149
|
+
behavior: shownBehavior,
|
|
150
|
+
dependencies: { files: [...hashes.values()], links, packages: parts.flatMap((p) => p.packages ?? []), services },
|
|
151
|
+
effects,
|
|
152
|
+
evidence,
|
|
153
|
+
unknowns,
|
|
154
|
+
history: { base: change?.base ?? null, head: change?.head ?? null, changedFiles, thunder },
|
|
155
|
+
};
|
|
156
|
+
const summary = summarize(body);
|
|
157
|
+
return { ...body, summary, history: { ...body.history, builtAt }, fingerprint: sha256(JSON.stringify({ ...body, summary })) };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The counts people read first. A claim is an evidence item; nothing counts as verified without one. */
|
|
161
|
+
export function summarize(p) {
|
|
162
|
+
const by = (s) => p.evidence.filter((e) => e.status === s).length;
|
|
163
|
+
const u = p.unknowns;
|
|
164
|
+
return {
|
|
165
|
+
claims: p.evidence.length, passed: by('passed'), failed: by('failed'), readFromCode: by('read'),
|
|
166
|
+
unknowns: u.notRead.length + u.notLinked.length + u.untested.length, notVerified: u.notVerified.length,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Is each evidence item still about the code as it is now? `read(part, file)` gives a file's current text, or null
|
|
172
|
+
* when it is gone. Nothing is re-run: an item is `current` when every file it depended on is unchanged, else `stale`
|
|
173
|
+
* (naming each changed or missing file). Items with no recorded inputs are `unknown`.
|
|
174
|
+
*/
|
|
175
|
+
export function checkPassport(passport, { read }) {
|
|
176
|
+
if (passport?.schema !== PASSPORT_SCHEMA) throw new Error('this is not a Thunder passport (thunder-passport-v1).');
|
|
177
|
+
const cache = new Map();
|
|
178
|
+
const now = (part, file) => {
|
|
179
|
+
const k = `${part}/${file}`;
|
|
180
|
+
if (!cache.has(k)) { const s = read(part, file); cache.set(k, s == null ? null : fileHash(s)); }
|
|
181
|
+
return cache.get(k);
|
|
182
|
+
};
|
|
183
|
+
const items = passport.evidence.map((e) => {
|
|
184
|
+
if (!e.inputs?.length) return { id: e.id, kind: e.kind, claim: e.claim, freshness: 'unknown', changed: [] };
|
|
185
|
+
const changed = [];
|
|
186
|
+
for (const i of e.inputs) {
|
|
187
|
+
const h = now(i.part, i.file);
|
|
188
|
+
if (h == null) changed.push({ part: i.part, file: i.file, now: 'missing' });
|
|
189
|
+
else if (h !== i.sha256) changed.push({ part: i.part, file: i.file, now: 'changed' });
|
|
190
|
+
}
|
|
191
|
+
return { id: e.id, kind: e.kind, claim: e.claim, freshness: changed.length ? 'stale' : 'current', changed };
|
|
192
|
+
});
|
|
193
|
+
const files = passport.dependencies.files.map((f) => ({ ...f, now: now(f.part, f.file) })).filter((f) => f.now !== f.sha256)
|
|
194
|
+
.map((f) => ({ part: f.part, file: f.file, now: f.now == null ? 'missing' : 'changed' }));
|
|
195
|
+
return { schema: 'thunder-passport-check-v1', current: items.filter((x) => x.freshness === 'current').length, stale: items.filter((x) => x.freshness === 'stale').length, items, changedFiles: files };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const MARK = { passed: '✓', failed: '✗', read: '○' };
|
|
199
|
+
const STATUS_WORDS = { passed: 'ran and passed', failed: 'ran and failed', read: 'read from code, not run' };
|
|
200
|
+
|
|
201
|
+
/** A passport as short plain text for the terminal: the counts, then each evidence item with a mark and words. */
|
|
202
|
+
export function renderPassportSummary(p) {
|
|
203
|
+
const s = p.summary;
|
|
204
|
+
const L = [`Thunder passport (${p.subject.kind}): ${p.subject.parts.map((x) => x.name).join(', ')}`,
|
|
205
|
+
`Purpose: ${p.purpose.stated ? p.purpose.text : 'not stated'}`,
|
|
206
|
+
`${s.claims} claim${s.claims === 1 ? '' : 's'} with evidence (${s.passed} passed, ${s.failed} failed, ${s.readFromCode} read from code), ${s.unknowns} unknown${s.unknowns === 1 ? '' : 's'}, ${s.notVerified} not verified`, '', 'Evidence'];
|
|
207
|
+
for (const e of p.evidence) L.push(` ${MARK[e.status] ?? '○'} ${STATUS_WORDS[e.status] ?? e.status}: ${e.claim}`);
|
|
208
|
+
if (!p.evidence.length) L.push(' (none: nothing in this passport is verified)');
|
|
209
|
+
L.push('', 'Not verified');
|
|
210
|
+
for (const x of p.unknowns.notVerified) L.push(` ○ ${x}`);
|
|
211
|
+
if (p.unknowns.untested.length) for (const x of p.unknowns.untested) L.push(` ○ ${x.what}`);
|
|
212
|
+
return L.join('\n');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The whole passport as Markdown, for a pull request or a folder. */
|
|
216
|
+
export function renderPassportMarkdown(p) {
|
|
217
|
+
const s = p.summary;
|
|
218
|
+
const L = [`# Thunder passport: ${p.subject.parts.map((x) => x.name).join(', ')}`, '',
|
|
219
|
+
`A ${p.subject.kind === 'change' ? `change${p.history.base ? ` from \`${String(p.history.base).slice(0, 12)}\`` : ''}` : 'snapshot'}. **${s.claims} claims with evidence** (${s.passed} passed, ${s.failed} failed, ${s.readFromCode} read from code), **${s.unknowns} unknowns**, **${s.notVerified} not verified**. This is an evidence record, not a certificate: each claim says what it rests on and what it does not cover.`, '',
|
|
220
|
+
'## Purpose', '', p.purpose.stated ? `${p.purpose.text}\n\n(Source: ${p.purpose.source}.)` : 'Not stated. Thunder never guesses what a change is for.', ''];
|
|
221
|
+
const evidenceList = (list) => {
|
|
222
|
+
for (const e of list) {
|
|
223
|
+
L.push(`- ${MARK[e.status] ?? '○'} ${e.claim}`);
|
|
224
|
+
const b = e.basis;
|
|
225
|
+
L.push(` - Basis: ${b.command ? `\`${b.command}\` in \`${b.cwd}\`, exit ${b.exitCode}, output ${String(b.outputDigest).slice(0, 19)}…` : b.from ? `${b.from} → ${b.to}` : b.base ? `review of ${String(b.base).slice(0, 12)} → ${String(b.head ?? 'working tree').slice(0, 12)}` : JSON.stringify(b)}`);
|
|
226
|
+
L.push(` - Does not cover: ${e.scope}`);
|
|
227
|
+
L.push(` - Depends on ${e.inputs.length} file${e.inputs.length === 1 ? '' : 's'} (by content hash)`);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
const ran = p.evidence.filter((e) => e.status === 'passed'), failedRuns = p.evidence.filter((e) => e.status === 'failed'), readOnly = p.evidence.filter((e) => e.status !== 'passed' && e.status !== 'failed');
|
|
231
|
+
L.push('## Verified by running (ran and passed)', '');
|
|
232
|
+
if (ran.length) evidenceList(ran); else L.push('Nothing was run, so nothing here is verified by running.');
|
|
233
|
+
if (failedRuns.length) { L.push('', '## Ran and failed', ''); evidenceList(failedRuns); }
|
|
234
|
+
L.push('', '## Read from code (not run)', '');
|
|
235
|
+
if (readOnly.length) evidenceList(readOnly); else L.push('None.');
|
|
236
|
+
L.push('', '## Not verified', '', ...p.unknowns.notVerified.map((x) => `- ${x}`), ...p.unknowns.untested.map((x) => `- ${x.what}`), '');
|
|
237
|
+
L.push('## Behavior', '');
|
|
238
|
+
for (const b of p.behavior) {
|
|
239
|
+
L.push(`### ${b.name} (${b.part}/${b.file}, lines ${b.lines[0]}–${b.lines[1]}${b.change ? `, ${b.change}` : ''})`, '', '```text', b.text || '(no reading)', '```', '');
|
|
240
|
+
}
|
|
241
|
+
if (p.unknowns.notShown) L.push(p.unknowns.notShown, '');
|
|
242
|
+
L.push('## Effects (detected in code, not observed)', '');
|
|
243
|
+
for (const e of p.effects) L.push(`- ${e.in} **${e.kind}**: ${e.says} (${e.part}/${e.file}:${e.line})`);
|
|
244
|
+
if (!p.effects.length) L.push('None detected.');
|
|
245
|
+
L.push('', '## Dependencies', '', ...p.dependencies.links.map((l) => `- ${l.says} (${l.from} → ${l.to})`));
|
|
246
|
+
if (p.dependencies.packages.length) L.push(...p.dependencies.packages.map((x) => `- package ${x.name}${x.version ? ` ${x.version}` : ''} (${x.from})`));
|
|
247
|
+
if (p.dependencies.services.length) L.push(...p.dependencies.services.map((x) => `- calls ${x.calls} (${x.at})`));
|
|
248
|
+
L.push(`- ${p.dependencies.files.length} files read, each recorded by content hash`, '');
|
|
249
|
+
L.push('## Unknowns', '');
|
|
250
|
+
for (const x of p.unknowns.notRead) L.push(`- not read: ${x.what} (${x.part}/${x.file}:${x.line})`);
|
|
251
|
+
for (const x of p.unknowns.notLinked) L.push(`- not linked: ${x.call}: ${x.why} (${x.at})`);
|
|
252
|
+
if (!p.unknowns.notRead.length && !p.unknowns.notLinked.length) L.push('Nothing Thunder failed to read or link.');
|
|
253
|
+
L.push('', '## History', '', `- Base: ${p.history.base ?? '(none: a snapshot)'}`, `- Head: ${p.history.head ?? '(working tree)'}`, ...p.history.changedFiles.map((c) => `- ${c.status}: ${c.part}/${c.file}`), `- Built: ${p.history.builtAt}${p.history.thunder ? ` with Thunder ${p.history.thunder}` : ''}`, `- Fingerprint: ${p.fingerprint}`, '');
|
|
254
|
+
return L.join('\n');
|
|
255
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Types for @skillstech/thunderlang/program (src/program.mjs). Results are plain objects; see docs/core.md.
|
|
2
|
+
export interface CoreDiagnostic { code: string; line: number; message: string; hint?: string; [k: string]: unknown }
|
|
3
|
+
export interface CoreResult { ok: boolean; program?: unknown; info?: unknown; diagnostics: CoreDiagnostic[]; file?: string; module?: string; kind?: string; [k: string]: unknown }
|
|
4
|
+
export interface RunOutput { status: number; stdout: string; stderr: string; [k: string]: unknown }
|
|
5
|
+
export type ReadText = ((path: string, cwd: string) => string) | null;
|
|
6
|
+
export const CORE_VERSION: string;
|
|
7
|
+
export const CODES: Record<string, unknown>;
|
|
8
|
+
export function compileCore(source: string, options?: { file?: string; imported?: unknown[]; srcModules?: unknown[] }): CoreResult;
|
|
9
|
+
export function diagnosticsText(result: CoreResult): string;
|
|
10
|
+
export function parseCore(source: string, ...rest: unknown[]): unknown;
|
|
11
|
+
export function checkCore(...args: unknown[]): unknown;
|
|
12
|
+
export function formatCore(source: string, options?: { width?: number }): unknown;
|
|
13
|
+
export function formatDiagnostic(...args: unknown[]): string;
|
|
14
|
+
export function runInProcess(options: { entry: CoreResult; cwd: string; deeper?: boolean; readText?: ReadText }): RunOutput;
|
|
15
|
+
export function recordedRun(options: { entry: CoreResult; cwd: string; readText?: ReadText }): unknown;
|
|
16
|
+
export function testInProcess(options: { results: CoreResult[]; cwd: string; deeper?: boolean; readText?: ReadText }): unknown;
|
|
17
|
+
export interface ScreenAppHandle { render(): unknown; readonly screen: string | null; press(label: string, nth?: number): { off: boolean; tree: unknown }; type(label: string, text: string, nth?: number): { tree: unknown } }
|
|
18
|
+
/** The same handle, by the name apps expect. */
|
|
19
|
+
export type ScreenApp = ScreenAppHandle;
|
|
20
|
+
export function screenApp(options: { entry: CoreResult; cwd?: string; readText?: ReadText }): ScreenAppHandle;
|
|
21
|
+
export function screenOutline(tree: unknown, indent?: string): string;
|
|
22
|
+
export function toPython(program: unknown, info: unknown, options?: { source?: string; imports?: unknown[] }): string;
|
|
23
|
+
export function toTypeScript(program: unknown, info: unknown, options?: { source?: string; imports?: unknown[] }): string;
|
|
24
|
+
export function toCSharp(program: unknown, info: unknown, options?: { source?: string; module?: string; namespace?: string; imports?: unknown[] }): string;
|
|
25
|
+
export function toJava(program: unknown, info: unknown, options?: { source?: string; module?: string; imports?: unknown[]; pkg?: string }): string;
|
|
26
|
+
export function toGo(program: unknown, info: unknown, options: { source?: string; module?: string; ns: unknown }): string;
|
|
27
|
+
export function goNamespaces(results: CoreResult[]): Map<string, unknown>;
|
|
28
|
+
export function toRust(program: unknown, info: unknown, options?: { source?: string; imports?: unknown[] }): string;
|
|
29
|
+
export function toReact(program: unknown, info: unknown, options?: { source?: string }): string;
|
|
30
|
+
export function hasScreens(info: unknown): boolean;
|
|
31
|
+
export function pythonToCore(source: string): { core: string; functions: Array<{ name: string; exact: boolean }>; [k: string]: unknown };
|
package/src/program.mjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// @skillstech/thunderlang/program: write and run Thunder Core anywhere, including in a browser. Compile a program,
|
|
2
|
+
// run it on the Thunder engine, show its screens, and turn it into Python, TypeScript, C#, Java, Go, Rust, or React.
|
|
3
|
+
// Everything here is browser-safe (no node: imports; test/program-entry.test.mjs checks the whole import graph).
|
|
4
|
+
// Files are read only through the `readText` you pass, so a browser can hand in its own.
|
|
5
|
+
export { compileCore, diagnosticsText, parseCore, checkCore, formatCore, CODES, formatDiagnostic, CORE_VERSION } from './core/index.mjs';
|
|
6
|
+
export { runInProcess, recordedRun, testInProcess, screenApp, screenOutline } from './core/engine-core.mjs';
|
|
7
|
+
export { toPython } from './core/target-python.mjs';
|
|
8
|
+
export { toTypeScript } from './core/target-typescript.mjs';
|
|
9
|
+
export { toCSharp } from './core/target-csharp.mjs';
|
|
10
|
+
export { toJava } from './core/target-java.mjs';
|
|
11
|
+
export { toGo, goNamespaces } from './core/target-go.mjs';
|
|
12
|
+
export { toRust } from './core/target-rust.mjs';
|
|
13
|
+
export { toReact, hasScreens } from './core/target-react.mjs';
|
|
14
|
+
export { pythonToCore } from './core/from-python.mjs';
|
package/src/read.mjs
CHANGED
|
@@ -135,6 +135,27 @@ function matchClose(src, open) {
|
|
|
135
135
|
// The language being read. Only Rust has lifetimes ('static, 'a), which look like an opening quote.
|
|
136
136
|
let READING_RUST = false;
|
|
137
137
|
|
|
138
|
+
/** For C# and Java: a flag per character, 1 inside text ("…", $"…", @"…", '…', """…""") or a comment. */
|
|
139
|
+
function textRanges(src) {
|
|
140
|
+
const flags = new Uint8Array(src.length + 1);
|
|
141
|
+
for (let i = 0; i < src.length; i++) {
|
|
142
|
+
const c = src[i];
|
|
143
|
+
if (c === '/' && src[i + 1] === '/') { const e = src.indexOf('\n', i); const end = e < 0 ? src.length : e; flags.fill(1, i, end); i = end; continue; }
|
|
144
|
+
if (c === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); const end = e < 0 ? src.length : e + 2; flags.fill(1, i, end); i = end - 1; continue; }
|
|
145
|
+
if (c === '"' || c === '\'') {
|
|
146
|
+
let end;
|
|
147
|
+
if (c === '"' && src[i - 1] === '@' || (c === '"' && src[i - 1] === '$' && src[i - 2] === '@')) {
|
|
148
|
+
// A verbatim string: "" is a quote inside it.
|
|
149
|
+
end = i + 1;
|
|
150
|
+
while (end < src.length && !(src[end] === '"' && src[end + 1] !== '"')) end += src[end] === '"' ? 2 : 1;
|
|
151
|
+
} else end = skipString(src, i);
|
|
152
|
+
flags.fill(1, i, Math.min(src.length, end + 1));
|
|
153
|
+
i = end;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return flags;
|
|
157
|
+
}
|
|
158
|
+
|
|
138
159
|
function skipString(src, i) {
|
|
139
160
|
const q = src[i];
|
|
140
161
|
// A multi-line string (triple quotes in Swift, Kotlin, Java, C#) runs to its closing triple quote.
|
|
@@ -338,6 +359,9 @@ function findFunctions(src, language) {
|
|
|
338
359
|
patterns.javascript = patterns.typescript;
|
|
339
360
|
patterns.csharp = [/(?:(?:public|private|protected|internal|static|virtual|override|async|sealed|abstract|readonly)\s+)*[\w.<>\[\],?\s]+?\s+(\w+)\s*\(/g];
|
|
340
361
|
const seen = new Set();
|
|
362
|
+
// C# and Java: words inside text (`$"known bug (fails as expected) {name}"`) are never a method, and neither is a
|
|
363
|
+
// lambda passed as an argument (`Check("…", async () => { … })`).
|
|
364
|
+
const inText = (language === 'csharp' || language === 'java') ? textRanges(src) : null;
|
|
341
365
|
for (const re of patterns[language] || []) {
|
|
342
366
|
let m;
|
|
343
367
|
re.lastIndex = 0;
|
|
@@ -345,6 +369,7 @@ function findFunctions(src, language) {
|
|
|
345
369
|
const name = m[1];
|
|
346
370
|
const open = src.indexOf('(', m.index + m[0].length - 1);
|
|
347
371
|
if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
|
|
372
|
+
if (inText && (inText[m.index + m[0].lastIndexOf(name, m[0].length - 1)] || (language === 'csharp' && name === 'async'))) continue;
|
|
348
373
|
const close = matchClose(src, open);
|
|
349
374
|
if (close < 0) continue;
|
|
350
375
|
// After the parameter list: an optional return type / throws clause, then a body. A signature's head is short,
|
|
@@ -419,6 +444,9 @@ function findFunctions(src, language) {
|
|
|
419
444
|
? [/\bRoute::(get|post|put|patch|delete|any)\(\s*['"]([^'"]+)['"]\s*,\s*(?:static\s+)?function\s*\(/g]
|
|
420
445
|
: language === 'go'
|
|
421
446
|
? [/\.(Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\(\s*"([^"]+)"\s*,\s*func\s*\(/g]
|
|
447
|
+
: language === 'csharp'
|
|
448
|
+
// ASP.NET minimal APIs: app.MapPost("/orders", async (OrderRequest request, OrderService orders) => { … })
|
|
449
|
+
? [/\b\w+\.Map(Get|Post|Put|Patch|Delete)\(\s*"([^"]+)"\s*,\s*(?:async\s*)?\(/g]
|
|
422
450
|
: (language === 'typescript' || language === 'javascript')
|
|
423
451
|
// (The handler may be wrapped: `fastify.get('/x', handle(async (request) => …))`, `asyncHandler(…)`.)
|
|
424
452
|
? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:[A-Za-z_$][\w$.]*(?:<[^<>()]*>)?\(\s*)*(?:async\s*)?(?:function\s*\w*\s*)?\(/g]
|
|
@@ -435,7 +463,7 @@ function findFunctions(src, language) {
|
|
|
435
463
|
// An arrow whose body is one expression: `async (request) => practiceView(…)`. It gives back that value;
|
|
436
464
|
// the expression runs to the first ")" or "," that closes the call around it.
|
|
437
465
|
const arrow = /^\s*(?::\s*[^=()]+)?=>\s*/.exec(src.slice(close + 1));
|
|
438
|
-
if (!(language === 'typescript' || language === 'javascript') || !arrow || src[close + 1 + arrow[0].length] === '{') continue;
|
|
466
|
+
if (!(language === 'typescript' || language === 'javascript' || language === 'csharp') || !arrow || src[close + 1 + arrow[0].length] === '{') continue;
|
|
439
467
|
const from = close + 1 + arrow[0].length;
|
|
440
468
|
let depth = 0, end = from, q = null;
|
|
441
469
|
for (; end < src.length; end++) {
|
|
@@ -1179,6 +1207,14 @@ function annotateRoutes(fns, src) {
|
|
|
1179
1207
|
const above = fn.decorators
|
|
1180
1208
|
? [...fn.decorators].reverse()
|
|
1181
1209
|
: lines.slice(Math.max(0, fn.line - 6), Math.max(0, fn.line - 1)).reverse().map((x) => x.trim());
|
|
1210
|
+
// Python's standard library server: a handler's do_POST answers POST, and the one path it checks
|
|
1211
|
+
// (`if self.path != "/charges": …`) is its route. Two or more paths checked: no single route, so none is named.
|
|
1212
|
+
const std = /^do_(GET|POST|PUT|PATCH|DELETE|HEAD)$/.exec(fn.name ?? '');
|
|
1213
|
+
const stdBody = typeof fn.body === 'string' ? fn.body : Array.isArray(fn.pyBody) ? fn.pyBody.map((x) => x.text).join('\n') : null;
|
|
1214
|
+
if (std && stdBody) {
|
|
1215
|
+
const paths = new Set([...stdBody.matchAll(/\bself\.path\s*(?:==|!=)\s*['"](\/[^'"]*)['"]/g)].map((x) => x[1]));
|
|
1216
|
+
if (paths.size === 1) { fn.route = { method: std[1], path: [...paths][0] }; continue; }
|
|
1217
|
+
}
|
|
1182
1218
|
for (const l of above) {
|
|
1183
1219
|
let m;
|
|
1184
1220
|
if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
|
package/src/review.mjs
CHANGED
|
@@ -376,14 +376,15 @@ function valueChanges(o, n) {
|
|
|
376
376
|
return ` (values ${onlyA.length ? `${onlyA.slice(0, 4).join(', ')} removed` : ''}${onlyA.length && onlyB.length ? ', ' : ''}${onlyB.length ? `${onlyB.slice(0, 4).join(', ')} added` : ''})`;
|
|
377
377
|
}
|
|
378
378
|
|
|
379
|
-
function compareMember(o, n, items) {
|
|
379
|
+
function compareMember(o, n, items, { extracted = false } = {}) {
|
|
380
380
|
const subject = subjectOf(n);
|
|
381
381
|
const sameCode = sameTokens(o.tokens, n.tokens);
|
|
382
382
|
const sameThunder = o.sig === n.sig;
|
|
383
383
|
const renamedOrMoved = [];
|
|
384
384
|
if (o.m.file !== n.m.file) renamedOrMoved.push(`moved from ${o.m.file} to ${n.m.file}`);
|
|
385
385
|
// A route handler is named after its address: a new address is said once, as the address.
|
|
386
|
-
|
|
386
|
+
// (Steps moved into a new function are not a rename: the old function is still there and runs the new one.)
|
|
387
|
+
if (!extracted && nameKey(o.m.name) !== nameKey(n.m.name) && (o.m.route ?? '') === (n.m.route ?? '')) renamedOrMoved.push(`renamed from ${o.m.label} to ${n.m.label}`);
|
|
387
388
|
const moveKind = o.m.file !== n.m.file && nameKey(o.m.name) === nameKey(n.m.name) ? 'moved' : 'renamed';
|
|
388
389
|
const formOnly = (why) => items.push(item(renamedOrMoved.length ? moveKind : 'form', 'form', subject, whereOf(n),
|
|
389
390
|
`${renamedOrMoved.length ? `${cap(renamedOrMoved.join(' and '))}. ` : ''}Only the form changed: ${why}`));
|
|
@@ -520,6 +521,18 @@ function enclosingName(lines, line) {
|
|
|
520
521
|
* pass only the files that changed (and, for a moved file, both paths) or whole trees. Returns
|
|
521
522
|
* { schema, summary, items, notRead, unchanged } with items ordered by importance (risk, then meaning, then form).
|
|
522
523
|
*/
|
|
524
|
+
/** Whether most of `a`'s code tokens (by count) are also in `b`: three out of four or more, ignoring punctuation. */
|
|
525
|
+
function mostlyIn(a, b) {
|
|
526
|
+
const words = (ts) => ts.map((t) => t.t).filter((t) => /\w/.test(t));
|
|
527
|
+
const have = new Map();
|
|
528
|
+
for (const t of words(b)) have.set(t, (have.get(t) || 0) + 1);
|
|
529
|
+
const want = words(a);
|
|
530
|
+
if (want.length < 12) return false;
|
|
531
|
+
let hit = 0;
|
|
532
|
+
for (const t of want) { const c = have.get(t) || 0; if (c) { hit++; have.set(t, c - 1); } }
|
|
533
|
+
return hit / want.length >= 0.75;
|
|
534
|
+
}
|
|
535
|
+
|
|
523
536
|
export function thunderReview(oldFiles, newFiles) {
|
|
524
537
|
detailsCache = new WeakMap();
|
|
525
538
|
const A = side(oldFiles || []), B = side(newFiles || []);
|
|
@@ -551,8 +564,23 @@ export function thunderReview(oldFiles, newFiles) {
|
|
|
551
564
|
|| (o.m.rule && e.m.rule && !o.m.rule.partial && !e.m.rule.partial && comparePlainRules(o.m.rule, e.m.rule).same)));
|
|
552
565
|
if (n) { used.add(n); pairs.push([o, n]); o.paired = true; }
|
|
553
566
|
}
|
|
567
|
+
// 5. Steps moved into a new function: the function now runs a new one in the same file, and most of its old code
|
|
568
|
+
// is there. Its old steps are compared with the new function (what really changed in them), and the function
|
|
569
|
+
// itself is said to run it, instead of "no longer gives back …" for every step that only moved.
|
|
570
|
+
const movedInto = new Map();
|
|
571
|
+
for (const [o, n] of pairs) {
|
|
572
|
+
const named = new Set(n.tokens.map((t) => t.t));
|
|
573
|
+
const target = leftB().find((b) => b.m.file === n.m.file && b.m.kind !== 'not-read' && named.has(b.m.name) && b.m.name !== n.m.name && mostlyIn(o.tokens, b.tokens));
|
|
574
|
+
if (target) { used.add(target); movedInto.set(o, target); }
|
|
575
|
+
}
|
|
554
576
|
let unchanged = 0;
|
|
555
|
-
for (const [o, n] of pairs)
|
|
577
|
+
for (const [o, n] of pairs) {
|
|
578
|
+
const into = movedInto.get(o);
|
|
579
|
+
if (!into) { if (compareMember(o, n, items) === 'unchanged') unchanged++; continue; }
|
|
580
|
+
const now = n.text.slice(1).map((l) => l.trim()).filter(Boolean);
|
|
581
|
+
items.push(item('moved-into', 'meaning', subjectOf(n), whereOf(n), `Its steps moved to ${subjectOf(into)}, a new function it now runs; what changed in them is listed under ${subjectOf(into)}.`, { before: null, after: now }));
|
|
582
|
+
compareMember(o, into, items, { extracted: true });
|
|
583
|
+
}
|
|
556
584
|
for (const o of leftA()) items.push(item('removed', 'meaning', subjectOf(o), whereOf(o), `Removed ${KIND_WORD[o.m.kind] ?? 'function'}: ${subjectOf(o)}.`, { before: o.text, after: null }));
|
|
557
585
|
for (const n of leftB()) items.push(item('added', n.m.kind === 'not-read' ? 'risk' : 'meaning', subjectOf(n), whereOf(n),
|
|
558
586
|
n.m.kind === 'not-read' ? "New function that Thunder cannot read yet: check the code itself." : `New ${KIND_WORD[n.m.kind] ?? 'function'}: ${subjectOf(n)}${summaryOf(n)}.`, { before: null, after: n.text }));
|
package/src/say-less.mjs
CHANGED
|
@@ -385,6 +385,15 @@ function newThing(v, says) {
|
|
|
385
385
|
if (!m) return false;
|
|
386
386
|
let c = coreOf(v);
|
|
387
387
|
if (c?.kind === 'unary' && c.op === '&') c = coreOf(c.value);
|
|
388
|
+
// "a new random ID" for the calls that make one (crypto.randomUUID(), uuid.uuid4(), Guid.NewGuid(), …), and for
|
|
389
|
+
// its text form (`.ToString()`, `.hex`).
|
|
390
|
+
if (m[1] === 'random ID') {
|
|
391
|
+
let x = c;
|
|
392
|
+
if (x?.kind === 'call' && x.callee?.kind === 'member' && /^(?:ToString|toString)$/.test(x.callee.property)) x = x.callee.object;
|
|
393
|
+
if (x?.kind === 'member' && x.property === 'hex') x = x.object;
|
|
394
|
+
const name = x?.kind === 'call' ? (x.callee?.kind === 'member' ? x.callee.property : x.callee?.name) : null;
|
|
395
|
+
return /^(?:randomUUID|uuid4|NewGuid|uuidv4|v4|new_v4)$/.test(name ?? '') && !(x.args?.length);
|
|
396
|
+
}
|
|
388
397
|
const type = c?.kind === 'object' ? c.type : c?.kind === 'call' ? (c.callee.kind === 'name' ? c.callee.name : c.callee.kind === 'member' ? (/^(?:new|New)$/.test(c.callee.property) ? (c.callee.object.name ?? c.callee.object.property) : c.callee.property) : null) : null;
|
|
389
398
|
return !!type && sameWords(String(type).replace(/<.*$/, '').split(/::|\./).pop(), m[1]);
|
|
390
399
|
}
|
|
@@ -476,6 +485,8 @@ function namesKept(tree, said) {
|
|
|
476
485
|
if (name && /^(?:any|some|all|every|none|find|first|filter|where|select|detect|find_index|findIndex|includes|include\?|contains|Contains|any\?|all\?|none\?|exists|Any|All|Exists|in_array|has|hasOwnProperty|has_key|key\?|containsKey|ContainsKey|startswith|endswith|startsWith|endsWith|StartsWith|EndsWith|start_with\?|end_with\?)$/.test(name) && / (?:any|every|all|no|first|matches|match|in|has|contains|starts|ends|one of) /.test(sw)) return ok(own) && n.args.every((a) => a.kind === 'lambda' || ok(a));
|
|
477
486
|
if (name && /^(?:len|length|size|count|nrow|NROW|Count|sizeof|strlen|wcslen|mb_strlen|nchar|str_length|lengths|Length)$/.test(name) && howMany) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
|
|
478
487
|
if (name && /^(?:isinstance|is_a\??|kind_of\??|instance_of\??|inherits|is)$/.test(name) && isA) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
|
|
488
|
+
// (C#'s String.IsNullOrEmpty(x) is a question about x: the type it is asked on is not a value.)
|
|
489
|
+
if (name && /^IsNullOr(?:Empty|WhiteSpace)$/.test(name) && c?.kind === 'member' && /^[Ss]tring$/.test(c.object?.name ?? '') && setWords) return ok(n.args);
|
|
479
490
|
if (name && /^(?:is\.null|is_null|isNull|is\.na|isset|empty|is_none|isNone|isNil|is_nil|nil\?|null\?|blank\?|present\?|empty\?|isEmpty|IsNullOrEmpty|IsNullOrWhiteSpace|isBlank|isNotEmpty|isNotBlank|any\?|none\?)$/.test(name) && setWords) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
|
|
480
491
|
return (name == null || has(name)) && (c?.kind !== 'member' || ok(c.object) || /^[A-Z]/.test(c.object?.name ?? '')) && ok(n.args);
|
|
481
492
|
}
|
|
@@ -500,7 +511,9 @@ const KEYWORD_CALLEE = /^(?:use|unsafe|using|foreach|for|type|return|pub|public|
|
|
|
500
511
|
|
|
501
512
|
const coreOf = (e) => {
|
|
502
513
|
let c = e;
|
|
503
|
-
|
|
514
|
+
// (.NET: a get-or-add of a Lazy, `byKey.GetOrAdd(k, _ => new Lazy<T>(…)).Value`, gives the entry's value: the call is the core.)
|
|
515
|
+
while (c && ((c.kind === 'unary' && (c.op === 'await' || c.op === '?' || c.op === '!!')) || (c.kind === 'cast' && c.form === 'nonnull')
|
|
516
|
+
|| (c.kind === 'member' && c.property === 'Value' && c.object?.kind === 'call' && c.object.callee?.property === 'GetOrAdd'))) c = c.kind === 'member' ? c.object : c.value;
|
|
504
517
|
return c;
|
|
505
518
|
};
|
|
506
519
|
/** The names of the calls along a value's receiver chain: a.b().c() -> [b, c]. */
|
|
@@ -824,7 +837,8 @@ function conditionCore(test, says, code, lang) {
|
|
|
824
837
|
const said = claimText(says);
|
|
825
838
|
const tn = treeNegations(test), wn = saidNegations(says);
|
|
826
839
|
if (tn !== wn) return M('L378');
|
|
827
|
-
|
|
840
|
+
// (String.IsNullOrEmpty(x) asks "null, or empty": the "or" is in its name; see accountsFor.)
|
|
841
|
+
let logic = 0; for (const n of nodesOf(test)) if (n.kind === 'logic') logic += n.operands.length - 1; else if (n.kind === 'call' && /^IsNullOr(?:Empty|WhiteSpace)$/.test(n.callee?.property ?? '')) logic++;
|
|
828
842
|
const wl = (said.match(/\band\b|\bor\b/g) || []).length;
|
|
829
843
|
if (logic !== wl) return M('L381');
|
|
830
844
|
if (!orderingKept(test, says)) return M('L382');
|
package/src/steps.mjs
CHANGED
|
@@ -315,6 +315,10 @@ function sayCodeConditionInner(cond) {
|
|
|
315
315
|
if (call[2] === 'is_null') return `${what} is ${call[1] ? 'not ' : ''}null`;
|
|
316
316
|
return call[2] === 'isset' ? `${what} is ${call[1] ? 'not ' : ''}set` : `${what} is ${neg ? 'not ' : ''}empty`;
|
|
317
317
|
}
|
|
318
|
+
// C#: String.IsNullOrEmpty(x) -> "x is empty or missing"; IsNullOrWhiteSpace -> "x is blank or missing".
|
|
319
|
+
if ((call = c.match(/^(!|not\s+)?[Ss]tring\.IsNullOr(Empty|WhiteSpace)\(\s*([\w$.]+)\s*\)$/))) {
|
|
320
|
+
return `${possessiveWords(call[3])} is ${call[1] ? 'not ' : ''}${call[2] === 'Empty' ? 'empty' : 'blank'}${call[1] ? ' and is set' : ' or missing'}`;
|
|
321
|
+
}
|
|
318
322
|
// isObject(x) -> "x is object"; !isRequest(options.request) -> "the options's request is not request".
|
|
319
323
|
if ((call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?is_?([A-Z]\w*)\s*\(\s*([\w$.]+)\s*\)$/)) && !/^(?:Empty|Set|Null)$/.test(call[2])) {
|
|
320
324
|
return `${possessiveWords(call[3])} is ${call[1] ? 'not ' : ''}${words(call[2])}`;
|
|
@@ -1538,6 +1542,12 @@ export function statementExpr(raw) {
|
|
|
1538
1542
|
}
|
|
1539
1543
|
const codeExpr = (text) => ({ kind: 'code', text: String(text ?? '').replace(/\s+/g, ' ').trim() });
|
|
1540
1544
|
|
|
1545
|
+
/**
|
|
1546
|
+
* A first line that opens an object as a call's argument, `fetch(url, {` / `post({`: the statement goes on to the
|
|
1547
|
+
* line that closes the call, so it is read whole. (A callback, `items.forEach((x) => {`, is a block: not this.)
|
|
1548
|
+
*/
|
|
1549
|
+
const callWithObject = (first) => /[(,]\s*\{\s*$/.test(first) && !/=>\s*\{\s*$/.test(first) && !bracketsClosed(first.replace(/\{\s*$/, ''));
|
|
1550
|
+
|
|
1541
1551
|
function classifyWords(raw, { inner = 0 } = {}) {
|
|
1542
1552
|
const text = String(raw).trim();
|
|
1543
1553
|
// A condition written over several lines (`if (\n a &&\n b\n) {`) is read whole.
|
|
@@ -1559,11 +1569,13 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1559
1569
|
const rest = c > 0 ? text.slice(c + 1).trim() : '';
|
|
1560
1570
|
if (rest && !rest.startsWith('{') && !text.slice(c + 1).split('\n')[0].trim()) first = `${text.slice(0, c + 1).replace(/\s+/g, ' ').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')')} ${rest.replace(/\s+/g, ' ')}`.trim();
|
|
1561
1571
|
}
|
|
1572
|
+
// C#: `return Task.FromResult(x);` gives back x (as a finished task): read as `return x;`.
|
|
1573
|
+
if (LANG === 'csharp') first = first.replace(/^return\s+(?:Task|ValueTask)\.FromResult\((.*)\)\s*;?$/, 'return $1;');
|
|
1562
1574
|
// `return (` with JSX on the next line: what is drawn on screen.
|
|
1563
1575
|
if (/^return\s*\(\s*$/.test(first) && /^\s*</.test(text.split('\n')[1] || '')) first = `return (${text.split('\n')[1].trim()}`;
|
|
1564
1576
|
// A statement written over several lines (`return a\n && b`, `x =\n cond ? y : z`, `return (\n <div>…`) is read
|
|
1565
1577
|
// whole, so a value is never cut to its first line.
|
|
1566
|
-
else if (text.includes('\n') && !/^(?:if|else|elif|elsif|for|foreach|while|until|switch|try|catch|finally|do|match|loop|when|case|default|unless|with|def|fn|fun|func|function|class|struct|interface|enum|impl|object|begin|select|using|lock)\b/.test(first) && (!/[{:]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^(?:const|let|var|val)\s*[{[]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first)) && !/=>\s*\{?\s*$/.test(first) && text.length < 2000 && balancedText(text) && (!/\{\s*$/.test(text.split('\n')[0]) || /^(?:const|let|var|val)\s*[{[]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first))) {
|
|
1578
|
+
else if (text.includes('\n') && !/^(?:if|else|elif|elsif|for|foreach|while|until|switch|try|catch|finally|do|match|loop|when|case|default|unless|with|def|fn|fun|func|function|class|struct|interface|enum|impl|object|begin|select|using|lock)\b/.test(first) && (!/[{:]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^(?:const|let|var|val)\s*[{[]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first) || callWithObject(first)) && !/=>\s*\{?\s*$/.test(first) && text.length < 2000 && balancedText(text) && (!/\{\s*$/.test(text.split('\n')[0]) || /^(?:const|let|var|val)\s*[{[]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first) || callWithObject(first))) {
|
|
1567
1579
|
const lines = text.split('\n');
|
|
1568
1580
|
const joined = lines.map((l) => l.trim()).join(' ');
|
|
1569
1581
|
if (!bracketsClosed(first) || /(?:[-+*/%&|^=<>?:.,(\[]|\b(?:and|or|not|in))\s*$/.test(first) || /^\s*(?:[-+*/%&|^=<>?:.)\]]|&&|\|\||\b(?:and|or)\b)/.test(lines[1] || '')) first = joined;
|
package/src/things-langs.mjs
CHANGED
|
@@ -66,8 +66,18 @@ function cDocAbove(src, idx) {
|
|
|
66
66
|
|
|
67
67
|
/** The body of a brace block with nested blocks removed: the type's own declarations, not its methods' bodies. */
|
|
68
68
|
function ownLevel(body) {
|
|
69
|
-
let depth = 0, own = '';
|
|
70
|
-
for (
|
|
69
|
+
let depth = 0, own = '', start = 0;
|
|
70
|
+
for (let i = 0; i < body.length; i++) {
|
|
71
|
+
const c = body[i];
|
|
72
|
+
if (c === '{') { if (depth === 0) start = i; depth++; }
|
|
73
|
+
if (depth === 0) own += c;
|
|
74
|
+
if (c === '}') {
|
|
75
|
+
depth--;
|
|
76
|
+
// A value's initializer (`= new() { ["a"] = 1 }`, `= new List<int> { 1, 2 }`, `= { 1, 2 }`) is kept as a
|
|
77
|
+
// mark, so a filled-in value never reads as empty; a method's body is dropped.
|
|
78
|
+
if (depth === 0 && /(?:=|\bnew\b[\w.<>,[\] ?]*(?:\([^()]*\))?)\s*$/.test(own) && body.slice(start + 1, i).trim()) own = `${own.replace(/\s+$/, '')} {…}`;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
71
81
|
return own;
|
|
72
82
|
}
|
|
73
83
|
|
|
@@ -95,7 +105,12 @@ function goDoc(src, at, name) {
|
|
|
95
105
|
const MODIFIERS = /^(?:(?:public|private|protected|internal|static|final|readonly|const|volatile|transient|override|open|abstract|sealed|lateinit|required|unsafe|mut|pub(?:\([^)]*\))?|var|val|let)\s+)*/;
|
|
96
106
|
|
|
97
107
|
export function makeThingReaders({ words, kindWords, startValue }) {
|
|
98
|
-
|
|
108
|
+
// (C#'s `new()` names no type: it is empty only when the declared type is a list or lookup table.)
|
|
109
|
+
const know = (name, type, start, params, line = null) => {
|
|
110
|
+
const kind = type ? kindWords(type) : null;
|
|
111
|
+
const said = start != null && start !== '' ? (/^new\(\)$/.test(String(start).trim()) && !/^(a list|a lookup table|a set)/.test(kind ?? '') ? 'worked out when it starts' : startValue(start, params)) : null;
|
|
112
|
+
return { name, label: words(name.replace(/^[_$]+|_$/g, '')), kind, start: said, line };
|
|
113
|
+
};
|
|
99
114
|
|
|
100
115
|
/** Java, C#, Kotlin, PHP: brace-bodied classes. */
|
|
101
116
|
function curlyThings(src, file, language) {
|
|
@@ -164,6 +179,8 @@ export function makeThingReaders({ words, kindWords, startValue }) {
|
|
|
164
179
|
thing.knows.push(know(f[2], f[1], f[3], params));
|
|
165
180
|
}
|
|
166
181
|
}
|
|
182
|
+
// A property that shows a field (`_orders` and `Orders`) is the same thing known twice: keep it once.
|
|
183
|
+
thing.knows = thing.knows.filter((k, i, all) => all.findIndex((x) => x.label === k.label) === i);
|
|
167
184
|
// Starting values set in the constructor: this.x = …; / $this->x = …; / x = … (Kotlin init blocks).
|
|
168
185
|
const ctorRe = language === 'php' ? /function\s+__construct\s*\(([^)]*)\)\s*\{/ : language === 'kotlin' ? /\binit\s*\{/ : new RegExp(`(?:public|private|protected|internal)?\\s*${name}\\s*\\(([^)]*)\\)\\s*(?::\\s*(?:this|base)\\([^)]*\\)\\s*)?\\{`);
|
|
169
186
|
const ctor = body.match(ctorRe);
|