@skillstech/thunderlang 1.0.3 → 1.1.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 +207 -0
- package/dist/core.cjs +13779 -10043
- package/dist/index.cjs +28500 -24392
- package/dist/learn.cjs +12853 -9579
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli.mjs +141 -58
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +133 -0
- package/src/core/diagnostics.mjs +81 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +38 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +167 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/target-python.mjs +486 -0
- package/src/core.d.ts +5 -2
- package/src/core.mjs +5 -2
- package/src/data-schema.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +1 -1
- package/src/expr.mjs +81 -4
- package/src/form-words.mjs +2 -0
- package/src/index.d.ts +8 -1
- package/src/index.mjs +5 -1
- package/src/intent-schema.mjs +1 -0
- package/src/libraries.mjs +2 -2
- package/src/mcp.mjs +23 -0
- package/src/meaning.mjs +47 -7
- package/src/model.d.mts +7 -3
- package/src/model.mjs +30 -9
- package/src/money.d.mts +18 -0
- package/src/money.mjs +124 -0
- package/src/plain-contract.mjs +18 -2
- package/src/powershell.mjs +24 -5
- package/src/read-repo.mjs +1 -0
- package/src/read.d.mts +11 -0
- package/src/read.mjs +121 -13
- package/src/review-comment.d.mts +16 -0
- package/src/review-comment.mjs +145 -0
- package/src/rlang.mjs +10 -3
- package/src/say-less.mjs +1432 -0
- package/src/shell.mjs +45 -8
- package/src/sql-proc.mjs +1198 -0
- package/src/sql.mjs +87 -119
- package/src/steps.mjs +188 -37
- package/src/system.mjs +153 -44
- package/src/target-cs.mjs +39 -34
- package/src/target-elixir.mjs +40 -30
- package/src/target-go.mjs +41 -36
- package/src/target-java.mjs +34 -27
- package/src/target-kotlin.mjs +43 -35
- package/src/target-py.mjs +57 -55
- package/src/target-result.d.mts +48 -0
- package/src/target-result.mjs +112 -0
- package/src/target-rust.mjs +42 -38
- package/src/target-scala.mjs +45 -35
- package/src/target-ts.mjs +37 -45
- package/src/target-types.mjs +41 -5
- package/src/target-util.mjs +55 -2
- package/src/trace-cli.mjs +58 -0
- package/src/trace-fs.mjs +76 -0
- package/src/trace.mjs +261 -0
- package/src/translate.d.mts +3 -0
- package/src/translate.mjs +62 -32
- package/src/why-cli.mjs +31 -0
- package/src/why.d.mts +28 -0
- package/src/why.mjs +532 -0
- package/src/write-steps.mjs +22 -5
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
// Python → Thunder Core: the reader's meaning tree printed as Core a person can edit and compile again.
|
|
2
|
+
// Browser-safe (no Node APIs).
|
|
3
|
+
//
|
|
4
|
+
// Reading and writing are the same language. The reader parses Python into a meaning tree (read.mjs: each step has
|
|
5
|
+
// an `expr`); this file prints that tree as Thunder Core (docs/core.md). It works from the tree, never from the
|
|
6
|
+
// reader's English, so what it prints means what the code means.
|
|
7
|
+
//
|
|
8
|
+
// Never a guess. A step Core cannot say with the same meaning is NOT rewritten into something close: it becomes
|
|
9
|
+
// # Not translated (line 7): sorted(items) sorts plain values, which Core cannot say yet
|
|
10
|
+
// Stop with "Line 7 of the Python was not translated: sorted(items)"
|
|
11
|
+
// so running it fails loudly at that point instead of skipping it, and the function is marked not safely editable.
|
|
12
|
+
// Assumptions that keep the meaning only for some inputs are written next to the line (`# assumes …`), never hidden:
|
|
13
|
+
// a Python value used as a condition is read as yes/no, and Core checks that it is when the program runs.
|
|
14
|
+
|
|
15
|
+
import { readCode } from '../read.mjs';
|
|
16
|
+
import { parseExpr } from '../meaning.mjs';
|
|
17
|
+
import { RESERVED } from './parser.mjs';
|
|
18
|
+
import { compileCore } from './index.mjs';
|
|
19
|
+
|
|
20
|
+
class NotTranslated extends Error {}
|
|
21
|
+
const nt = (why) => { throw new NotTranslated(why); };
|
|
22
|
+
|
|
23
|
+
// Statement words Core reads at the start of a line: a name equal to one is kept as its Python spelling.
|
|
24
|
+
const STATEMENT_START = new Set(['say', 'print', 'set', 'keep', 'give', 'stop', 'when', 'if', 'for', 'repeat', 'to', 'receive', 'expect', 'never', 'use', 'test', 'add', 'remove', 'increase', 'decrease', 'sort', 'reverse', 'round', 'read', 'each', 'until', 'while', 'otherwise', 'has', 'have', 'fails', 'this', 'error']);
|
|
25
|
+
|
|
26
|
+
/** A Python identifier as a Core name: snake_case becomes words ("tax_rate" → "tax rate") unless a word belongs to Thunder. */
|
|
27
|
+
export function coreName(id) {
|
|
28
|
+
const words = String(id).split('_').filter(Boolean);
|
|
29
|
+
const ok = words.length > 0 && !String(id).startsWith('_') && words.every((w) => /^[A-Za-z][A-Za-z0-9]*$/.test(w) && !RESERVED.has(w.toLowerCase()) && !STATEMENT_START.has(w.toLowerCase()));
|
|
30
|
+
if (ok) return words.join(' ');
|
|
31
|
+
// A whole name that is a Thunder word ("a", "to", "say") gets an underscore, so it can never be read as that word.
|
|
32
|
+
const lower = String(id).toLowerCase();
|
|
33
|
+
return RESERVED.has(lower) || STATEMENT_START.has(lower) ? `${id}_` : id;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A method's Core name: the class, then the method ("Account deposit"); __init__ is "set up". */
|
|
37
|
+
export function methodName(cls, method) {
|
|
38
|
+
// Inside a name that starts with the class, a word like "add" cannot start a statement; only Thunder's own words
|
|
39
|
+
// ("is", "of", "to") are kept out.
|
|
40
|
+
const words = String(method).split('_').filter(Boolean);
|
|
41
|
+
const m = method === '__init__' ? 'set up' : words.length && !method.startsWith('_') && words.every((w) => /^[A-Za-z][A-Za-z0-9]*$/.test(w) && !RESERVED.has(w.toLowerCase())) ? words.join(' ') : coreName(method);
|
|
42
|
+
const c = coreName(cls);
|
|
43
|
+
return /^[A-Za-z]+( [A-Za-z]+)*$/.test(`${c} ${m}`) ? `${c} ${m}` : `${cls}_${method.replace(/^_+|_+$/g, '')}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Text as a Core text literal: quotes, backslashes, and braces escaped ({ starts a hole in Core text). */
|
|
47
|
+
export const coreText = (s) => `"${String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\{/g, '{{').replace(/\n/g, '\\n').replace(/\t/g, '\\t').replace(/\r/g, '\\r')
|
|
48
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '\ufffd')}"`; // (other control characters cannot be written in Core text)
|
|
49
|
+
|
|
50
|
+
const BOOLISH = new Set(['compare', 'logic', 'not']);
|
|
51
|
+
const isBoolish = (e) => !!e && (BOOLISH.has(e.kind) || (e.kind === 'literal' && e.type === 'bool') || (e.kind === 'unary' && e.op === 'not'));
|
|
52
|
+
const isName = (e, n) => e?.kind === 'name' && (n === undefined || e.name === n);
|
|
53
|
+
const lit = (e) => (e?.kind === 'literal' ? e : null);
|
|
54
|
+
// A value needs no parentheses when it is one thing: a number, a text, a name (words), or a field chain (o's a's b).
|
|
55
|
+
const ATOM = /^(-?\d[\d.]*|"(?:[^"\\]|\\.)*"|[A-Za-z_]\w*(?: [A-Za-z_]\w*)*(?:'s [A-Za-z_]\w*)*|\((?:[^()]|\([^()]*\))*\)|\[(?:[^[\]"]|"(?:[^"\\]|\\.)*")*\])$/;
|
|
56
|
+
// (A run of words is one name only when none of them belongs to Thunder: "price of item with tax" is not a name.)
|
|
57
|
+
const paren = (s) => (ATOM.test(s) && !(/^[A-Za-z_]/.test(s) && s.split(/ |'s /).some((w) => RESERVED.has(w.toLowerCase()))) ? s : `(${s})`);
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Print Python source as Thunder Core.
|
|
61
|
+
* Gives back { core, functions: [{ name, coreName, line, exact, notTranslated: [{ line, code, why }], assumptions }] }.
|
|
62
|
+
* `exact` means every step was printed with its meaning; only then is the function safe to edit and compile back.
|
|
63
|
+
*/
|
|
64
|
+
export function pythonToCore(source) {
|
|
65
|
+
const reading = readCode(source, { language: 'python', allSteps: true, sayEverything: true });
|
|
66
|
+
const srcLines = String(source).split('\n');
|
|
67
|
+
const all = reading.items.filter((i) => (i.kind === 'function' || i.kind === 'decision') && Array.isArray(i.steps));
|
|
68
|
+
// A method of a top-level class becomes a Core function that receives the object first (Core has functions, not
|
|
69
|
+
// methods): Account.deposit(self, amount) → "To Account deposit:" with "Receive self and amount". An inner function,
|
|
70
|
+
// or a method of a nested class, is not translated: it is listed as a comment.
|
|
71
|
+
const indentOf = (t) => /^\s*/.exec(t)[0].length;
|
|
72
|
+
const classOf = (item) => {
|
|
73
|
+
const own = indentOf(srcLines[item.line - 1] ?? '');
|
|
74
|
+
for (let i = item.line - 2; i >= 0; i--) {
|
|
75
|
+
const t = srcLines[i];
|
|
76
|
+
if (!t.trim() || /^\s*(#|@)/.test(t) || indentOf(t) >= own) continue;
|
|
77
|
+
const m = /^class\s+([A-Za-z_]\w*)\s*(?:\(([^)]*)\))?\s*:/.exec(t);
|
|
78
|
+
return m ? { name: m[1], bases: (m[2] ?? '').split(',').map((b) => b.trim()).filter((b) => b && b !== 'object') } : null;
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
};
|
|
82
|
+
const methodsByClass = new Map();
|
|
83
|
+
const nested = [];
|
|
84
|
+
const fns = [];
|
|
85
|
+
for (const item of all) {
|
|
86
|
+
if (!/^\s/.test(srcLines[item.line - 1] ?? '')) { fns.push(item); continue; }
|
|
87
|
+
const cls = classOf(item);
|
|
88
|
+
const decorators = [];
|
|
89
|
+
for (let i = item.line - 2; i >= 0 && /^\s*(@|#)/.test(srcLines[i]); i--) if (/^\s*@/.test(srcLines[i])) decorators.push(srcLines[i].trim());
|
|
90
|
+
// A static method has no self, and Account.fee(x) means the same as a plain function: it is printed as one.
|
|
91
|
+
const isStatic = decorators.includes('@staticmethod');
|
|
92
|
+
const self = isStatic ? null : /\bdef\s+\w+\s*\(\s*([A-Za-z_]\w*)/.exec(srcLines[item.line - 1] ?? '')?.[1];
|
|
93
|
+
if (!cls || (!self && !isStatic)) { nested.push(item); continue; }
|
|
94
|
+
const m = { ...item, inputs: [...(self ? [{ name: self, type: null }] : []), ...(item.inputs || [])], method: { cls: cls.name, bases: cls.bases, self, name: item.name, isStatic } };
|
|
95
|
+
(methodsByClass.get(cls.name) ?? methodsByClass.set(cls.name, new Map()).get(cls.name)).set(item.name, m);
|
|
96
|
+
fns.push(m);
|
|
97
|
+
}
|
|
98
|
+
// Functions and values share one set of names in Core. A function whose name is also a value somewhere in the file
|
|
99
|
+
// (an input, a variable, a module value) is renamed "<name> function", and every call to it follows. Core names
|
|
100
|
+
// ignore case (MARKET and market are one name), so every comparison here is in lower case.
|
|
101
|
+
const lc = (n) => coreName(n).toLowerCase();
|
|
102
|
+
const valueNames = new Set();
|
|
103
|
+
const collect = (e) => {
|
|
104
|
+
if (!e || typeof e !== 'object') return;
|
|
105
|
+
if (Array.isArray(e)) return e.forEach(collect);
|
|
106
|
+
if (e.kind === 'assign' && e.target?.kind === 'name') valueNames.add(lc(e.target.name));
|
|
107
|
+
if (e.kind === 'loop') for (const t of e.targets || []) if (t.kind === 'name') valueNames.add(lc(t.name));
|
|
108
|
+
for (const v of Object.values(e)) if (v && typeof v === 'object') collect(v);
|
|
109
|
+
};
|
|
110
|
+
const walk = (ss) => { for (const s of ss || []) { collect(s.expr); walk(s.children); walk(s.otherwise); } };
|
|
111
|
+
for (const f of fns) { for (const p of f.inputs || []) valueNames.add(lc(p.name)); walk(f.steps); }
|
|
112
|
+
for (const text of String(source).split('\n')) { const m = /^([A-Za-z_]\w*)\s*=/.exec(text); if (m) valueNames.add(lc(m[1])); }
|
|
113
|
+
// A module value that a function also uses as its own input or variable is renamed "<name>_module" (Python lets the
|
|
114
|
+
// local hide the module value; Core keeps names distinct). Each function reads the module value by that name only
|
|
115
|
+
// where it has no local of the same name.
|
|
116
|
+
const localsOf = new Map();
|
|
117
|
+
for (const f of fns) {
|
|
118
|
+
const loc = new Set((f.inputs || []).map((p) => p.name));
|
|
119
|
+
const add = (e) => { if (!e || typeof e !== 'object') return; if (Array.isArray(e)) return e.forEach(add); if (e.kind === 'assign' && e.target?.kind === 'name') loc.add(e.target.name); if (e.kind === 'loop') for (const t of e.targets || []) if (t.kind === 'name') loc.add(t.name); for (const v of Object.values(e)) if (v && typeof v === 'object') add(v); };
|
|
120
|
+
const w = (ss) => { for (const st of ss || []) { add(st.expr); w(st.children); w(st.otherwise); } };
|
|
121
|
+
w(f.steps);
|
|
122
|
+
localsOf.set(f, loc);
|
|
123
|
+
}
|
|
124
|
+
const allLocals = new Set([...localsOf.values()].flatMap((x) => [...x].map(lc)));
|
|
125
|
+
const moduleNames = new Map();
|
|
126
|
+
for (const text of srcLines) { const m = /^([A-Za-z_]\w*)\s*=/.exec(text); if (m && !moduleNames.has(m[1])) moduleNames.set(m[1], allLocals.has(lc(m[1])) ? `${m[1]}_module` : m[1]); }
|
|
127
|
+
const own = new Map();
|
|
128
|
+
const taken = new Set();
|
|
129
|
+
for (const f of fns) {
|
|
130
|
+
let n = f.method ? methodName(f.method.cls, f.name) : coreName(f.name);
|
|
131
|
+
if (valueNames.has(n.toLowerCase())) n = /^[A-Za-z]+( [A-Za-z]+)*$/.test(n) ? `${n} function` : `${n}_function`;
|
|
132
|
+
// Python lets a later def replace an earlier one; in Core each gets its own name.
|
|
133
|
+
for (let k = 2; taken.has(n.toLowerCase()); k++) n = `${n.replace(/_\d+$/, '')}_${k}`;
|
|
134
|
+
taken.add(n.toLowerCase());
|
|
135
|
+
if (!f.method && !own.has(f.name)) own.set(f.name, n);
|
|
136
|
+
f.coreName = n;
|
|
137
|
+
}
|
|
138
|
+
const lines = String(source).split('\n');
|
|
139
|
+
const out = [];
|
|
140
|
+
const functions = [];
|
|
141
|
+
// Module-level values (TAX = 0.07): "Keep TAX at 0.07". Anything else at the top level is listed, never dropped quietly.
|
|
142
|
+
const kept = [];
|
|
143
|
+
const top = new FunctionPrinter({ name: '(module)', steps: [], inputs: [] }, own, lines, { moduleNames });
|
|
144
|
+
lines.forEach((text, i) => {
|
|
145
|
+
const m = /^([A-Za-z_]\w*)\s*=\s*(.+?)\s*$/.exec(text);
|
|
146
|
+
if (!m || /^\s/.test(text)) return;
|
|
147
|
+
try { kept.push(`Keep ${coreName(moduleNames.get(m[1]) ?? m[1])} at ${top.value(parseExpr(m[2], 'python'))}`); }
|
|
148
|
+
catch (e) {
|
|
149
|
+
if (!(e instanceof NotTranslated)) throw e;
|
|
150
|
+
kept.push(`# Not translated (line ${i + 1}): ${e.message}`, `Keep ${coreName(moduleNames.get(m[1]) ?? m[1])} at nothing`);
|
|
151
|
+
top.notTranslated.push({ line: i + 1, code: text.trim(), why: e.message });
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
if (kept.length) out.push(...kept, '');
|
|
155
|
+
const printed = fns.map((f) => new FunctionPrinter(f, own, lines, { moduleNames, locals: localsOf.get(f), classMethods: f.method ? methodsByClass.get(f.method.cls) : null }).print());
|
|
156
|
+
// The printed Core must compile, whatever the Python looked like. A function that does not (a name set only by a
|
|
157
|
+
// line that was not translated, say) keeps what was printed as comments, so a reader still sees it, and its body
|
|
158
|
+
// becomes one Stop line; it is reported as not translated, never as exact.
|
|
159
|
+
const assemble = () => [...out, ...printed.flatMap((p) => [...p.lines, ''])].join('\n').replace(/\n+$/, '\n');
|
|
160
|
+
for (let round = 0; round <= printed.length + kept.length; round++) {
|
|
161
|
+
const text = assemble();
|
|
162
|
+
const c = compileCore(text);
|
|
163
|
+
if (c.ok || !c.diagnostics.length) break;
|
|
164
|
+
const d = c.diagnostics[0];
|
|
165
|
+
// Which part holds the line: a kept value at the top, or one of the functions.
|
|
166
|
+
let at = 1 + out.length + (out.length ? 0 : 0);
|
|
167
|
+
let owner = null;
|
|
168
|
+
if (d.line <= out.length) {
|
|
169
|
+
const i = d.line - 1;
|
|
170
|
+
top.notTranslated.push({ line: null, code: out[i], why: `the printed Core did not compile: ${d.message}` });
|
|
171
|
+
out[i] = `# Not translated: ${out[i]} (${d.message})`;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
at = out.length + 1;
|
|
175
|
+
for (const p of printed) { if (d.line >= at && d.line < at + p.lines.length) { owner = p; break; } at += p.lines.length + 1; }
|
|
176
|
+
if (!owner || owner.commented) break; // nothing more Thunder can do; the diagnostics stay visible
|
|
177
|
+
const [header, ...rest] = owner.lines;
|
|
178
|
+
// Keep the Receive line, unless the problem is on it (then it is shown as a comment too).
|
|
179
|
+
const receive = rest[0]?.startsWith(' Receive ') && d.line !== at + 1 ? [rest.shift()] : [];
|
|
180
|
+
owner.info.exact = false;
|
|
181
|
+
owner.info.notTranslated.push({ line: null, code: owner.info.name, why: `the printed Core did not compile (${d.message}), so the function is shown as comments` });
|
|
182
|
+
owner.lines = [header, ...receive, ...rest.map((l) => ` # ${l.trimStart().startsWith('#') ? l.trim().replace(/^#\s*/, '') : l.slice(2)}`), ` Stop with ${coreText(`${owner.info.name} was not translated from Python: the printed Core did not compile`)}`];
|
|
183
|
+
owner.commented = true;
|
|
184
|
+
}
|
|
185
|
+
let core = assemble();
|
|
186
|
+
if (!compileCore(core).ok) {
|
|
187
|
+
// Last resort, so the promise holds: everything is shown as comments, and nothing is claimed as exact.
|
|
188
|
+
const why = compileCore(core).diagnostics[0]?.message ?? 'unknown';
|
|
189
|
+
core = [`# Thunder could not print this file as Core that compiles (${why}). What it printed is below, as comments.`, ...core.split('\n').map((l) => (l ? `# ${l}` : l))].join('\n');
|
|
190
|
+
for (const p of printed) if (p.info.exact) { p.info.exact = false; p.info.notTranslated.push({ line: null, code: p.info.name, why: 'the file as a whole did not compile as Core, so it is shown as comments' }); }
|
|
191
|
+
}
|
|
192
|
+
if (nested.length) {
|
|
193
|
+
core += `${core.endsWith('\n') || !core ? '' : '\n'}\n# Not translated: ${nested.length} inner function${nested.length === 1 ? '' : 's'} or method${nested.length === 1 ? '' : 's'} of a nested class (Core has no inner functions yet):\n`
|
|
194
|
+
+ nested.map((f) => `# line ${f.line}: ${f.name}`).join('\n') + '\n';
|
|
195
|
+
}
|
|
196
|
+
for (const p of printed) functions.push(p.info);
|
|
197
|
+
for (const f of nested) functions.push({ name: f.name, coreName: null, line: f.line, exact: false, notTranslated: [{ line: f.line, code: (srcLines[f.line - 1] ?? '').trim(), why: 'a function inside another function, or a method of a nested class (Core has no inner functions yet)' }], assumptions: [] });
|
|
198
|
+
functions.sort((a, b) => a.line - b.line);
|
|
199
|
+
return { core, functions, module: { notTranslated: top.notTranslated } };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
class FunctionPrinter {
|
|
203
|
+
constructor(fn, own, srcLines, { moduleNames = new Map(), locals = new Set(), classMethods = null } = {}) {
|
|
204
|
+
this.fn = fn; this.own = own; this.src = srcLines; this.moduleNames = moduleNames; this.locals = locals; this.classMethods = classMethods;
|
|
205
|
+
// json.loads / json.dumps mean the standard library's only when the file imports it under that name.
|
|
206
|
+
this.importsJson = srcLines.some((l) => /^import\s+json\s*$/.test(l));
|
|
207
|
+
this.lines = []; this.notTranslated = []; this.assumptions = [];
|
|
208
|
+
this.kinds = new Map(); // name -> 'number' | 'text' | 'list' | 'map' (what this function set it to)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
print() {
|
|
212
|
+
const f = this.fn;
|
|
213
|
+
const name = f.coreName ?? this.own.get(f.name) ?? coreName(f.name);
|
|
214
|
+
const params = (f.inputs || []).map((p) => p.name);
|
|
215
|
+
const one = (p) => (this.defaults?.has(p) ? `${coreName(p)} (${this.defaults.get(p)} if not given)` : coreName(p));
|
|
216
|
+
const head = (n, ps) => [`To ${n}:`, ...(ps.length ? [` Receive ${ps.length === 1 ? one(ps[0]) : `${ps.slice(0, -1).map(one).join(', ')} and ${one(ps.at(-1))}`}`] : [])];
|
|
217
|
+
if (f.stepsMore || (f.totalSteps != null && f.steps.length === 0 && f.totalSteps > 0)) this.notTranslated.push({ line: f.line, code: f.name, why: 'the reader did not list every step of this function' });
|
|
218
|
+
if (f.method && /^__\w+__$/.test(f.name) && f.name !== '__init__') {
|
|
219
|
+
this.notTranslated.push({ line: f.line, code: (this.src[f.line - 1] ?? '').trim(), why: `${f.name} is a special method: it changes how Python treats the object (operators, printing, comparing), which Core cannot say` });
|
|
220
|
+
return this.refuseWhole(head(name, params), name);
|
|
221
|
+
}
|
|
222
|
+
if (!f.method && /^\s/.test(this.src[f.line - 1] ?? '')) {
|
|
223
|
+
this.notTranslated.push({ line: f.line, code: (this.src[f.line - 1] ?? '').trim(), why: 'a function inside a class or another function (Core has records and functions, not methods or inner functions yet)' });
|
|
224
|
+
return this.refuseWhole(head(name, params), name);
|
|
225
|
+
}
|
|
226
|
+
if (params.some((p) => !/^[A-Za-z_]\w*$/.test(p))) {
|
|
227
|
+
this.notTranslated.push({ line: f.line, code: this.src[f.line - 1]?.trim() ?? '', why: 'its inputs use *args, **kwargs, or another form Core does not have' });
|
|
228
|
+
return this.refuseWhole([`To ${name}:`], name);
|
|
229
|
+
}
|
|
230
|
+
for (let i = f.line - 2; i >= 0 && /^\s*(@|#)/.test(this.src[i]); i--) {
|
|
231
|
+
if (/^\s*@/.test(this.src[i]) && !(f.method?.isStatic && this.src[i].trim() === '@staticmethod')) { this.notTranslated.push({ line: i + 1, code: this.src[i].trim(), why: 'a decorator changes what this function is (it may cache it, register it, or replace it), which Core cannot say' }); break; }
|
|
232
|
+
}
|
|
233
|
+
// The signature may run over several lines: read it until its parentheses close.
|
|
234
|
+
let sig = '';
|
|
235
|
+
for (let i = f.line - 1, depth = 0, started = false; i < this.src.length; i++) {
|
|
236
|
+
for (const ch of this.src[i]) {
|
|
237
|
+
if (ch === '(') { depth++; started = true; } else if (ch === ')') depth--;
|
|
238
|
+
if (started) sig += ch;
|
|
239
|
+
if (started && depth === 0) break;
|
|
240
|
+
}
|
|
241
|
+
if (started && depth === 0) break;
|
|
242
|
+
sig += ' ';
|
|
243
|
+
}
|
|
244
|
+
// Defaults: "rate=0.07" is "rate (0.07 if not given)" when the value is fixed (a number, text, True/False, None,
|
|
245
|
+
// or a module value). A list, a dict, or a computed default is refused: Python makes it once and shares it.
|
|
246
|
+
const parts = []; let cur = '', depth = 0;
|
|
247
|
+
for (const ch of sig.slice(1, -1)) { if ('([{'.includes(ch)) depth++; if (')]}'.includes(ch)) depth--; if (ch === ',' && depth === 0) { parts.push(cur); cur = ''; } else cur += ch; }
|
|
248
|
+
parts.push(cur);
|
|
249
|
+
this.defaults = new Map();
|
|
250
|
+
for (const part of parts) {
|
|
251
|
+
const m = /^\s*([A-Za-z_]\w*)\s*(?::[^=]*)?=(?!=)\s*([\s\S]+?)\s*$/.exec(part);
|
|
252
|
+
if (!m) continue;
|
|
253
|
+
const d = parseExpr(m[2], 'python');
|
|
254
|
+
if (!d) { this.notTranslated.push({ line: f.line, code: m[0].trim(), why: `the default for ${m[1]} was not read` }); continue; }
|
|
255
|
+
const fixed = (x) => (x.kind === 'literal' && ['number', 'text', 'bool', 'null'].includes(x.type) && !x.bytes) || (x.kind === 'unary' && x.op === '-' && fixed(x.value)) || (x.kind === 'name' && this.moduleNames.has(x.name));
|
|
256
|
+
if (!fixed(d)) { this.notTranslated.push({ line: f.line, code: m[0].trim(), why: `the default for ${m[1]} is ${d.kind === 'array' || d.kind === 'object' ? 'a list or a dict, which Python makes once and shares between calls' : 'computed, not a fixed value'}` }); continue; }
|
|
257
|
+
try { this.defaults.set(m[1], this.value(d)); } catch (e) { if (!(e instanceof NotTranslated)) throw e; this.notTranslated.push({ line: f.line, code: m[0].trim(), why: e.message }); }
|
|
258
|
+
}
|
|
259
|
+
this.block(f.steps, 1);
|
|
260
|
+
const exact = this.notTranslated.length === 0;
|
|
261
|
+
const body = this.lines.length ? this.lines : [' Give nothing'];
|
|
262
|
+
return {
|
|
263
|
+
lines: [...head(name, params), ...body],
|
|
264
|
+
info: { name: f.name, coreName: name, line: f.line, exact, notTranslated: this.notTranslated, assumptions: this.assumptions },
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The whole function is one meaning Core cannot say yet: its body is one Stop line. */
|
|
269
|
+
refuseWhole(headLines, name) {
|
|
270
|
+
const n = this.notTranslated[0];
|
|
271
|
+
return {
|
|
272
|
+
lines: [...headLines, ` # Not translated (line ${n.line}): ${n.why}`, ` Stop with ${coreText(`${this.fn.name} was not translated from Python: ${n.why}`)}`],
|
|
273
|
+
info: { name: this.fn.name, coreName: name, line: this.fn.line, exact: false, notTranslated: this.notTranslated, assumptions: [] },
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
emit(depth, text) { this.lines.push(`${' '.repeat(depth)}${text}`); }
|
|
278
|
+
|
|
279
|
+
block(steps, depth) {
|
|
280
|
+
for (const s of steps || []) {
|
|
281
|
+
const mark = this.lines.length;
|
|
282
|
+
this.line = s.line ?? this.line;
|
|
283
|
+
try { this.step(s, depth); }
|
|
284
|
+
catch (e) {
|
|
285
|
+
if (!(e instanceof NotTranslated)) throw e;
|
|
286
|
+
this.lines.length = mark; // drop anything this step half-printed
|
|
287
|
+
const code = (s.code || this.src[(s.line ?? 1) - 1] || '').trim();
|
|
288
|
+
this.notTranslated.push({ line: s.line ?? null, code, why: e.message });
|
|
289
|
+
this.emit(depth, `# Not translated (line ${s.line}): ${e.message}`);
|
|
290
|
+
this.emit(depth, `Stop with ${coreText(`Line ${s.line} of the Python was not translated: ${code}`)}`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
step(s, d) {
|
|
296
|
+
const e = s.expr;
|
|
297
|
+
if (s.kind === 'branch' || e?.kind === 'if') return this.branch(s, d, false);
|
|
298
|
+
if (!e) nt(`Thunder did not read the meaning of this step (${s.kind})`);
|
|
299
|
+
switch (e.kind) {
|
|
300
|
+
case 'assign': return this.assign(e, d);
|
|
301
|
+
case 'return': return this.emit(d, e.value ? `Give ${this.value(e.value)}` : 'Give nothing');
|
|
302
|
+
case 'call': return this.callStatement(e, d);
|
|
303
|
+
case 'loop': return this.loop(s, e, d);
|
|
304
|
+
case 'throw': {
|
|
305
|
+
if (!e.value) nt('a bare raise passes on an error that is caught here, which Core cannot say yet');
|
|
306
|
+
const v = e.value;
|
|
307
|
+
if (v.kind === 'call' && (v.args || []).length === 1) return this.emit(d, `Stop with ${this.value(v.args[0])}`);
|
|
308
|
+
if (v.kind === 'call' && !(v.args || []).length) return this.emit(d, `Stop with ${coreText(v.callee?.name ?? 'an error')}`);
|
|
309
|
+
nt('this raise is not of the form raise SomeError("message")');
|
|
310
|
+
return undefined;
|
|
311
|
+
}
|
|
312
|
+
case 'pass': return undefined;
|
|
313
|
+
case 'code': nt('Thunder did not read the meaning of this line'); return undefined;
|
|
314
|
+
default: nt(`Core has no step for a Python ${e.kind}${e.kind === 'try' ? ' (an error handler that names its error kinds)' : ''} yet`);
|
|
315
|
+
}
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
branch(s, d, isElse) {
|
|
320
|
+
const test = s.expr?.test;
|
|
321
|
+
if (!test) nt('the condition of this if was not read');
|
|
322
|
+
let cond = this.condition(test, s.line);
|
|
323
|
+
if (s.negate) cond = `not ${paren(cond)}`;
|
|
324
|
+
this.emit(d, `${isElse ? 'Otherwise when' : 'When'} ${cond}:`);
|
|
325
|
+
this.blockOrNothing(s.children, d + 1);
|
|
326
|
+
const other = s.otherwise || [];
|
|
327
|
+
if (other.length === 1 && other[0].elseIf) return this.branch(other[0], d, true);
|
|
328
|
+
if (other.length) { this.emit(d, 'Otherwise:'); this.blockOrNothing(other, d + 1); }
|
|
329
|
+
return undefined;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
blockOrNothing(steps, d) {
|
|
333
|
+
const before = this.lines.length;
|
|
334
|
+
this.block(steps, d);
|
|
335
|
+
if (this.lines.length === before) nt('an empty block (pass) inside a condition or loop, which Core does not have');
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// ── statements ──
|
|
339
|
+
|
|
340
|
+
assign(e, d) {
|
|
341
|
+
const t = e.target;
|
|
342
|
+
if (e.op === '=' ) {
|
|
343
|
+
if (t.kind === 'name') {
|
|
344
|
+
this.remember(t.name, e.value);
|
|
345
|
+
return this.emit(d, `Set ${coreName(t.name)} to ${this.value(e.value)}`);
|
|
346
|
+
}
|
|
347
|
+
return this.emit(d, `Set ${this.place(t)} to ${this.value(e.value)}`);
|
|
348
|
+
}
|
|
349
|
+
if (e.op === '+=' || e.op === '-=') {
|
|
350
|
+
const target = t.kind === 'name' ? coreName(t.name) : this.place(t);
|
|
351
|
+
const v = this.value(e.value);
|
|
352
|
+
if (t.kind === 'name' && this.kinds.get(t.name) === 'number') return this.emit(d, `${e.op === '+=' ? 'Increase' : 'Decrease'} ${target} by ${v}`);
|
|
353
|
+
return this.emit(d, `Set ${target} to ${target} ${e.op[0]} ${paren(v)}`);
|
|
354
|
+
}
|
|
355
|
+
nt(`Core has no ${e.op} yet`);
|
|
356
|
+
return undefined;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
remember(name, v) {
|
|
360
|
+
const k = v?.kind === 'literal' ? (v.type === 'number' ? 'number' : v.type === 'text' ? 'text' : null)
|
|
361
|
+
: v?.kind === 'object' ? 'map' : v?.kind === 'array' || v?.kind === 'list' ? 'list' : null;
|
|
362
|
+
if (k) this.kinds.set(name, k); else this.kinds.delete(name);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Something that can be set: a field (o's price) or an entry of a map (counts at word). */
|
|
366
|
+
place(t) {
|
|
367
|
+
if (t.kind === 'member') return `${this.owner(t.object)}'s ${t.property}`;
|
|
368
|
+
if (t.kind === 'index') return this.indexed(t);
|
|
369
|
+
nt('only a name, a field, or a map entry can be set in Core');
|
|
370
|
+
return '';
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
callStatement(e, d) {
|
|
374
|
+
const path = calleePath(e.callee);
|
|
375
|
+
if (path?.length === 1 && path[0] === 'print') {
|
|
376
|
+
if ((e.args || []).some((a) => a.kind === 'named' || a.kind === 'spread')) nt('print with sep=, end= or file= has no Core form');
|
|
377
|
+
const args = e.args || [];
|
|
378
|
+
if (!args.length) nt('an empty print() prints a blank line, which Core has no form for yet');
|
|
379
|
+
if (args.length === 1) return this.emit(d, `say ${this.value(args[0])}`);
|
|
380
|
+
// print(a, b) separates its values with one space; text written in the call is kept as text.
|
|
381
|
+
return this.emit(d, `say "${args.map((a) => (lit(a)?.type === 'text' && !a.bytes ? coreText(a.value).slice(1, -1) : `{${this.value(a)}}`)).join(' ')}"`);
|
|
382
|
+
}
|
|
383
|
+
if (e.callee?.kind === 'member' && e.callee.property === 'append' && (e.args || []).length === 1 && e.args[0].kind !== 'named') return this.emit(d, `Add ${this.value(e.args[0])} to ${this.owner(e.callee.object)}`);
|
|
384
|
+
if (path?.length === 1 && this.own.has(path[0])) return this.emit(d, this.ownCall(path[0], e.args || []));
|
|
385
|
+
const sm = this.selfCall(e);
|
|
386
|
+
if (sm) return this.emit(d, sm);
|
|
387
|
+
nt(`calls ${path ? path.join('.') : 'a computed function'}, which Core does not know`);
|
|
388
|
+
return undefined;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
loop(s, e, d) {
|
|
392
|
+
if (e.form === 'while') {
|
|
393
|
+
this.emit(d, `Repeat while ${this.condition(e.test ?? e.condition, s.line)}:`);
|
|
394
|
+
return this.blockOrNothing(s.children, d + 1);
|
|
395
|
+
}
|
|
396
|
+
if (e.form !== 'each') nt(`Core has no ${e.form} loop`);
|
|
397
|
+
const targets = e.targets || [];
|
|
398
|
+
const it = e.iterable;
|
|
399
|
+
if (targets.length === 1 && isName(targets[0]) && it?.kind === 'call' && isName(it.callee, 'range')) {
|
|
400
|
+
const a = it.args || [];
|
|
401
|
+
if (a.length === 0 || a.length > 2) nt('range with a step has no Core form yet');
|
|
402
|
+
const from = a.length === 2 ? this.value(a[0]) : '0';
|
|
403
|
+
const end = a.length === 2 ? a[1] : a[0];
|
|
404
|
+
// range stops before its end: range(1, n + 1) counts 1 … n.
|
|
405
|
+
let to;
|
|
406
|
+
if (end.kind === 'binary' && end.op === '+' && lit(end.right)?.type === 'number' && Number(lit(end.right).value) === 1) to = this.value(end.left);
|
|
407
|
+
else if (lit(end)?.type === 'number' && Number.isInteger(Number(lit(end).value))) to = String(Number(lit(end).value) - 1);
|
|
408
|
+
else to = `${paren(this.value(end))} - 1`;
|
|
409
|
+
this.kinds.set(targets[0].name, 'number');
|
|
410
|
+
this.emit(d, `For each ${coreName(targets[0].name)} from ${from} to ${to}:`);
|
|
411
|
+
return this.blockOrNothing(s.children, d + 1);
|
|
412
|
+
}
|
|
413
|
+
if (targets.length === 2 && targets.every((t) => isName(t)) && it?.kind === 'call' && calleePath(it.callee)?.at(-1) === 'items' && !(it.args || []).length) {
|
|
414
|
+
this.emit(d, `For each ${coreName(targets[0].name)} and ${coreName(targets[1].name)} in ${this.owner(it.callee.object)}:`);
|
|
415
|
+
return this.blockOrNothing(s.children, d + 1);
|
|
416
|
+
}
|
|
417
|
+
if (targets.length !== 1 || !isName(targets[0])) nt('a loop that unpacks several names has no Core form here');
|
|
418
|
+
this.kinds.delete(targets[0].name);
|
|
419
|
+
this.emit(d, `For each ${coreName(targets[0].name)} in ${this.value(it)}:`);
|
|
420
|
+
return this.blockOrNothing(s.children, d + 1);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// ── values ──
|
|
424
|
+
|
|
425
|
+
/** A condition: a comparison stays as it is; any other value is read as yes/no (and Core checks that it is). */
|
|
426
|
+
condition(e, line, item = null) {
|
|
427
|
+
if (isBoolish(e)) return this.value(e, item);
|
|
428
|
+
if (e?.kind === 'unary' && e.op === 'not') return `not ${paren(this.condition(e.value ?? e.operand, line, item))}`;
|
|
429
|
+
const v = this.value(e, item);
|
|
430
|
+
this.assumptions.push({ line: line ?? this.line ?? null, says: `${v} is read as yes/no (Python would also accept other values here); Core stops with an error if it is not yes/no` });
|
|
431
|
+
return `${paren(v)} is true`;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
value(e, item = null) {
|
|
435
|
+
if (!e) nt('a value Thunder did not read');
|
|
436
|
+
switch (e.kind) {
|
|
437
|
+
case 'name':
|
|
438
|
+
if (item && e.name === item) nt('the item itself is used here, which "where" cannot say');
|
|
439
|
+
if (this.own.has(e.name) && !this.locals.has(e.name)) nt(`passes the function ${e.name} itself as a value; in Core, writing a function's name calls it`);
|
|
440
|
+
return coreName(!this.locals.has(e.name) && this.moduleNames.has(e.name) ? this.moduleNames.get(e.name) : e.name);
|
|
441
|
+
case 'literal': {
|
|
442
|
+
if (e.type === 'number') { if (!/^-?\d[\d_]*(\.\d+)?$/.test(String(e.raw ?? e.value))) nt(`the number ${e.raw} has no Core form`); return String(e.raw ?? e.value).replace(/_/g, ''); }
|
|
443
|
+
if (e.type === 'text') { if (e.bytes) nt('a bytes value (b"…") is not text in Python, and Core has no bytes'); if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(String(e.value))) nt('this text holds a control character that Core text cannot write'); return coreText(e.value); }
|
|
444
|
+
if (e.type === 'bool') return e.value ? 'true' : 'false';
|
|
445
|
+
if (e.type === 'null') return 'nothing';
|
|
446
|
+
nt(`a ${e.type} value has no Core form`);
|
|
447
|
+
return '';
|
|
448
|
+
}
|
|
449
|
+
case 'template': return this.template(e, item);
|
|
450
|
+
case 'member':
|
|
451
|
+
if (item && isName(e.object, item)) return e.property;
|
|
452
|
+
return `${this.owner(e.object, item)}'s ${e.property}`;
|
|
453
|
+
case 'index': return this.indexed(e, item);
|
|
454
|
+
case 'binary': {
|
|
455
|
+
const op = { '+': '+', '-': '-', '*': '*', '/': '/', '%': 'mod' }[e.op];
|
|
456
|
+
if (!op) nt(e.op === '//' ? 'Python // rounds down to a whole number, which Core cannot say yet' : `Core has no ${e.op} operator`);
|
|
457
|
+
if (op !== '+' && [e.left, e.right].some((x) => lit(x)?.type === 'text')) nt(`${e.op} with text means something else in Python here (a path, a repeat, or a format), not arithmetic`);
|
|
458
|
+
return `${paren(this.value(e.left, item))} ${op} ${paren(this.value(e.right, item))}`;
|
|
459
|
+
}
|
|
460
|
+
case 'unary':
|
|
461
|
+
if (e.op === '-') return `-${paren(this.value(e.value ?? e.operand, item))}`;
|
|
462
|
+
nt(`Core has no unary ${e.op}`);
|
|
463
|
+
return '';
|
|
464
|
+
case 'not': return `not ${paren(this.condition(e.value ?? e.operand ?? e.expr, null, item))}`;
|
|
465
|
+
case 'compare': return this.compare(e, item);
|
|
466
|
+
case 'chain': nt('a chained comparison (a < b < c) has no Core form yet'); return '';
|
|
467
|
+
case 'logic': {
|
|
468
|
+
// Python and/or give back one of their values; in Core they are yes/no, so each side must be yes/no.
|
|
469
|
+
const ops = e.operands || [];
|
|
470
|
+
if (ops.length < 2) nt('a logic expression Thunder did not read');
|
|
471
|
+
// Comparisons bind tighter than and/or in Core, so only a nested and/or of the other kind needs parentheses.
|
|
472
|
+
return ops.map((x) => { const t = isBoolish(x) ? this.value(x, item) : this.condition(x, null, item); return x.kind === 'logic' && x.op !== e.op ? `(${t})` : t; }).join(e.op === 'and' ? ' and ' : ' or ');
|
|
473
|
+
}
|
|
474
|
+
case 'call': return this.callValue(e, item);
|
|
475
|
+
case 'array': case 'list':
|
|
476
|
+
// A tuple is not a list in Python (it never equals one); only as the right side of "in" is it the same.
|
|
477
|
+
if (e.form === 'tuple' && !this.inMembership) nt('a tuple is not a list in Python, and Core has lists only');
|
|
478
|
+
return `[${(e.items || e.elements || []).map((x) => this.value(x, item)).join(', ')}]`;
|
|
479
|
+
case 'object':
|
|
480
|
+
if ((e.entries || []).length) nt('a dictionary written with entries has no Core form yet (an empty one does)');
|
|
481
|
+
return 'an empty map';
|
|
482
|
+
case 'comprehension': return this.comprehension(e);
|
|
483
|
+
default: nt(`Core has no form for a Python ${e.kind}`);
|
|
484
|
+
}
|
|
485
|
+
return '';
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** The value a field or entry is read from: a name, or another field (Core reads o's a's b). */
|
|
489
|
+
owner(e, item = null) {
|
|
490
|
+
if (e.kind === 'name') return this.value(e, item);
|
|
491
|
+
if (e.kind === 'member') return this.value(e, item);
|
|
492
|
+
return paren(this.value(e, item));
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
indexed(e, item = null) {
|
|
496
|
+
const obj = e.object, key = e.index ?? e.property ?? e.key;
|
|
497
|
+
const kind = obj.kind === 'name' ? this.kinds.get(obj.name) : null;
|
|
498
|
+
if (lit(key)?.type === 'text' || kind === 'map') return `${this.owner(obj, item)} at ${paren(this.value(key, item))}`;
|
|
499
|
+
if (lit(key)?.type === 'number' && Number.isInteger(Number(key.value)) && Number(key.value) >= 0) {
|
|
500
|
+
if (kind !== 'list') this.assumptions.push({ line: this.line ?? null, says: `${this.owner(obj, item)} is read as a list (or tuple), so Python's position ${key.value} is Core's position ${Number(key.value) + 1}; a map with number keys would mean something else` });
|
|
501
|
+
return `${this.owner(obj, item)} at ${Number(key.value) + 1}`; // Core counts from 1
|
|
502
|
+
}
|
|
503
|
+
nt('Thunder cannot tell whether this is a list position (Python counts from 0, Core from 1) or a map key');
|
|
504
|
+
return '';
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
compare(e, item) {
|
|
508
|
+
if (e.chain || e.comparators) nt('a chained comparison (a < b < c) has no Core form yet');
|
|
509
|
+
const l = this.value(e.left, item);
|
|
510
|
+
const r = e.right;
|
|
511
|
+
if (r && lit(r)?.type === 'null' && (e.op === 'is' || e.op === '==')) return `${paren(l)} is nothing`;
|
|
512
|
+
if (r && lit(r)?.type === 'null' && (e.op === 'is not' || e.op === '!=')) return `${paren(l)} is not nothing`;
|
|
513
|
+
const words = { '==': 'is', '!=': 'is not', '>=': 'is at least', '<=': 'is at most', '>': 'is more than', '<': 'is less than', in: 'is in' }[e.op];
|
|
514
|
+
const side = (x) => { this.inMembership = true; try { return this.value(x, item); } finally { this.inMembership = false; } };
|
|
515
|
+
if (e.op === 'not in') return `not (${paren(l)} is in ${paren(side(r))})`;
|
|
516
|
+
if (e.op === 'in') return `${paren(l)} is in ${paren(side(r))}`;
|
|
517
|
+
if (!words) nt(`Core has no ${e.op} comparison`);
|
|
518
|
+
return `${paren(l)} ${words} ${paren(this.value(r, item))}`;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
template(e, item) {
|
|
522
|
+
let out = '"';
|
|
523
|
+
for (const p of e.parts || []) {
|
|
524
|
+
if (typeof p === 'string') out += coreText(p).slice(1, -1);
|
|
525
|
+
else {
|
|
526
|
+
if (p.format || p.spec || p.conversion) nt('a format specification inside an f-string has no Core form yet');
|
|
527
|
+
out += `{${this.value(p.expr ?? p, item)}}`;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
return `${out}"`;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
callValue(e, item) {
|
|
534
|
+
const path = calleePath(e.callee);
|
|
535
|
+
const args = e.args || [];
|
|
536
|
+
if ((args).some((a) => a.kind === 'spread')) nt('*args in a call has no Core form');
|
|
537
|
+
const one = args.length === 1 && args[0].kind !== 'named' ? args[0] : null;
|
|
538
|
+
const sm = this.selfCall(e, item);
|
|
539
|
+
if (sm) return sm;
|
|
540
|
+
if (path?.length === 1) {
|
|
541
|
+
const f = path[0];
|
|
542
|
+
if (f === 'len' && one) return `the count of ${paren(this.value(one, item))}`;
|
|
543
|
+
if (f === 'sum' && one) return `the sum of ${paren(this.value(one, item))}`;
|
|
544
|
+
if (f === 'min' && one) return `the smallest of ${paren(this.value(one, item))}`;
|
|
545
|
+
if (f === 'max' && one) return `the largest of ${paren(this.value(one, item))}`;
|
|
546
|
+
if (f === 'round') nt('Python round() rounds halves to even; Thunder rounds half up');
|
|
547
|
+
if (f === 'sorted') return this.sorted(e, item);
|
|
548
|
+
if (f === 'abs' && one) return `the absolute value of ${paren(this.value(one, item))}`;
|
|
549
|
+
if ((f === 'max' || f === 'min') && args.length >= 2) {
|
|
550
|
+
if (args.some((a) => a.kind === 'named' || a.kind === 'spread')) nt(`${f}() with key= or default= has no Core form yet`);
|
|
551
|
+
return `the ${f === 'max' ? 'largest' : 'smallest'} of [${args.map((a) => this.value(a, item)).join(', ')}]`;
|
|
552
|
+
}
|
|
553
|
+
if (f === 'list' && !args.length) return 'an empty list';
|
|
554
|
+
if (f === 'list' && one) return `${paren(this.value(one, item))} as list`;
|
|
555
|
+
if (f === 'dict' && !args.length) return 'an empty map';
|
|
556
|
+
if (this.own.has(f)) return this.ownCall(f, args, item);
|
|
557
|
+
nt(`calls ${f}(), which Core does not know`);
|
|
558
|
+
}
|
|
559
|
+
if (e.callee?.kind === 'member' && !(path?.length === 1)) {
|
|
560
|
+
const m = e.callee.property;
|
|
561
|
+
const of = (op) => `the ${op} of ${this.owner(e.callee.object, item)}`;
|
|
562
|
+
if (m === 'lower' && !args.length) return of('lowercase');
|
|
563
|
+
if (m === 'upper' && !args.length) return of('uppercase');
|
|
564
|
+
if (m === 'strip' && !args.length) return of('trimmed');
|
|
565
|
+
if (m === 'get' && args.length === 2) return `(${this.owner(e.callee.object, item)} at ${paren(this.value(args[0], item))} otherwise ${paren(this.value(args[1], item))})`;
|
|
566
|
+
const pos = args.filter((a) => a.kind !== 'named');
|
|
567
|
+
if (args.some((a) => a.kind === 'named')) nt(`.${m}() with name=value inputs has no Core form yet`);
|
|
568
|
+
const obj = () => this.owner(e.callee.object, item);
|
|
569
|
+
if (m === 'split' && !args.length) return `the parts of ${obj()}`;
|
|
570
|
+
if (m === 'split' && pos.length === 1) return `${obj()} split at ${paren(this.value(pos[0], item))}`;
|
|
571
|
+
if (m === 'split') nt('split() with a maximum number of parts has no Core form yet');
|
|
572
|
+
if (m === 'join' && pos.length === 1) return `${paren(this.value(pos[0], item))} joined with ${obj()}`;
|
|
573
|
+
if (m === 'replace' && pos.length === 2) return `${obj()} replacing ${paren(this.value(pos[0], item))} with ${paren(this.value(pos[1], item))}`;
|
|
574
|
+
if (m === 'replace') nt('replace() with a count has no Core form yet');
|
|
575
|
+
if ((m === 'startswith' || m === 'endswith') && pos.length === 1) {
|
|
576
|
+
if (pos[0].kind === 'array') nt(`${m}() with a tuple of choices has no Core form yet`);
|
|
577
|
+
return `${obj()} ${m === 'startswith' ? 'starts' : 'ends'} with ${paren(this.value(pos[0], item))}`;
|
|
578
|
+
}
|
|
579
|
+
if (path?.length === 2 && path[0] === 'json' && this.importsJson) {
|
|
580
|
+
if (m === 'loads' && pos.length === 1) return `the JSON data in ${paren(this.value(pos[0], item))}`;
|
|
581
|
+
if (m === 'dumps' && pos.length === 1) return `the JSON text of ${paren(this.value(pos[0], item))}`;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
nt(`calls ${path ? path.join('.') : e.callee?.kind === 'member' ? `.${e.callee.property}()` : 'a computed function'}, which Core does not know`);
|
|
585
|
+
return '';
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
sorted(e, item) {
|
|
589
|
+
const args = e.args || [];
|
|
590
|
+
const list = args.find((a) => a.kind !== 'named');
|
|
591
|
+
const named = Object.fromEntries(args.filter((a) => a.kind === 'named').map((a) => [a.name, a.value]));
|
|
592
|
+
if (!list) nt('sorted() without a list');
|
|
593
|
+
const rev = named.reverse;
|
|
594
|
+
if (rev && !(lit(rev)?.type === 'bool')) nt('reverse= with a computed value has no Core form');
|
|
595
|
+
const down = rev && lit(rev).value;
|
|
596
|
+
if (!named.key) return `${paren(this.value(list, item))} sorted${down ? ' descending' : ''}`;
|
|
597
|
+
const k = named.key;
|
|
598
|
+
const p0 = (k.params || [])[0]; const pn = typeof p0 === 'string' ? p0 : p0?.name;
|
|
599
|
+
const field = k.kind === 'lambda' && (k.params || []).length === 1 && k.body?.kind === 'member' && isName(k.body.object, pn) ? k.body.property : null;
|
|
600
|
+
if (!field) nt('a sort key other than lambda x: x.field has no Core form yet');
|
|
601
|
+
return `${paren(this.value(list, item))} sorted by ${field}${down ? ' descending' : ''}`;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
comprehension(e) {
|
|
605
|
+
if (e.form !== 'list') nt(`a ${e.form} comprehension has no Core form yet`);
|
|
606
|
+
const clauses = e.clauses || [];
|
|
607
|
+
if (clauses.length !== 1) nt('a comprehension with several for clauses has no Core form');
|
|
608
|
+
const g = clauses[0];
|
|
609
|
+
const v = (g.targets || []).length === 1 && isName(g.targets[0]) ? g.targets[0].name : null;
|
|
610
|
+
if (!v || !isName(e.item, v)) nt('only [x for x in items if …] (keeping the items themselves) has a Core form: "items where …"');
|
|
611
|
+
const conds = g.conds || [];
|
|
612
|
+
const src = this.value(g.iter);
|
|
613
|
+
if (!conds.length) return src;
|
|
614
|
+
if (conds.length > 1) nt('several if clauses in one comprehension have no Core form yet');
|
|
615
|
+
return `${paren(src)} where ${this.condition(conds[0], null, v)}`;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** self.other(args) inside a class: the Core function for that method, given the object first. Python picks the
|
|
619
|
+
* method when it runs, so a subclass could replace it; that is written down as an assumption. */
|
|
620
|
+
selfCall(e, item = null) {
|
|
621
|
+
const m = this.fn.method;
|
|
622
|
+
if (!m || e.callee?.kind !== 'member' || !isName(e.callee.object, m.self)) return null;
|
|
623
|
+
const target = this.classMethods?.get(e.callee.property);
|
|
624
|
+
if (!target) nt(`calls ${m.self}.${e.callee.property}(), which is not a method written in ${m.cls} here (it may come from a parent class)`);
|
|
625
|
+
if ((e.args || []).some((a) => a.kind === 'named' || a.kind === 'spread')) nt('a call with name=value or *args inputs has no Core form yet');
|
|
626
|
+
this.assumptions.push({ line: this.line ?? null, says: `${m.self}.${e.callee.property}() is read as ${m.cls}'s own ${e.callee.property}; a subclass that replaces it would run its own version` });
|
|
627
|
+
const vs = [coreName(m.self), ...(e.args || []).map((a) => paren(this.value(a, item)))];
|
|
628
|
+
return `${target.coreName} with ${vs.length === 1 ? vs[0] : `${vs.slice(0, -1).join(', ')} and ${vs.at(-1)}`}`;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
ownCall(f, args, item = null) {
|
|
632
|
+
if (args.some((a) => a.kind === 'named')) nt('a call with name=value inputs has no Core form yet');
|
|
633
|
+
const name = this.own.get(f);
|
|
634
|
+
if (!args.length) return name;
|
|
635
|
+
const vs = args.map((a) => paren(this.value(a, item)));
|
|
636
|
+
return `${name} with ${vs.length === 1 ? vs[0] : `${vs.slice(0, -1).join(', ')} and ${vs.at(-1)}`}`;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function calleePath(e) {
|
|
641
|
+
if (!e) return null;
|
|
642
|
+
if (e.kind === 'name') return [e.name];
|
|
643
|
+
if (e.kind === 'member') { const o = calleePath(e.object); return o ? [...o, e.property] : null; }
|
|
644
|
+
return null;
|
|
645
|
+
}
|