@skillstech/thunderlang 0.5.11 → 0.5.12
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 +437 -0
- package/dist/core.cjs +30431 -7604
- package/dist/index.cjs +28577 -5331
- package/dist/learn.cjs +22676 -3870
- package/package.json +12 -3
- package/src/bicep.mjs +167 -0
- package/src/cli.mjs +169 -3
- package/src/commands.mjs +464 -0
- package/src/core.d.ts +12 -4
- package/src/core.mjs +12 -4
- package/src/emit.mjs +1 -1
- package/src/executed.d.mts +53 -0
- package/src/executed.mjs +465 -0
- package/src/faithful.mjs +137 -0
- package/src/file-formats.mjs +35 -0
- package/src/hcl.mjs +94 -0
- package/src/index.d.ts +7 -1
- package/src/index.mjs +6 -1
- package/src/infra-bicep.mjs +312 -0
- package/src/infra-cloud.mjs +348 -0
- package/src/infra-compose.mjs +315 -0
- package/src/infra-containers.mjs +100 -0
- package/src/infra-docker.mjs +267 -0
- package/src/infra-expr.mjs +509 -0
- package/src/infra-gha.mjs +350 -0
- package/src/infra-k8s.mjs +657 -0
- package/src/infra-terraform.mjs +499 -0
- package/src/infra-words.mjs +811 -0
- package/src/libraries.mjs +202 -0
- package/src/lift.mjs +48 -6
- package/src/meaning.d.mts +89 -0
- package/src/meaning.mjs +2544 -0
- package/src/model.d.mts +59 -12
- package/src/model.mjs +462 -80
- package/src/powershell.mjs +1361 -0
- package/src/read-repo-fs.mjs +29 -7
- package/src/read-repo.d.mts +5 -1
- package/src/read-repo.mjs +33 -7
- package/src/read.d.mts +21 -1
- package/src/read.mjs +1015 -42
- package/src/review.d.mts +35 -0
- package/src/review.mjs +671 -0
- package/src/rlang.mjs +1084 -0
- package/src/round-trip.d.mts +12 -0
- package/src/round-trip.mjs +174 -0
- package/src/runners/thunder-generate.mjs +56 -0
- package/src/runners/thunder-trace.cjs +284 -0
- package/src/runners/thunder_trace.py +599 -0
- package/src/running.d.mts +104 -0
- package/src/running.mjs +787 -0
- package/src/same.d.mts +1 -0
- package/src/same.mjs +24 -3
- package/src/shell.mjs +1212 -0
- package/src/sql.mjs +3 -2
- package/src/steps.d.mts +6 -1
- package/src/steps.mjs +1448 -86
- package/src/system.d.mts +12 -0
- package/src/system.mjs +845 -0
- package/src/things-langs.mjs +275 -0
- package/src/thunderize.mjs +3 -3
- package/src/visual.d.mts +5 -5
- package/src/visual.mjs +24 -3
- package/src/write-steps.d.mts +64 -0
- package/src/write-steps.mjs +1608 -0
- package/src/write.mjs +2 -1
- package/src/yaml.mjs +403 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// Common libraries, read as what they do. Most of what an app does is calls into well-known libraries (an ORM, an
|
|
2
|
+
// HTTP client, a cache, a payment service). Read by name alone they say nothing ("Calls find unique"); read with their
|
|
3
|
+
// arguments they say what happens: "Finds the user whose id is id". Each entry matches a call written the way the
|
|
4
|
+
// library's own documentation writes it, and only says what the call itself makes plain. Unknown calls are left to
|
|
5
|
+
// the general reader. Browser-safe, no dependencies.
|
|
6
|
+
|
|
7
|
+
const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_\-$]+/g, ' ').toLowerCase().trim();
|
|
8
|
+
const singular = (w) => w.replace(/ies$/, 'y').replace(/(ss|sh|ch|x)es$/, '$1').replace(/([^s])s$/, '$1');
|
|
9
|
+
const plural = (w) => (/(s|sh|ch|x)$/.test(w) ? `${w}es` : /[^aeiou]y$/.test(w) ? `${w.slice(0, -1)}ies` : `${w}s`);
|
|
10
|
+
const listWords = (xs) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')}${xs.length > 2 ? ',' : ''} and ${xs.at(-1)}`);
|
|
11
|
+
|
|
12
|
+
/** Split at top-level commas. */
|
|
13
|
+
function splitTop(text) {
|
|
14
|
+
const out = []; let d = 0, cur = '', q = null;
|
|
15
|
+
for (const c of String(text)) {
|
|
16
|
+
if (q) { cur += c; if (c === q) q = null; continue; }
|
|
17
|
+
if (c === '"' || c === "'" || c === '`') { q = c; cur += c; continue; }
|
|
18
|
+
if ('([{'.includes(c)) d++;
|
|
19
|
+
if (')]}'.includes(c)) d--;
|
|
20
|
+
if (c === ',' && d === 0) { out.push(cur.trim()); cur = ''; } else cur += c;
|
|
21
|
+
}
|
|
22
|
+
if (cur.trim()) out.push(cur.trim());
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
/** The text inside the outermost (…) after position `open`. */
|
|
26
|
+
function inside(text, open) {
|
|
27
|
+
for (let i = open, d = 0, q = null; i < text.length; i++) {
|
|
28
|
+
const c = text[i];
|
|
29
|
+
if (q) { if (c === q && text[i - 1] !== '\\') q = null; continue; }
|
|
30
|
+
if (c === '"' || c === "'" || c === '`') { q = c; continue; }
|
|
31
|
+
if (c === '(' || c === '{' || c === '[') d++;
|
|
32
|
+
else if ((c === ')' || c === '}' || c === ']') && --d === 0) return text.slice(open + 1, i);
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
/** A value in words: user.id -> "the user's id", 'paid' -> "\"paid\"", 3 -> "3". */
|
|
37
|
+
function valueWords(v) {
|
|
38
|
+
const t = String(v).trim().replace(/^\$/, '');
|
|
39
|
+
if (/^["'`]([^"'`]*)["'`]$/.test(t)) return `"${t.slice(1, -1)}"`;
|
|
40
|
+
if (/^-?\d+(\.\d+)?$/.test(t) || /^(true|false)$/i.test(t)) return /^true$/i.test(t) ? 'yes' : /^false$/i.test(t) ? 'no' : t;
|
|
41
|
+
if (/^(null|None|nil)$/i.test(t)) return 'empty';
|
|
42
|
+
// What the request carries: params[:email] (Rails), request.form['email'], req.body.email -> "the email it was sent".
|
|
43
|
+
let rq;
|
|
44
|
+
if ((rq = t.match(/^params\s*\[\s*[:'"]([\w]+)['"]?\s*\]$/)) || (rq = t.match(/^(?:req|request)\s*\.\s*(?:body|form|json|data)\s*(?:\.\s*(\w+)|\[\s*['"](\w+)['"]\s*\])$/))) return `the ${words(rq[1] || rq[2])} it was sent`;
|
|
45
|
+
if ((rq = t.match(/^(?:req|request)\s*\.\s*(?:query|params|args)\s*(?:\.\s*(\w+)|\[\s*['"](\w+)['"]\s*\]|\.get\(\s*['"](\w+)['"]\s*\))$/))) return `the ${words(rq[1] || rq[2] || rq[3])} in the address`;
|
|
46
|
+
const parts = t.split(/\.|->/).filter((p) => p && !/^(self|this)$/.test(p));
|
|
47
|
+
if (parts.length === 2 && /^[A-Za-z_]\w*$/.test(parts[0]) && /^[A-Za-z_]\w*$/.test(parts[1])) return `the ${words(parts[0])}'s ${words(parts[1])}`;
|
|
48
|
+
if (/^[A-Za-z_][\w.]*$/.test(t)) return words(parts.at(-1) ?? t);
|
|
49
|
+
return 'a worked-out value';
|
|
50
|
+
}
|
|
51
|
+
/** Conditions from an object literal or keyword arguments: { id, email: e } / id=x, email=e -> "whose id is id and email is e". */
|
|
52
|
+
function whoseFrom(text) {
|
|
53
|
+
const t = String(text || '').trim();
|
|
54
|
+
const body = /^\{/.test(t) ? inside(t, 0) ?? '' : t;
|
|
55
|
+
const parts = splitTop(body).map((p) => {
|
|
56
|
+
const kv = p.match(/^["']?([A-Za-z_]\w*)["']?\s*(?::|=>|=(?!=))\s*(.+)$/s);
|
|
57
|
+
if (kv) {
|
|
58
|
+
const v = kv[2].trim();
|
|
59
|
+
if (/^\{/.test(v)) return null; // nested operators ({ gt: 3 }) are not read here
|
|
60
|
+
return `${words(kv[1].replace(/__(\w+)$/, ''))} is ${valueWords(v)}`;
|
|
61
|
+
}
|
|
62
|
+
return /^[A-Za-z_]\w*$/.test(p) ? `${words(p)} is ${words(p)}` : null;
|
|
63
|
+
}).filter(Boolean);
|
|
64
|
+
return parts.length ? `whose ${parts.join(' and ')}` : '';
|
|
65
|
+
}
|
|
66
|
+
/** `where: { … }` inside a Prisma/Sequelize options object. */
|
|
67
|
+
function whereOf(args) {
|
|
68
|
+
const m = String(args).match(/\bwhere\s*:\s*\{/);
|
|
69
|
+
if (!m) return '';
|
|
70
|
+
return whoseFrom(`{${inside(args, m.index + m[0].length - 1) ?? ''}}`);
|
|
71
|
+
}
|
|
72
|
+
const URL_WORDS = (u) => {
|
|
73
|
+
const t = String(u || '').trim();
|
|
74
|
+
if (/^["'`]/.test(t)) return t.slice(1, -1).replace(/\$\{[^}]*\}/g, '…');
|
|
75
|
+
return /^[A-Za-z_][\w.]*$/.test(t) ? `the ${words(t.split('.').pop()).replace(/\burl\b/, 'URL')}` : 'an address worked out by the code';
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// Spring Data / Rails-style derived query names: findByEmailAndActive -> "whose email is … and active is …".
|
|
79
|
+
function derivedWhose(name, args) {
|
|
80
|
+
const m = name.match(/^(?:find|get|read|query|search|stream|count|exists|delete|remove)(?:All|First|Top\d*|One)?By(\w+)$/);
|
|
81
|
+
if (!m) return null;
|
|
82
|
+
const fields = m[1].split(/And|Or/).map((f) => words(f.replace(/(IgnoreCase|OrderBy\w*)$/, '')));
|
|
83
|
+
const vals = splitTop(args);
|
|
84
|
+
return `whose ${fields.map((f, i) => `${f} is ${vals[i] ? valueWords(vals[i]) : '…'}`).join(/Or/.test(m[1]) ? ' or ' : ' and ')}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Each entry: re on the whole call (after `await`), and say(match, call) -> { says, does }. */
|
|
88
|
+
const CATALOG = [
|
|
89
|
+
// ── HTTP clients ──
|
|
90
|
+
{ re: /^fetch\s*\(/, say: (m, c) => { const a = splitTop(inside(c, c.indexOf('(')) ?? ''); const method = (a[1]?.match(/method\s*:\s*["'`](\w+)/i) || [])[1]?.toUpperCase() ?? 'GET'; return { says: `Sends a ${method} request to ${URL_WORDS(a[0])}`, does: 'ask' }; } },
|
|
91
|
+
{ re: /^(?:axios|http|httpClient|client|api|ky|got|superagent|request)\s*\.\s*(get|post|put|patch|delete|head)\s*\(/i, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
92
|
+
{ re: /^(?:requests|httpx|session|self\.session|aiohttp\.ClientSession\(\))\s*\.\s*(get|post|put|patch|delete)\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
93
|
+
{ re: /^(?:_?httpClient|client|_client|HttpClient)\s*\.\s*(Get|Post|Put|Patch|Delete)(?:AsJson|FromJson|String)?Async\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
94
|
+
{ re: /^(?:restTemplate|webClient)\s*\.\s*(get|post|put|delete|patch)(?:ForObject|ForEntity)?\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
95
|
+
{ re: /^http\s*\.\s*(Get|Post|Head)\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
96
|
+
{ re: /^reqwest\s*::\s*get\s*\(/, say: (m, c) => ({ says: `Sends a GET request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
97
|
+
|
|
98
|
+
// ── Prisma ──
|
|
99
|
+
{ re: /^(?:this\.)?prisma\s*\.\s*(\w+)\s*\.\s*(findUnique|findUniqueOrThrow|findFirst|findFirstOrThrow|findMany|create|createMany|update|updateMany|upsert|delete|deleteMany|count|aggregate)\s*\(/, say: (m, c) => {
|
|
100
|
+
const thing = words(m[1]), args = inside(c, c.indexOf('(', m.index + m[0].length - 1)) ?? '', whose = whereOf(args);
|
|
101
|
+
const S = { findUnique: `Finds the ${thing} ${whose}`, findUniqueOrThrow: `Finds the ${thing} ${whose} (stops if there is none)`, findFirst: `Finds the first ${thing} ${whose}`, findFirstOrThrow: `Finds the first ${thing} ${whose} (stops if there is none)`, findMany: `Finds the ${plural(thing)} ${whose}`, create: `Saves a new ${thing}`, createMany: `Saves new ${plural(thing)}`, update: `Changes the ${thing} ${whose}`, updateMany: `Changes the ${plural(thing)} ${whose}`, upsert: `Saves the ${thing} ${whose} (adds it if it is new)`, delete: `Removes the ${thing} ${whose}`, deleteMany: `Removes the ${plural(thing)} ${whose}`, count: `Counts the ${plural(thing)} ${whose}`, aggregate: `Adds up the ${plural(thing)} ${whose}` };
|
|
102
|
+
return { says: S[m[2]].trim(), does: /^(find|count|aggregate)/.test(m[2]) ? 'find' : 'save' };
|
|
103
|
+
} },
|
|
104
|
+
// ── Mongoose / Sequelize / Eloquent / ActiveRecord / Django (Model.method) ──
|
|
105
|
+
{ re: /^([A-Z]\w*)\s*\.\s*(findById|findByPk|find_by_id)\s*\(/, say: (m, c) => ({ says: `Finds the ${words(m[1])} whose id is ${valueWords(splitTop(inside(c, c.indexOf('(')) ?? '')[0] ?? '…')}`, does: 'find' }) },
|
|
106
|
+
{ re: /^([A-Z]\w*)\s*(?:\.|::)\s*find\s*\(/, say: (m, c) => { const a = splitTop(inside(c, c.indexOf('(')) ?? ''); return a.length === 1 && !/^\{/.test(a[0]) ? { says: `Finds the ${words(m[1])} whose id is ${valueWords(a[0])}`, does: 'find' } : { says: `Finds the ${plural(words(m[1]))} ${whoseFrom(a[0] ?? '')}`.trim(), does: 'find' }; } },
|
|
107
|
+
{ re: /^([A-Z]\w*)\s*\.\s*(findOne|find_by|findFirst)\s*\(/, say: (m, c) => ({ says: `Finds the ${words(m[1])} ${whereOf(inside(c, c.indexOf('(')) ?? '') || whoseFrom(inside(c, c.indexOf('(')) ?? '')}`.trim(), does: 'find' }) },
|
|
108
|
+
{ re: /^([A-Z]\w*)\s*(?:\.|::)\s*where\s*\(\s*["']([\w.]+)["']\s*,\s*(?:["'](?:=|==)["']\s*,\s*)?([^)]+?)\s*\)\s*(?:->|\.)\s*(first|get|firstOrFail|count|exists)\s*\(\s*\)$/, say: (m) => ({ says: `${{ first: 'Finds the first', firstOrFail: 'Finds the first', get: 'Finds the', count: 'Counts the', exists: 'Checks whether there are' }[m[4]]} ${m[4] === 'first' || m[4] === 'firstOrFail' ? words(m[1]) : plural(words(m[1]))} whose ${words(m[2])} is ${valueWords(m[3])}${m[4] === 'firstOrFail' ? ' (stops if there is none)' : ''}`, does: 'find' }) },
|
|
109
|
+
{ re: /^([A-Z]\w*)\s*\.\s*(findAll|where|all|filter)\s*\(/, say: (m, c) => ({ says: `Finds the ${plural(words(m[1]))} ${whereOf(inside(c, c.indexOf('(')) ?? '') || whoseFrom(inside(c, c.indexOf('(')) ?? '')}`.trim(), does: 'find' }) },
|
|
110
|
+
// A model class (not a language built-in: Object.create makes an object, it saves nothing).
|
|
111
|
+
{ re: /^(?!(?:Object|Array|Promise|Symbol|Reflect|Proxy|JSON|Math|Date|Error|URL|String|Number|Map|Set|WeakMap|Stream|Path|Paths|File|Files|Thread|Task|Channel|Pattern|List|Collections|Optional|Executors|Duration|Instant|UUID|Uri|Logger|Http\w*|Request|Response|Headers|Blob|Intl|React|Vue|Ember|Ext|Class)\b)([A-Z]\w*)\s*(?:\.|::)\s*(create|insert|insertMany|bulkCreate|create!)\s*\(/, say: (m, c) => { const w = whoseFrom(inside(c, c.indexOf('(')) ?? '').replace(/^whose /, ''); return { says: `Saves a new ${words(m[1])}${w ? ` with ${w.replace(/ is /g, ' ').replace(/ and /g, ', ')}` : ''}`, does: 'save' }; } },
|
|
112
|
+
{ re: /^([A-Z]\w*)\s*\.\s*(updateOne|updateMany|findByIdAndUpdate|findOneAndUpdate|update_all)\s*\(/, say: (m) => ({ says: `Changes ${/Many|all/.test(m[2]) ? `the ${plural(words(m[1]))}` : `a ${words(m[1])}`}`, does: 'save' }) },
|
|
113
|
+
{ re: /^([A-Z]\w*)\s*\.\s*(deleteOne|deleteMany|findByIdAndDelete|destroy|destroy_all|delete_all)\s*\(/, say: (m) => ({ says: `Removes ${/Many|all/.test(m[2]) ? `the ${plural(words(m[1]))}` : `a ${words(m[1])}`}`, does: 'save' }) },
|
|
114
|
+
{ re: /^([A-Z]\w*)\s*\.\s*(countDocuments|count)\s*\(/, say: (m) => ({ says: `Counts the ${plural(words(m[1]))}`, does: 'find' }) },
|
|
115
|
+
{ re: /^([A-Z]\w*)\.objects\s*\.\s*(get|filter|exclude|create|all|count|get_or_create|update_or_create)\s*\(/, say: (m, c) => {
|
|
116
|
+
const thing = words(m[1]), args = inside(c, c.indexOf('(', m.index + m[0].length - 1)) ?? '', whose = whoseFrom(args);
|
|
117
|
+
const S = { get: `Finds the ${thing} ${whose}`, filter: `Finds the ${plural(thing)} ${whose}`, exclude: `Finds the ${plural(thing)} except those ${whose}`, create: `Saves a new ${thing}`, all: `Finds all the ${plural(thing)}`, count: `Counts the ${plural(thing)}`, get_or_create: `Finds the ${thing} ${whose}, or saves a new one`, update_or_create: `Changes the ${thing} ${whose}, or saves a new one` };
|
|
118
|
+
return { says: S[m[2]].trim(), does: /^(get|filter|exclude|all|count)$/.test(m[2]) ? 'find' : 'save' };
|
|
119
|
+
} },
|
|
120
|
+
// ── SQLAlchemy ──
|
|
121
|
+
{ re: /^(?:self\.)?(?:db\.)?session\s*\.\s*query\s*\(\s*([A-Z]\w*)\s*\)(.*)$/, say: (m) => { const f = m[2].match(/\.filter(?:_by)?\s*\((.*?)\)\s*\.\s*(first|one|all|count|one_or_none|scalar)\s*\(\s*\)\s*$/); const thing = words(m[1]); const cond = f ? f[1].replace(/\b[A-Z]\w*\.(\w+)\s*==\s*/g, '$1=') : ''; const whose = whoseFrom(cond); return { says: f ? ({ first: `Finds the first ${thing} ${whose}`, one: `Finds the ${thing} ${whose}`, one_or_none: `Finds the ${thing} ${whose}, if there is one`, all: `Finds the ${plural(thing)} ${whose}`, count: `Counts the ${plural(thing)} ${whose}`, scalar: `Finds the ${thing} ${whose}` }[f[2]]).trim() : `Finds ${plural(thing)}`, does: 'find' }; } },
|
|
122
|
+
{ re: /^(?:self\.)?(?:db\.)?session\s*\.\s*(add|add_all|delete|merge)\s*\(\s*([\w.]+)/, say: (m) => ({ says: `${{ add: 'Adds', add_all: 'Adds', delete: 'Marks', merge: 'Adds' }[m[1]]} ${valueWords(m[2])} ${m[1] === 'delete' ? 'to be removed' : 'to be saved'}`, does: 'save' }) },
|
|
123
|
+
{ re: /^(?:self\.)?(?:db\.)?session\s*\.\s*commit\s*\(\s*\)$/, say: () => ({ says: 'Saves the changes to the database', does: 'save' }) },
|
|
124
|
+
{ re: /^(?:self\.)?(?:db\.)?session\s*\.\s*rollback\s*\(\s*\)$/, say: () => ({ says: 'Throws away the unsaved changes', does: 'save' }) },
|
|
125
|
+
{ re: /^(?:self\.)?(?:db\.)?session\s*\.\s*(?:get)\s*\(\s*([A-Z]\w*)\s*,\s*(.+)\)$/, say: (m) => ({ says: `Finds the ${words(m[1])} whose id is ${valueWords(m[2])}`, does: 'find' }) },
|
|
126
|
+
// ── Spring Data / JPA / repositories ──
|
|
127
|
+
{ re: /^(?:this\.)?(\w*[Rr]epo(?:sitory)?)\s*\.\s*(findById|getById|getReferenceById|existsById|deleteById|findAll|save|saveAll|delete|deleteAll|count|(?:find|get|read|query|search|stream|count|exists|delete|remove)(?:All|First|Top\d*|One)?By\w+)\s*\(/, say: (m, c) => {
|
|
128
|
+
const thing = words(m[1].replace(/^_/, '').replace(/[Rr]epo(?:sitory)?$/, '')) || 'item', args = inside(c, c.indexOf('(', m.index + m[0].length - 1)) ?? '';
|
|
129
|
+
const derived = derivedWhose(m[2], args);
|
|
130
|
+
if (derived) return { says: `${/^count/.test(m[2]) ? 'Counts' : /^exists/.test(m[2]) ? 'Checks whether there is a' : /^(delete|remove)/.test(m[2]) ? 'Removes the' : 'Finds the'} ${/^count/.test(m[2]) ? plural(thing) : thing} ${derived}`.replace('Counts ', 'Counts the ').replace('Checks whether there is a ', 'Checks whether there is a '), does: /^(delete|remove)/.test(m[2]) ? 'save' : 'find' };
|
|
131
|
+
const S = { findById: `Finds the ${thing} whose id is ${valueWords(args)}`, getById: `Finds the ${thing} whose id is ${valueWords(args)}`, getReferenceById: `Finds the ${thing} whose id is ${valueWords(args)}`, existsById: `Checks whether there is a ${thing} whose id is ${valueWords(args)}`, deleteById: `Removes the ${thing} whose id is ${valueWords(args)}`, findAll: `Finds all the ${plural(thing)}`, save: `Saves ${valueWords(args)}`, saveAll: `Saves ${valueWords(args)}`, delete: `Removes ${valueWords(args)}`, deleteAll: `Removes all the ${plural(thing)}`, count: `Counts the ${plural(thing)}` };
|
|
132
|
+
return { says: S[m[2]], does: /^(find|get|exists|count)/.test(m[2]) ? 'find' : 'save' };
|
|
133
|
+
} },
|
|
134
|
+
// ── Entity Framework (C#) ──
|
|
135
|
+
{ re: /^(?:_?(?:context|db|dbContext|ctx))\s*\.\s*(\w+)\s*\.\s*(Add|AddAsync|Remove|Update|AddRange|RemoveRange)\s*\(\s*([\w.]+)/, say: (m) => ({ says: `${/Add/.test(m[2]) ? 'Adds' : /Remove/.test(m[2]) ? 'Marks' : 'Marks'} ${valueWords(m[3])} ${/Add/.test(m[2]) ? `to be saved in ${words(m[1])}` : /Remove/.test(m[2]) ? 'to be removed' : 'as changed'}`, does: 'save' }) },
|
|
136
|
+
{ re: /^(?:_?(?:context|db|dbContext|ctx))\s*\.\s*SaveChanges(?:Async)?\s*\(/, say: () => ({ says: 'Saves the changes to the database', does: 'save' }) },
|
|
137
|
+
{ re: /^(?:_?(?:context|db|dbContext|ctx))\s*\.\s*(\w+)\s*\.\s*FindAsync\s*\(\s*(.+?)\s*\)$|^(?:_?(?:context|db|dbContext|ctx))\s*\.\s*(\w+)\s*\.\s*Find\s*\(\s*(.+?)\s*\)$/, say: (m) => ({ says: `Finds the ${singular(words(m[1] ?? m[3]))} whose id is ${valueWords(m[2] ?? m[4])}`, does: 'find' }) },
|
|
138
|
+
{ re: /^(?:_?(?:context|db|dbContext|ctx))\s*\.\s*(\w+)\s*(?:\.\s*(?:Include|AsNoTracking)\s*\([^)]*\)\s*)*\.\s*(Where|FirstOrDefault(?:Async)?|First(?:Async)?|SingleOrDefault(?:Async)?|Single(?:Async)?|Any(?:Async)?|Count(?:Async)?|ToList(?:Async)?)\s*\(\s*(?:\w+\s*=>\s*)?(.*?)\)/, say: (m) => {
|
|
139
|
+
const thing = words(m[1]), cond = (m[3] || '').replace(/\b\w+\.(\w+)\s*==\s*/g, '$1=').replace(/&&/g, ',');
|
|
140
|
+
const whose = cond ? whoseFrom(cond) : '';
|
|
141
|
+
const v = m[2].replace(/Async$/, '');
|
|
142
|
+
const S = { Where: `Finds the ${thing} ${whose}`, FirstOrDefault: `Finds the first ${singular(thing)} ${whose}, if there is one`, First: `Finds the first ${singular(thing)} ${whose}`, SingleOrDefault: `Finds the ${singular(thing)} ${whose}, if there is one`, Single: `Finds the ${singular(thing)} ${whose}`, Any: `Checks whether there are ${thing} ${whose}`, Count: `Counts the ${thing} ${whose}`, ToList: `Finds all the ${thing}` };
|
|
143
|
+
return { says: S[v].replace(/\s+,/, ',').trim(), does: 'find' };
|
|
144
|
+
} },
|
|
145
|
+
// ── GORM / database/sql (Go) ──
|
|
146
|
+
{ re: /^(?:\w+\.)?(?:db|DB|tx|gormDB)\s*\.\s*(First|Find|Take|Last)\s*\(\s*&?(\w+)(?:\s*,\s*(.+))?\)/, say: (m) => ({ says: `Finds ${m[1] === 'Find' ? 'the' : `the ${m[1] === 'Last' ? 'last' : 'first'}`} ${words(m[2])}${m[3] ? ` whose id is ${valueWords(m[3])}` : ''}`, does: 'find' }) },
|
|
147
|
+
{ re: /^(?:\w+\.)?(?:db|DB|tx)\s*\.\s*(Create|Save|Delete|Updates?)\s*\(\s*&?(\w+)/, say: (m) => ({ says: `${{ Create: 'Saves a new', Save: 'Saves', Delete: 'Removes', Update: 'Changes', Updates: 'Changes' }[m[1]]} ${words(m[2])}`, does: 'save' }) },
|
|
148
|
+
{ re: /^(?:\w+\.)?(?:db|DB|tx|conn|pool)\s*\.\s*(QueryRow|Query|QueryContext|QueryRowContext|Exec|ExecContext)\s*\(\s*(?:ctx\s*,\s*)?["'`]\s*(\w+)\s+(?:\*|[\w, ]+\s+)?(?:FROM\s+|INTO\s+)?(\w+)?/i, say: (m) => { const verb = m[2].toUpperCase(); const t = m[3] ? words(m[3]) : 'the database'; return { says: verb === 'SELECT' ? `Finds ${/Row/.test(m[1]) ? 'one row' : 'rows'} in ${t}` : verb === 'INSERT' ? `Saves a new row in ${t}` : verb === 'UPDATE' ? `Changes rows in ${t}` : verb === 'DELETE' ? `Removes rows from ${t}` : 'Runs a database query', does: verb === 'SELECT' ? 'find' : 'save' }; } },
|
|
149
|
+
// ── Laravel query builder ──
|
|
150
|
+
{ re: /^DB\s*::\s*table\s*\(\s*["']([\w.]+)["']\s*\)(.*)$/, say: (m) => ({ says: /->(insert|insertGetId)\(/.test(m[2]) ? `Saves a new row in ${words(m[1])}` : /->update\(/.test(m[2]) ? `Changes rows in ${words(m[1])}` : /->delete\(/.test(m[2]) ? `Removes rows from ${words(m[1])}` : `Finds rows in ${words(m[1])}`, does: /->(insert|update|delete)/.test(m[2]) ? 'save' : 'find' }) },
|
|
151
|
+
// ── Saving an object you already have (ORM instance) ──
|
|
152
|
+
{ re: /^(\$?[a-z_]\w*)\s*(?:\.|->)\s*(save|save!|delete|destroy|update)\s*\(\s*\)$/, say: (m) => ({ says: `${{ save: 'Saves', 'save!': 'Saves', delete: 'Removes', destroy: 'Removes', update: 'Saves' }[m[2]]} ${words(m[1])}`, does: 'save' }) },
|
|
153
|
+
|
|
154
|
+
// ── Caches ──
|
|
155
|
+
{ re: /^(?:this\.)?(?:redis|cache|client|redisClient|_cache)\s*\.\s*(get|set|setex|del|exists|expire|incr|hget|hset)\s*\(\s*(.*)$/i, say: (m, c) => { const a = splitTop(inside(c, c.indexOf('(')) ?? ''); const k = a[0] ? valueWords(a[0]) : 'a key'; const S = { get: `Reads ${k} from the cache`, set: `Keeps ${k} in the cache`, setex: `Keeps ${k} in the cache for a while`, del: `Removes ${k} from the cache`, exists: `Checks whether ${k} is in the cache`, expire: `Sets when ${k} leaves the cache`, incr: `Adds 1 to ${k} in the cache`, hget: `Reads ${k} from the cache`, hset: `Keeps ${k} in the cache` }; return { says: S[m[1].toLowerCase()], does: /^(get|exists|hget)$/i.test(m[1]) ? 'find' : 'save' }; } },
|
|
156
|
+
|
|
157
|
+
// ── Sign-in tokens and passwords ──
|
|
158
|
+
{ re: /^jwt\s*\.\s*(sign|encode)\s*\(/, say: () => ({ says: 'Makes a sign-in token', does: 'calculate' }) },
|
|
159
|
+
{ re: /^jwt\s*\.\s*(verify|decode)\s*\(/, say: (m) => ({ says: m[1] === 'verify' ? 'Checks the sign-in token (stops if it is not valid)' : 'Reads the sign-in token', does: 'check' }) },
|
|
160
|
+
{ re: /^bcrypt\s*\.\s*(hash|hashSync|hashpw|generate_password_hash)\s*\(|^generate_password_hash\s*\(/, say: () => ({ says: 'Scrambles the password so it can be stored safely', does: 'calculate' }) },
|
|
161
|
+
{ re: /^bcrypt\s*\.\s*(compare|compareSync|checkpw)\s*\(|^check_password_hash\s*\(/, say: () => ({ says: 'Checks the password against its scrambled copy', does: 'check' }) },
|
|
162
|
+
|
|
163
|
+
// ── Payments, email, queues ──
|
|
164
|
+
{ re: /^(?:this\.)?stripe\s*\.\s*(\w+)\s*\.\s*(create|retrieve|update|list|del|cancel|confirm|capture)\s*\(/, say: (m) => ({ says: `${{ create: 'Creates', retrieve: 'Gets', update: 'Changes', list: 'Lists', del: 'Removes', cancel: 'Cancels', confirm: 'Confirms', capture: 'Captures' }[m[2]]} a Stripe ${singular(words(m[1]))}`, does: 'ask' }) },
|
|
165
|
+
{ re: /^(?:\w+\.)?(?:transporter|mailer|sgMail|mail|resend\.emails|ses)\s*\.\s*(sendMail|send|send_mail|send_email)\s*\(/, say: () => ({ says: 'Sends an email', does: 'send' }) },
|
|
166
|
+
{ re: /^send_mail\s*\(/, say: () => ({ says: 'Sends an email', does: 'send' }) },
|
|
167
|
+
{ re: /^(\w+)\s*\.\s*(delay|apply_async)\s*\(/, say: (m) => ({ says: `Starts ${words(m[1])} in the background`, does: 'send' }) },
|
|
168
|
+
{ re: /^(?:\w+\.)?(?:queue|producer|channel)\s*\.\s*(add|send|publish|enqueue|basic_publish|sendMessage)\s*\(/, say: () => ({ says: 'Puts a message on the queue', does: 'send' }) },
|
|
169
|
+
|
|
170
|
+
// ── JSON, files, time ──
|
|
171
|
+
{ re: /^JSON\s*\.\s*parse\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords(m[1])} as JSON`, does: 'calculate' }) },
|
|
172
|
+
{ re: /^JSON\s*\.\s*stringify\s*\(\s*([^,]+)/, say: (m) => ({ says: `Turns ${valueWords(m[1])} into JSON text`, does: 'calculate' }) },
|
|
173
|
+
{ re: /^json\s*\.\s*(loads|load)\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords(m[2])} as JSON`, does: 'calculate' }) },
|
|
174
|
+
{ re: /^json\s*\.\s*(dumps|dump)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Turns ${valueWords(m[2])} into JSON text`, does: 'calculate' }) },
|
|
175
|
+
{ re: /^json\s*\.\s*Marshal\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Turns ${valueWords(m[1])} into JSON`, does: 'calculate' }) },
|
|
176
|
+
{ re: /^json\s*\.\s*Unmarshal\s*\(\s*[^,]+,\s*&?(\w+)\s*\)$/, say: (m) => ({ says: `Reads the JSON into ${words(m[1])}`, does: 'calculate' }) },
|
|
177
|
+
{ re: /^json\s*\.\s*NewDecoder\s*\(\s*r\.Body\s*\)\s*\.\s*Decode\s*\(\s*&?(\w+)\s*\)$/, say: (m) => ({ says: `Reads what it was sent into ${words(m[1])}`, does: 'calculate' }) },
|
|
178
|
+
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(readFile|readFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Reads the file ${URL_WORDS(m[2])}`, does: 'find' }) },
|
|
179
|
+
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(writeFile|writeFileSync|appendFile|appendFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `${/append/.test(m[1]) ? 'Adds to' : 'Writes'} the file ${URL_WORDS(m[2])}`, does: 'save' }) },
|
|
180
|
+
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(unlink|unlinkSync|rm|rmSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Removes the file ${URL_WORDS(m[2])}`, does: 'save' }) },
|
|
181
|
+
{ re: /^(?:Date\.now|datetime\.now|datetime\.utcnow|time\.Now|DateTime\.Now|DateTime\.UtcNow|Instant\.now|LocalDateTime\.now|Time\.now)\s*\(?\s*\)?$/, say: () => ({ says: 'the current time', does: 'calculate', value: true }) },
|
|
182
|
+
];
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Read a call with the library catalog. `expr` is the call as written (an `await` in front is fine). Gives
|
|
186
|
+
* { says, does } (does: find, save, ask, send, check, calculate), or null for calls the catalog does not know.
|
|
187
|
+
*/
|
|
188
|
+
export function sayLibraryCall(expr) {
|
|
189
|
+
const c = String(expr).trim().replace(/^await\s+/, '').replace(/^(?:return\s+)/, '').replace(/[;]\s*$/, '').replace(/\.(?:exec|lean|then\(.*\)|unwrap\(\)|expect\(.*\)|get\(\))\s*\(\s*\)\s*$/, '').replace(/\s*\?$/, '');
|
|
190
|
+
for (const entry of CATALOG) {
|
|
191
|
+
const m = c.match(entry.re);
|
|
192
|
+
if (!m) continue;
|
|
193
|
+
try {
|
|
194
|
+
const r = entry.say(m, c);
|
|
195
|
+
// A yes/no field reads as a mark: "whose published is yes" -> "marked published".
|
|
196
|
+
if (r?.says && !/\b(undefined|null)\b/.test(r.says)) return { ...r, says: r.says.replace(/\bwhose (\w+(?: \w+)?) is yes\b/g, 'marked $1').replace(/\bwhose (\w+(?: \w+)?) is no\b/g, 'not marked $1').replace(/ and (\w+(?: \w+)?) is yes\b/g, ' and marked $1').replace(/\s+/g, ' ').replace(/\s+,/g, ',').trim() };
|
|
197
|
+
} catch { /* a call the entry cannot read stays with the general reader */ }
|
|
198
|
+
}
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export const LIBRARY_CATALOG_SIZE = CATALOG.length;
|
package/src/lift.mjs
CHANGED
|
@@ -17,7 +17,23 @@ const SEMANTIC_TYPES = new Set([
|
|
|
17
17
|
]);
|
|
18
18
|
const SENSITIVE = /password|token|jwt|secret|payment|credential|ssn|pii|email/i;
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
// The line an index is on. Line starts are found once per source (the last few are kept), then searched: slicing and
|
|
21
|
+
// splitting the source for every match was quadratic on large files.
|
|
22
|
+
const LINE_STARTS = new Map();
|
|
23
|
+
const lineOf = (source, index) => {
|
|
24
|
+
let starts = LINE_STARTS.get(source);
|
|
25
|
+
if (!starts) {
|
|
26
|
+
starts = [0];
|
|
27
|
+
for (let i = source.indexOf('\n'); i >= 0; i = source.indexOf('\n', i + 1)) starts.push(i + 1);
|
|
28
|
+
if (LINE_STARTS.size > 8) LINE_STARTS.delete(LINE_STARTS.keys().next().value);
|
|
29
|
+
LINE_STARTS.set(source, starts);
|
|
30
|
+
}
|
|
31
|
+
// (An index past the end counts the lines before it, as slice + split did.)
|
|
32
|
+
const at = Math.min(Math.max(index, 0), source.length);
|
|
33
|
+
let lo = 0, hi = starts.length - 1;
|
|
34
|
+
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= at) lo = mid; else hi = mid - 1; }
|
|
35
|
+
return lo + 1;
|
|
36
|
+
};
|
|
21
37
|
|
|
22
38
|
// ── Seeded lift (OT's intent-ir-v1 grounding) ────────────────────────────────
|
|
23
39
|
// OT passes { seeds } so the lifted .intent references OT's EXACT node ids instead
|
|
@@ -422,6 +438,25 @@ export function extractFactsKotlin(source, file = 'input.kt') {
|
|
|
422
438
|
return { schemaVersion: IR_SCHEMA_VERSION, sourceLanguage: 'kotlin', sourceRoot: file, functions, tests, errors };
|
|
423
439
|
}
|
|
424
440
|
|
|
441
|
+
// ── Swift adapter (func name(label name: Type) -> Ret, XCTest test* / @Test, Error types) ───────────
|
|
442
|
+
export function extractFactsSwift(source, file = 'input.swift') {
|
|
443
|
+
let m; const functions = []; const tests = []; const seen = new Set();
|
|
444
|
+
const xctest = /:\s*XCTestCase\b/.test(source);
|
|
445
|
+
const fnRe = /(@Test\b[^\n]*\n\s*)?\bfunc\s+(?:`([^`]+)`|([A-Za-z_]\w*))\s*(?:<[^>\n]*>)?\s*\(([^)]*)\)[ \t]*(?:async[ \t]+)?(?:(?:re)?throws[ \t]+)?(?:->[ \t]*([^{\n]+))?/g;
|
|
446
|
+
while ((m = fnRe.exec(source))) {
|
|
447
|
+
const name = m[2] || m[3];
|
|
448
|
+
if (m[1] || (xctest && /^test/.test(name))) { if (!tests.some((t) => t.name === name)) tests.push({ name, file, line: lineOf(source, m.index + (m[1] || '').length) }); continue; }
|
|
449
|
+
if (seen.has(name)) continue; seen.add(name);
|
|
450
|
+
const parameters = splitTopLevel(m[4] || '', ',').map((p) => p.trim()).filter(Boolean).map((p) => { const q = p.replace(/=.*$/, '').match(/^(?:\w+\s+)?(\w+)\s*:\s*(.+)$/); return q ? { name: q[1], type: q[2].trim() } : { name: p, type: null }; });
|
|
451
|
+
functions.push({ name, file, line: lineOf(source, m.index), parameters, returnType: m[5] ? m[5].trim() : null, evidence: [{ kind: 'func', file, line: lineOf(source, m.index) }] });
|
|
452
|
+
}
|
|
453
|
+
const errors = []; const addErr = addErrOf(errors, new Set(), { _src: source, _file: file });
|
|
454
|
+
let mm; const ce = /\b(?:enum|struct|class)\s+(\w+)\s*:\s*(?:[\w, ]*\b)?(?:Error|LocalizedError)\b/g; while ((mm = ce.exec(source))) addErr(mm[1], mm.index);
|
|
455
|
+
// Vapor's Abort is an HTTP response (Fails with 404 Not Found), read as a step, not an error type.
|
|
456
|
+
const th = /\bthrow\s+([A-Z]\w*)\s*[.(]/g; while ((mm = th.exec(source))) if (mm[1] !== 'Abort') addErr(mm[1], mm.index);
|
|
457
|
+
return { schemaVersion: IR_SCHEMA_VERSION, sourceLanguage: 'swift', sourceRoot: file, functions, tests, errors };
|
|
458
|
+
}
|
|
459
|
+
|
|
425
460
|
// ── Scala adapter (def name(p: Type): Ret, ScalaTest, *Exception) ─────────────
|
|
426
461
|
export function extractFactsScala(source, file = 'input.scala') {
|
|
427
462
|
let m; const functions = []; const tests = []; const seen = new Set();
|
|
@@ -470,7 +505,9 @@ const ADAPTERS = {
|
|
|
470
505
|
java: extractFactsJava,
|
|
471
506
|
csharp: extractFactsCSharp, cs: extractFactsCSharp, 'c#': extractFactsCSharp,
|
|
472
507
|
go: extractFactsGo, golang: extractFactsGo,
|
|
473
|
-
cpp: extractFactsCpp, 'c++': extractFactsCpp,
|
|
508
|
+
cpp: extractFactsCpp, 'c++': extractFactsCpp, cc: extractFactsCpp,
|
|
509
|
+
c: (source, file) => ({ ...extractFactsCpp(source, file), sourceLanguage: 'c' }), h: (source, file) => ({ ...extractFactsCpp(source, file), sourceLanguage: 'c' }),
|
|
510
|
+
swift: extractFactsSwift,
|
|
474
511
|
php: extractFactsPhp,
|
|
475
512
|
ruby: extractFactsRuby, rb: extractFactsRuby,
|
|
476
513
|
kotlin: extractFactsKotlin, kt: extractFactsKotlin, kts: extractFactsKotlin,
|
|
@@ -484,12 +521,12 @@ export function extractFacts(source, language, file) {
|
|
|
484
521
|
return adapter ? adapter(String(source), file || `input.${LANG_EXT[key] || 'txt'}`) : null;
|
|
485
522
|
}
|
|
486
523
|
|
|
487
|
-
export const SUPPORTED_LANGUAGES = ['typescript', 'javascript', 'python', 'java', 'csharp', 'go', 'rust', 'cpp', 'php', 'ruby', 'perl', 'kotlin', 'scala', 'elixir'];
|
|
524
|
+
export const SUPPORTED_LANGUAGES = ['typescript', 'javascript', 'python', 'java', 'csharp', 'go', 'rust', 'c', 'cpp', 'swift', 'php', 'ruby', 'perl', 'kotlin', 'scala', 'elixir'];
|
|
488
525
|
const DYNAMIC_LANGUAGES = new Set(['perl', 'javascript', 'python', 'ruby', 'php', 'elixir']);
|
|
489
526
|
|
|
490
527
|
const LANG_DISPLAY = {
|
|
491
528
|
typescript: 'TypeScript', javascript: 'JavaScript', python: 'Python', java: 'Java',
|
|
492
|
-
csharp: 'C#', go: 'Go', rust: 'Rust', cpp: 'C++', php: 'PHP', ruby: 'Ruby', perl: 'Perl',
|
|
529
|
+
csharp: 'C#', go: 'Go', rust: 'Rust', c: 'C', cpp: 'C++', swift: 'Swift', php: 'PHP', ruby: 'Ruby', perl: 'Perl',
|
|
493
530
|
kotlin: 'Kotlin', scala: 'Scala', elixir: 'Elixir',
|
|
494
531
|
};
|
|
495
532
|
|
|
@@ -635,13 +672,18 @@ export function languageForFile(file) {
|
|
|
635
672
|
if (/\.java$/i.test(file)) return 'java';
|
|
636
673
|
if (/\.cs$/i.test(file)) return 'csharp';
|
|
637
674
|
if (/\.go$/i.test(file)) return 'go';
|
|
638
|
-
if (/\.
|
|
675
|
+
if (/\.c$/i.test(file)) return 'c';
|
|
676
|
+
if (/\.(cpp|cc|cxx|c\+\+|hpp|hh|hxx|h)$/i.test(file)) return 'cpp'; // a .h is C or C++: the reader decides by its content
|
|
677
|
+
if (/\.swift$/i.test(file)) return 'swift';
|
|
639
678
|
if (/\.php$/i.test(file)) return 'php';
|
|
640
679
|
if (/\.rb$/i.test(file)) return 'ruby';
|
|
641
680
|
if (/\.kts?$/i.test(file)) return 'kotlin';
|
|
642
681
|
if (/\.(scala|sc)$/i.test(file)) return 'scala';
|
|
643
682
|
if (/\.exs?$/i.test(file)) return 'elixir';
|
|
644
683
|
if (/\.(mjs|cjs|jsx?)$/i.test(file)) return 'javascript';
|
|
684
|
+
if (/\.r$/i.test(file)) return 'r';
|
|
685
|
+
if (/\.(sh|bash|zsh|ksh)$/i.test(file)) return 'shell';
|
|
686
|
+
if (/\.(ps1|psm1)$/i.test(file)) return 'powershell';
|
|
645
687
|
return 'typescript';
|
|
646
688
|
}
|
|
647
689
|
|
|
@@ -725,7 +767,7 @@ export function liftRepo(files, { language } = {}) {
|
|
|
725
767
|
// Default source file extension per language (for accurate source-map evidence in the draft).
|
|
726
768
|
const LANG_EXT = {
|
|
727
769
|
typescript: 'ts', javascript: 'js', python: 'py', java: 'java', csharp: 'cs',
|
|
728
|
-
go: 'go', rust: 'rs', cpp: 'cpp', php: 'php', ruby: 'rb', perl: 'pl',
|
|
770
|
+
go: 'go', rust: 'rs', c: 'c', cpp: 'cpp', swift: 'swift', php: 'php', ruby: 'rb', perl: 'pl',
|
|
729
771
|
kotlin: 'kt', scala: 'scala', elixir: 'ex',
|
|
730
772
|
};
|
|
731
773
|
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// thunder-expr-v1: the meaning model underneath Thunder's words (see src/meaning.mjs).
|
|
2
|
+
export const EXPR_SCHEMA: 'thunder-expr-v1';
|
|
3
|
+
export const RENDER_LANGUAGES: string[];
|
|
4
|
+
|
|
5
|
+
/** A literal value, exactly as the code has it: `value` is the decoded value, `raw` its spelling. */
|
|
6
|
+
export interface ExprLiteral { kind: 'literal'; type: 'number' | 'text' | 'bool' | 'null' | 'char' | 'regex' | 'symbol'; value: unknown; raw: string; bytes?: true; flags?: string; /** Text with parts filled in at run time that are kept as written (C# $"…", Kotlin "$x", Ruby "#{x}"). */ interpolated?: true }
|
|
7
|
+
/** Text with values in it: `hello ${name}`, f"{name!r}". Parts are text or { expr, conv?, format? }. */
|
|
8
|
+
export interface ExprTemplate { kind: 'template'; parts: (string | { expr: Expr; conv?: string; format?: string; selfDoc?: true })[]; raw: string; form?: 'f'; tag?: Expr }
|
|
9
|
+
/** A block of statements: the step's own children (a lambda's body, a method in an object). */
|
|
10
|
+
export interface ExprBlock { kind: 'block' }
|
|
11
|
+
|
|
12
|
+
/** An expression or statement tree. Every node has `kind`; what is not understood is `{ kind: 'code', text }`. */
|
|
13
|
+
export type Expr =
|
|
14
|
+
| { kind: 'code'; text: string }
|
|
15
|
+
| { kind: 'name'; name: string; typeArgs?: string }
|
|
16
|
+
| ExprLiteral | ExprTemplate
|
|
17
|
+
| { kind: 'member'; object: Expr; property: string; optional?: true; static?: true; typeArgs?: string }
|
|
18
|
+
| { kind: 'index'; object: Expr; index: Expr; optional?: true }
|
|
19
|
+
| { kind: 'slice'; start?: Expr; end?: Expr; step?: Expr }
|
|
20
|
+
| { kind: 'call'; callee: Expr; args: Expr[]; new?: true; optional?: true; typeArgs?: string; parens?: false; init?: { key?: Expr; value: Expr }[] }
|
|
21
|
+
| { kind: 'named'; name: string; value: Expr }
|
|
22
|
+
| { kind: 'spread'; value: Expr; form?: '...' | '*' | '**' | '&' | '..' }
|
|
23
|
+
| { kind: 'hole' }
|
|
24
|
+
| { kind: 'not'; value: Expr }
|
|
25
|
+
| { kind: 'unary'; op: string; value: Expr; postfix?: true }
|
|
26
|
+
| { kind: 'binary'; op: string; left: Expr; right: Expr }
|
|
27
|
+
| { kind: 'compare'; op: string; left: Expr; right: Expr; type?: true }
|
|
28
|
+
| { kind: 'chain'; ops: string[]; operands: Expr[] }
|
|
29
|
+
| { kind: 'logic'; op: 'and' | 'or'; operands: Expr[] }
|
|
30
|
+
| { kind: 'conditional'; test: Expr; then: Expr; else: Expr }
|
|
31
|
+
| { kind: 'array'; items: Expr[]; form?: 'tuple' | 'set' | 'braces'; type?: string; repeat?: Expr }
|
|
32
|
+
| { kind: 'object'; entries: ({ key?: Expr; value: Expr; shorthand?: true; computed?: true; method?: true } | { kind: 'spread'; value: Expr; form?: string })[]; type?: string; form?: string }
|
|
33
|
+
| { kind: 'comprehension'; form: 'list' | 'set' | 'dict' | 'generator'; item: Expr; key?: Expr; clauses: { targets: Expr[]; iter: Expr; conds?: Expr[] }[] }
|
|
34
|
+
| { kind: 'lambda'; params: string[]; body: Expr | ExprBlock; returns?: string; async?: true; form?: string; name?: string; trailing?: true }
|
|
35
|
+
| { kind: 'cast'; value: Expr; type: string; form: string }
|
|
36
|
+
| { kind: 'pattern'; text: string; names: string[] }
|
|
37
|
+
| ExprBlock
|
|
38
|
+
// Statements
|
|
39
|
+
| { kind: 'assign'; op: string; target: Expr; value: Expr; declare?: string; type?: string; mutable?: true }
|
|
40
|
+
| { kind: 'declare'; names: (string | Expr)[]; declare?: string; type?: string; scope?: string }
|
|
41
|
+
| { kind: 'sequence'; items: Expr[] }
|
|
42
|
+
| { kind: 'return'; value?: Expr }
|
|
43
|
+
| { kind: 'throw'; value?: Expr; error?: string; message?: string; cause?: Expr; form?: string }
|
|
44
|
+
| { kind: 'if'; test: Expr; negate?: true; init?: Expr; inline?: true | Expr; elvis?: true }
|
|
45
|
+
| { kind: 'loop'; form: 'each' | 'while' | 'until' | 'for' | 'forever' | 'do-while'; targets?: Expr[]; iterable?: Expr; test?: Expr; init?: Expr; update?: Expr; keys?: true; range?: true; declare?: string; type?: string }
|
|
46
|
+
| { kind: 'switch'; form?: string; subject?: Expr; init?: Expr }
|
|
47
|
+
| { kind: 'case'; patterns?: Expr[]; default?: true; guard?: Expr }
|
|
48
|
+
| { kind: 'catch'; errors: string[]; as?: string }
|
|
49
|
+
| { kind: 'try' }
|
|
50
|
+
| { kind: 'jump'; jump: 'break' | 'continue' | 'fallthrough'; label?: string }
|
|
51
|
+
| { kind: 'yield'; value?: Expr; delegate?: true; end?: true }
|
|
52
|
+
| { kind: 'defer' | 'go'; value: Expr }
|
|
53
|
+
| { kind: 'delete'; target: Expr }
|
|
54
|
+
| { kind: 'assert'; test: Expr; message?: Expr }
|
|
55
|
+
| { kind: 'with'; items: { value: Expr; as?: Expr }[] }
|
|
56
|
+
| { kind: 'function'; name: string; params: string[]; returns?: string; async?: true; body: ExprBlock }
|
|
57
|
+
| { kind: 'pass' };
|
|
58
|
+
|
|
59
|
+
/** One whole expression, or null when the text is not exactly one expression the reader understands. */
|
|
60
|
+
export function parseExpr(text: string, language?: string): Expr | null;
|
|
61
|
+
/** A statement (a step's `expr`). For a statement that opens a block, only its head; never guessed. */
|
|
62
|
+
export function parseStatement(text: string, language?: string): Expr;
|
|
63
|
+
/** A statement with where each part came from (for running the original code of a part). */
|
|
64
|
+
export function parseStatementSpans(text: string, language?: string): { tree: Expr; textOf(node: Expr): string | null; /** [start, end) of a part in `source` (the trimmed text). */ rangeOf(node: Expr): [number, number] | null; source: string } | null;
|
|
65
|
+
/** Index of the `}` closing the `{` at `open` (strings, templates, and comments skipped), or -1. */
|
|
66
|
+
export function blockEnd(src: string, open: number, language?: string): number;
|
|
67
|
+
/** Code for an expression in TypeScript/JavaScript, Python, or Go. Throws when the language cannot say it. */
|
|
68
|
+
export function renderExpr(tree: Expr, language: string): string;
|
|
69
|
+
/** Code for a statement (a block-opening one with an empty block). Throws when the language cannot say it. */
|
|
70
|
+
export function renderStatement(tree: Expr, language: string): string;
|
|
71
|
+
/** Every detail as one line of neutral, readable code. */
|
|
72
|
+
export function sayFull(tree: Expr): string;
|
|
73
|
+
/** What a step's short words leave out: [{ label, text }], empty when they say everything. */
|
|
74
|
+
export function detailParts(step: { says?: string; kind?: string; code?: string; restates?: boolean; expr?: Expr }): { label: string; text: string }[];
|
|
75
|
+
/** The short words with every omitted detail after them, or null: "Calls save — with: order, { validate: false }". */
|
|
76
|
+
export function detailOf(step: { says?: string; kind?: string; code?: string; restates?: boolean; expr?: Expr }): string | null;
|
|
77
|
+
/** Negations, and/or joins, and comparisons in a tree (what the faithfulness gate counts). */
|
|
78
|
+
export function exprCounts(tree: Expr): { neg: number; logic: number; compare: number };
|
|
79
|
+
/** The tree without spelling (quote style, spacing in types and parameters, layout). */
|
|
80
|
+
export function normalizeExpr(tree: Expr): unknown;
|
|
81
|
+
/** True when two trees mean the same after normalizing spelling. */
|
|
82
|
+
export function sameExpr(a: Expr, b: Expr): boolean;
|
|
83
|
+
/** The names and values in a tree, as a reader would look for them in words. */
|
|
84
|
+
export function namesIn(tree: Expr): string[];
|
|
85
|
+
/** Where a step's words disagree with its tree (a number or text not in the code, a call it does not make). */
|
|
86
|
+
export function wordsAgree(step: { says?: string; kind?: string; restates?: boolean; expr?: Expr }): string[];
|
|
87
|
+
/** Every node of a tree, depth first. */
|
|
88
|
+
export function nodesOf(tree: unknown): Generator<Expr>;
|
|
89
|
+
export class Unrenderable extends Error {}
|