gdp-wired 0.44.0 → 0.45.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/dist/core/c/reader.js +22 -7
- package/dist/core/check.js +3 -2
- package/dist/core/cli.d.ts +1 -0
- package/dist/core/cli.js +136 -6
- package/dist/core/counts.d.ts +1 -1
- package/dist/core/counts.js +30 -12
- package/dist/core/data.d.ts +6 -1
- package/dist/core/data.js +894 -152
- package/dist/core/dsl.d.ts +2 -0
- package/dist/core/dsl.js +88 -10
- package/dist/core/effect-prims.js +2 -2
- package/dist/core/ex/reader.exs +17 -1
- package/dist/core/exists.d.ts +15 -1
- package/dist/core/exists.js +263 -41
- package/dist/core/extract-c.js +19 -12
- package/dist/core/extract-check.d.ts +6 -0
- package/dist/core/extract-check.js +49 -3
- package/dist/core/extract-ex.js +3 -3
- package/dist/core/extract-go-check.js +19 -12
- package/dist/core/extract-go.js +20 -5
- package/dist/core/extract-jvm.js +63 -14
- package/dist/core/extract-print.js +3 -0
- package/dist/core/extract-py.js +3 -3
- package/dist/core/extract-rb.js +3 -3
- package/dist/core/extract-read.d.ts +8 -0
- package/dist/core/extract-read.js +55 -0
- package/dist/core/extract-rs.js +17 -19
- package/dist/core/extract-shapes.js +20 -0
- package/dist/core/extract-sol.js +19 -8
- package/dist/core/extract-step.d.ts +50 -3
- package/dist/core/extract-step.js +289 -58
- package/dist/core/extract-swift.js +20 -13
- package/dist/core/extract.d.ts +1 -0
- package/dist/core/extract.js +27 -2
- package/dist/core/fresh.d.ts +2 -2
- package/dist/core/fresh.js +7 -3
- package/dist/core/go/reader.go +7 -1
- package/dist/core/infer.js +115 -42
- package/dist/core/jvm/JavaReader.java +10 -2
- package/dist/core/jvm/Jvm.java +17 -1
- package/dist/core/jvm/KtReader.java +57 -5
- package/dist/core/machine.d.ts +1 -2
- package/dist/core/machine.js +27 -15
- package/dist/core/py/harness.py +77 -11
- package/dist/core/py/reader.py +50 -5
- package/dist/core/rb/reader.rb +52 -5
- package/dist/core/rs/src/main.rs +10 -0
- package/dist/core/sol/harness.py +6 -3
- package/dist/core/solver.js +5 -4
- package/dist/core/system.d.ts +62 -1
- package/dist/core/system.js +262 -3
- package/dist/core/transfer.js +17 -0
- package/dist/core/watch.js +1 -1
- package/dist/interchange/check.js +10 -10
- package/dist/interchange/format.d.ts +4 -0
- package/dist/interchange/format.js +13 -5
- package/dist/kernel/cdcl.js +33 -2
- package/dist/kernel/epr.js +35 -5
- package/dist/kernel/kernel.d.ts +2 -0
- package/dist/kernel/kernel.js +67 -40
- package/dist/kernel/prove.d.ts +22 -0
- package/dist/kernel/prove.js +156 -7
- package/dist/lean-kernel/emit.d.ts +9 -3
- package/dist/lean-kernel/emit.js +170 -29
- package/dist/lean-kernel/library.js +1 -1
- package/package.json +2 -2
|
@@ -51,7 +51,9 @@ public final class KtReader implements Jvm.Env {
|
|
|
51
51
|
public static void main(String[] argv) throws Exception {
|
|
52
52
|
Map<?, ?> req = (Map<?, ?>) parse(argv[0]);
|
|
53
53
|
Jvm.kotlin = true;
|
|
54
|
-
|
|
54
|
+
String out = null;
|
|
55
|
+
try { out = json(new KtReader().read(req)); } catch (RuntimeException | Error e) { if (!Jvm.overflowed(e)) Jvm.failed("Kotlin", e); Jvm.refuse("the source nests too deeply to read"); }
|
|
56
|
+
System.out.println(out);
|
|
55
57
|
}
|
|
56
58
|
static KtPsiFactory factory() throws Exception {
|
|
57
59
|
CompilerConfiguration cfg = new CompilerConfiguration();
|
|
@@ -68,9 +70,21 @@ public final class KtReader implements Jvm.Env {
|
|
|
68
70
|
Map<String, Object> read(Map<?, ?> req) throws Exception {
|
|
69
71
|
String path = (String) req.get("file"), root = (String) req.get("root");
|
|
70
72
|
src = Files.readString(Path.of(path));
|
|
73
|
+
// (the PSI recovering from deep unclosed nesting took 23 minutes on one source: past MAX_DEPTH brackets it is refused
|
|
74
|
+
// before the parse, as the Rust reader refuses it)
|
|
75
|
+
int depth = 0, most = 0;
|
|
76
|
+
for (int i = 0; i < src.length(); i++) { char c = src.charAt(i); if (c == '(' || c == '[' || c == '{') most = Math.max(most, ++depth); else if (c == ')' || c == ']' || c == '}') depth--; }
|
|
77
|
+
if (most > 1000) Jvm.refuse(new File(path).getName() + ": the source nests " + most + " brackets deep (past 1000)");
|
|
71
78
|
base = new File(path).getName();
|
|
72
79
|
KtPsiFactory f = factory();
|
|
73
80
|
file = f.createFile(base, src);
|
|
81
|
+
// (the PSI recovers from a syntax error and leaves an error element where it was: what the walk past it reads is
|
|
82
|
+
// not the code the compiler would refuse, so the source is refused there)
|
|
83
|
+
com.intellij.psi.PsiErrorElement bad = com.intellij.psi.util.PsiTreeUtil.findChildOfType(file, com.intellij.psi.PsiErrorElement.class);
|
|
84
|
+
if (bad != null) {
|
|
85
|
+
int at = bad.getTextRange().getStartOffset(), line = 1 + (int) src.substring(0, Math.min(at, src.length())).chars().filter(c -> c == '\n').count();
|
|
86
|
+
Jvm.refuse("the source doesn't parse: line " + line + ": " + bad.getErrorDescription());
|
|
87
|
+
}
|
|
74
88
|
pkg = file.getPackageFqName().asString();
|
|
75
89
|
List<Integer> ls = new ArrayList<>(List.of(0));
|
|
76
90
|
for (int i = 0; i < src.length(); i++) if (src.charAt(i) == '\n') ls.add(i + 1);
|
|
@@ -158,7 +172,7 @@ public final class KtReader implements Jvm.Env {
|
|
|
158
172
|
}
|
|
159
173
|
return null;
|
|
160
174
|
}
|
|
161
|
-
static JT boxed(JT t) { String b = UNBOX.get(t.n); return b == null ? t : new JT(b, t.a, t.nul); }
|
|
175
|
+
static JT boxed(JT t) { if (t == null) return null; String b = UNBOX.get(t.n); return b == null ? t : new JT(b, t.a, t.nul); }
|
|
162
176
|
// A JVM parameter's erased type, as the harness looks the method up.
|
|
163
177
|
static String erased(JT t) { if (t == null) return "java.lang.Object"; if (t.nul) return UNBOX.getOrDefault(t.n, t.n); return t.n.equals("void") ? "java.lang.Object" : t.n; }
|
|
164
178
|
@Override public List<String> enumValues(String fq) {
|
|
@@ -389,6 +403,36 @@ public final class KtReader implements Jvm.Env {
|
|
|
389
403
|
}
|
|
390
404
|
return m("id", binOf(c) + "#<init>", "name", "__init__", "cls", selfName, "p", p, "span", List.of(base, 0, 0), "params", prepend(m("name", "self", "t", m("k", "any"), "self", true), params), "ret", m("k", "none"), "body", body, "decorators", List.of());
|
|
391
405
|
}
|
|
406
|
+
// What a data class's copy runs that the subset doesn't read as an update with its init blocks after: a property
|
|
407
|
+
// its body computes from the constructor's parameters (computed again), an init block that sets one, an init block of
|
|
408
|
+
// another class than the one read.
|
|
409
|
+
String copyRuns(KtClassOrObject k) {
|
|
410
|
+
if (!(k instanceof KtClass kc)) return null;
|
|
411
|
+
Set<String> ps = new HashSet<>();
|
|
412
|
+
for (KtParameter pa : kc.getPrimaryConstructorParameters()) ps.add(pa.getName());
|
|
413
|
+
for (KtDeclaration d : body(k)) {
|
|
414
|
+
if (d instanceof KtProperty pr && !computed(pr) && pr.getInitializer() != null && com.intellij.psi.util.PsiTreeUtil.findChildrenOfType(pr.getInitializer(), KtNameReferenceExpression.class).stream().anyMatch(r -> ps.contains(r.getReferencedName())))
|
|
415
|
+
return "a copy of a data class whose property " + pr.getName() + " is computed from its constructor (copy computes it again)";
|
|
416
|
+
if (d instanceof KtAnonymousInitializer ai) {
|
|
417
|
+
if (k != self) return "a copy of another data class with an init block (copy runs it again)";
|
|
418
|
+
if (com.intellij.psi.util.PsiTreeUtil.findChildrenOfType(ai, KtBinaryExpression.class).stream().anyMatch(b -> KtTokens.ALL_ASSIGNMENTS.contains(b.getOperationToken())))
|
|
419
|
+
return "a copy of a data class whose init block sets a property (copy runs it again)";
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return null;
|
|
423
|
+
}
|
|
424
|
+
// The init blocks run on a copy (self): the copy returned.
|
|
425
|
+
String copyCheck(KtClassOrObject k) {
|
|
426
|
+
String id = binOf(k) + "#<copy>";
|
|
427
|
+
if (!funcs.containsKey(id)) {
|
|
428
|
+
Ctx cx = new Ctx(new ArrayList<>(), new HashMap<>(), 0, false);
|
|
429
|
+
List<Object> b = new ArrayList<>();
|
|
430
|
+
for (KtDeclaration d : body(k)) if (d instanceof KtAnonymousInitializer ai && ai.getBody() instanceof KtBlockExpression bl) b.addAll(block(bl.getStatements(), cx, null));
|
|
431
|
+
b.add(s("ret", where(k), "x", self(where(k))));
|
|
432
|
+
funcs.put(id, fn(id, "copy", k, List.of(), new JT(binOf(k)), b, null));
|
|
433
|
+
}
|
|
434
|
+
return id;
|
|
435
|
+
}
|
|
392
436
|
static List<Object> prepend(Object a, List<Object> xs) { List<Object> out = new ArrayList<>(); out.add(a); out.addAll(xs); return out; }
|
|
393
437
|
|
|
394
438
|
// --- statements ------------------------------------------------------------------------------------------------------
|
|
@@ -610,11 +654,13 @@ public final class KtReader implements Jvm.Env {
|
|
|
610
654
|
if (et == KtNodeTypes.INTEGER_CONSTANT) {
|
|
611
655
|
boolean lng = s.endsWith("L") || s.endsWith("l");
|
|
612
656
|
String d = s.replaceAll("[lLuU]+$", "");
|
|
613
|
-
long v
|
|
657
|
+
long v;
|
|
658
|
+
try { v = d.startsWith("0x") || d.startsWith("0X") ? Long.parseLong(d.substring(2), 16) : d.startsWith("0b") || d.startsWith("0B") ? Long.parseLong(d.substring(2), 2) : Long.parseLong(d); }
|
|
659
|
+
catch (NumberFormatException nfe) { return no1(k, "an integer literal past 64 bits"); }
|
|
614
660
|
JT ty = lng || v > Integer.MAX_VALUE || v < Integer.MIN_VALUE ? new JT("long") : want != null && integral(want) ? new JT(prim(want)) : new JT("int");
|
|
615
661
|
return new X(lit(v, ty, p), ty);
|
|
616
662
|
}
|
|
617
|
-
if (et == KtNodeTypes.FLOAT_CONSTANT) { double d = Double.parseDouble(s.replaceAll("[fF]$", "")); return d == Math.floor(d) && Math.abs(d) < 9.007199254740992E15 ? new X(x("int", p, "v", Long.toString((long) d), "float", true), new JT(s.endsWith("f") || s.endsWith("F") ? "float" : "double")) : no1(e, "a float that isn't whole (a binary fraction)"); }
|
|
663
|
+
if (et == KtNodeTypes.FLOAT_CONSTANT) { double d; try { d = Double.parseDouble(s.replaceAll("[fF]$", "")); } catch (NumberFormatException nfe) { return no1(k, "a float literal that isn't a number"); } return d == Math.floor(d) && Math.abs(d) < 9.007199254740992E15 ? new X(x("int", p, "v", Long.toString((long) d), "float", true), new JT(s.endsWith("f") || s.endsWith("F") ? "float" : "double")) : no1(e, "a float that isn't whole (a binary fraction)"); }
|
|
618
664
|
if (et == KtNodeTypes.CHARACTER_CONSTANT) return no1(e, "a character literal");
|
|
619
665
|
}
|
|
620
666
|
if (e instanceof KtStringTemplateExpression st) {
|
|
@@ -890,7 +936,13 @@ public final class KtReader implements Jvm.Env {
|
|
|
890
936
|
if (!args.isEmpty()) return no1(ce, "copy given arguments by position");
|
|
891
937
|
List<Object> fs = new ArrayList<>();
|
|
892
938
|
for (Object k0 : kw) fs.add(k0);
|
|
893
|
-
|
|
939
|
+
Map<String, Object> u = x("upd", p, "x", recv == null ? self(p) : recv.ir(), "fields", fs, "text", t);
|
|
940
|
+
// (copy makes the object anew by its primary constructor: its init blocks run again, on the copy's fields)
|
|
941
|
+
KtClassOrObject of = recv == null ? self : classes.get(recv.t().n);
|
|
942
|
+
String why = copyRuns(of);
|
|
943
|
+
if (why != null) return no1(ce, why);
|
|
944
|
+
if (of != null && body(of).stream().anyMatch(d -> d instanceof KtAnonymousInitializer)) u = m("e", "call", "p", p, "text", t, "f", x("fn", p, "id", copyCheck(of)), "args", List.of(u), "kw", List.of());
|
|
945
|
+
return new X(u, recv == null ? new JT(selfName) : recv.t());
|
|
894
946
|
}
|
|
895
947
|
// a constructor: a class of the code's own (made from its fields), an atomic, a map, a lock
|
|
896
948
|
String ctorOf = recv == null && Character.isUpperCase(n.charAt(0)) ? resolve(n) : null;
|
package/dist/core/machine.d.ts
CHANGED
|
@@ -2,8 +2,6 @@ import { type Constraint, type Verdict } from './solver.js';
|
|
|
2
2
|
export declare const lcg: (x: number) => number;
|
|
3
3
|
export type Rand = (k: number) => number;
|
|
4
4
|
export declare const seeded: (seed: number) => Rand;
|
|
5
|
-
export declare const lcgFloat: (x: number) => number;
|
|
6
|
-
export declare const searchSeeded: (seed: number) => Rand;
|
|
7
5
|
export declare const walk: (t: unknown, f: (o: Record<string, unknown>) => void) => void;
|
|
8
6
|
export declare const walkOnce: (t: unknown, f: (o: object) => void) => void;
|
|
9
7
|
export type E = {
|
|
@@ -252,6 +250,7 @@ export type Compiled = {
|
|
|
252
250
|
};
|
|
253
251
|
};
|
|
254
252
|
export declare const loadJs: (m: Machine) => Compiled;
|
|
253
|
+
export declare function fastStep(m: Machine): ((params: Env, st: State, input: Request) => State) | undefined;
|
|
255
254
|
export type Obligation = {
|
|
256
255
|
phase: 'start' | 'step';
|
|
257
256
|
law: string;
|
package/dist/core/machine.js
CHANGED
|
@@ -10,18 +10,9 @@ import { add, env, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solv
|
|
|
10
10
|
// The one generator of the repo's random draws: x' = (1103515245 x + 12345) mod 2^31, exact (Math.imul). In doubles
|
|
11
11
|
// the product passes 2^53 and rounds, which folds every seed into one of six short cycles (61 to 10,466 steps; 98.8% of
|
|
12
12
|
// seeds into the same one). Its period is 2^31 (core/rand.test.ts). Draws are its high bits (the low ones repeat with a
|
|
13
|
-
// short period). Every test, harness and fuzz draws from it.
|
|
13
|
+
// short period). Every search, test, harness and fuzz draws from it.
|
|
14
14
|
export const lcg = (x) => (Math.imul(x, 1103515245) + 12345) & 0x7fffffff;
|
|
15
15
|
export const seeded = (seed) => { let x = seed; return k => { x = lcg(x); return Math.floor(x / 2 ** 31 * k); }; };
|
|
16
|
-
// The searches still on the float form's stream (one 10,466-step cycle whatever the seed): infer.ts's runs and
|
|
17
|
-
// candidates, data.ts's rng, and the CHC and ITS runners' own runs (which feed infer). Under exact draws their results
|
|
18
|
-
// hinge on the draw: over 20 seed shifts, the system test's lease 1, the infer test's in-flight bound 15, the CHC task
|
|
19
|
-
// s_split_22 2, frontier2's break_safe 18, and bstInsert 9 (data.ts: which 240 random models its search compares terms
|
|
20
|
-
// in decides it, 0 of 8 shifts with the models fixed, the same 01001101 with only the models shifted). The rest of the
|
|
21
|
-
// searches (dsl's walks, nonterm, effect's runs, discover, live, cycles, fresh, xstate, the extractors' checks) draw
|
|
22
|
-
// from `seeded`. One moves to `seeded` once its result no longer turns on the draw.
|
|
23
|
-
export const lcgFloat = (x) => (x * 1103515245 + 12345) % 2 ** 31;
|
|
24
|
-
export const searchSeeded = (seed) => { let x = seed; return k => { x = lcgFloat(x); return Math.floor(x / 2 ** 31 * k); }; };
|
|
25
16
|
// Every object in a term, the term first.
|
|
26
17
|
export const walk = (t, f) => {
|
|
27
18
|
if (Array.isArray(t)) {
|
|
@@ -221,10 +212,12 @@ const exact = (v) => {
|
|
|
221
212
|
throw new RangeError('a value passed 2^53 - 1, past which the proofs over the naturals no longer describe the run');
|
|
222
213
|
return v;
|
|
223
214
|
};
|
|
215
|
+
// (a value is a number: a name like constructor or toString, read through an object's prototype, is no value of it)
|
|
216
|
+
const num = (x) => (typeof x === 'number' ? x : undefined);
|
|
224
217
|
export function evalE(e, env, st, m) {
|
|
225
218
|
switch (e.op) {
|
|
226
219
|
case 'var': {
|
|
227
|
-
const v = env[e.name] ?? st.scalars[e.name];
|
|
220
|
+
const v = num(env[e.name]) ?? num(st.scalars[e.name]);
|
|
228
221
|
if (v === undefined)
|
|
229
222
|
throw new Error(`no value for ${e.name}`);
|
|
230
223
|
return v;
|
|
@@ -238,13 +231,13 @@ export function evalE(e, env, st, m) {
|
|
|
238
231
|
case 'max': return Math.max(evalE(e.a, env, st, m), evalE(e.b, env, st, m));
|
|
239
232
|
case 'if': return evalC(e.c, env, st, m) ? evalE(e.then, env, st, m) : evalE(e.else, env, st, m);
|
|
240
233
|
case 'get': {
|
|
241
|
-
const fn = m.fns
|
|
234
|
+
const fn = m.fns && Object.hasOwn(m.fns, e.map) ? m.fns[e.map] : undefined, args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
|
|
242
235
|
if (args) {
|
|
243
236
|
const xs = args.map(a => evalE(a, env, st, m));
|
|
244
237
|
return naturalIn(callOf(fn)(...xs), `${e.map}(${xs.join(', ')})`);
|
|
245
238
|
}
|
|
246
239
|
const key = evalE(e.key, env, st, m);
|
|
247
|
-
return fn ? naturalIn(fnOf(fn)(key), `${e.map}(${key})`) : st.maps[e.map].get(key) ?? st.defaults
|
|
240
|
+
return fn ? naturalIn(fnOf(fn)(key), `${e.map}(${key})`) : st.maps[e.map].get(key) ?? (st.defaults && Object.hasOwn(st.defaults, e.map) ? st.defaults[e.map] : undefined) ?? m.maps[e.map];
|
|
248
241
|
}
|
|
249
242
|
}
|
|
250
243
|
}
|
|
@@ -314,7 +307,7 @@ export function compileE(e, m) {
|
|
|
314
307
|
switch (e.op) {
|
|
315
308
|
case 'var': {
|
|
316
309
|
const name = e.name;
|
|
317
|
-
return (env, st) => { const v = env[name] ?? st.scalars[name]; if (v === undefined)
|
|
310
|
+
return (env, st) => { const v = num(env[name]) ?? num(st.scalars[name]); if (v === undefined)
|
|
318
311
|
throw new Error(`no value for ${name}`); return v; };
|
|
319
312
|
}
|
|
320
313
|
case 'const': {
|
|
@@ -674,7 +667,7 @@ export function compileJs(m) {
|
|
|
674
667
|
case 'max': return `Math.max(${ex(e.a)}, ${ex(e.b)})`;
|
|
675
668
|
case 'if': return `(${cx(e.c)} ? ${ex(e.then)} : ${ex(e.else)})`;
|
|
676
669
|
case 'get': {
|
|
677
|
-
const fn = m.fns
|
|
670
|
+
const fn = m.fns && Object.hasOwn(m.fns, e.map) ? m.fns[e.map] : undefined, args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
|
|
678
671
|
if (args)
|
|
679
672
|
return `$n(fnc${fns.indexOf(e.map)}(${args.map(ex).join(', ')}), ${id(`${e.map}()`)})`;
|
|
680
673
|
return fns.includes(e.map) ? `$n(fn${fns.indexOf(e.map)}(${ex(e.key)}), ${id(`${e.map}()`)})` : `(maps[${id(e.map)}].get(${ex(e.key)}) ?? ${carriedMaps.includes(e.map) ? '0' : `dft[${id(e.map)}] ?? ${plain.maps[e.map]}`})`;
|
|
@@ -787,6 +780,25 @@ export function compileFunction(params, body) {
|
|
|
787
780
|
return new Function(...params, body);
|
|
788
781
|
}
|
|
789
782
|
export const loadJs = (m) => compileFunction([], `${compileJs(m).replace(/^export function/gm, 'function')}\nreturn {init, fork, step}`)();
|
|
783
|
+
// The interpreter's step (persistent: a copy of the state each) through loadJs's, several times faster, a request's counts
|
|
784
|
+
// given to it as maps the request carries (carriedView's, each cell its sum when read); none with a history, or where the
|
|
785
|
+
// generator refuses the machine.
|
|
786
|
+
export function fastStep(m) {
|
|
787
|
+
const cs = Object.keys(m.counts ?? {});
|
|
788
|
+
let js;
|
|
789
|
+
try {
|
|
790
|
+
if (m.history)
|
|
791
|
+
return undefined;
|
|
792
|
+
js = loadJs({ ...m, counts: undefined, inputMaps: [...m.inputMaps ?? [], ...cs] });
|
|
793
|
+
}
|
|
794
|
+
catch {
|
|
795
|
+
return undefined;
|
|
796
|
+
}
|
|
797
|
+
return (params, st, input) => {
|
|
798
|
+
const view = cs.length ? carriedView(m, st, input, undefined, params).maps : {};
|
|
799
|
+
return js.step(params, js.fork(st), cs.length ? { ...input, ...Object.fromEntries(cs.map(c => [c, view[c]])) } : input);
|
|
800
|
+
};
|
|
801
|
+
}
|
|
790
802
|
const cross = (as, f) => as.flatMap(a => f(a.value).map(b => ({ path: [...a.path, ...b.path], value: b.value })));
|
|
791
803
|
// Every way a key can differ from each of some focus keys.
|
|
792
804
|
const apartFrom = (key, keys) => keys.reduce((acc, f) => acc.flatMap(p => [[...p, ...lt(key, f)], [...p, ...lt(f, key)]]), [[]]);
|
package/dist/core/py/harness.py
CHANGED
|
@@ -9,6 +9,7 @@ import time as time_module
|
|
|
9
9
|
|
|
10
10
|
NOW = [0]
|
|
11
11
|
CUR = {}
|
|
12
|
+
EFF = {}
|
|
12
13
|
HIT = set()
|
|
13
14
|
S = {}
|
|
14
15
|
|
|
@@ -38,6 +39,13 @@ def resolve(q):
|
|
|
38
39
|
mod, _, name = q.rpartition('.')
|
|
39
40
|
return getattr(importlib.import_module(mod), name)
|
|
40
41
|
|
|
42
|
+
class Inert:
|
|
43
|
+
"""An attribute of a store the rule leaves out (a registry the constructor adds to): its calls do nothing."""
|
|
44
|
+
def __getattr__(self, name):
|
|
45
|
+
if name.startswith('__'): raise AttributeError(name)
|
|
46
|
+
return Inert()
|
|
47
|
+
def __call__(self, *a, **k): return None
|
|
48
|
+
|
|
41
49
|
class FakeStore:
|
|
42
50
|
"""A store as the caller stated it: get, set and delete over a dict that keeps what is set (no expiry)."""
|
|
43
51
|
def __init__(self, decl, name=None):
|
|
@@ -45,9 +53,17 @@ class FakeStore:
|
|
|
45
53
|
for path, v in (decl.get('attrs') or {}).items():
|
|
46
54
|
o, parts = self, path.split('.')
|
|
47
55
|
for p in parts[:-1]:
|
|
48
|
-
if not
|
|
56
|
+
if p not in vars(o): setattr(o, p, types.SimpleNamespace())
|
|
49
57
|
o = getattr(o, p)
|
|
50
58
|
setattr(o, parts[-1], v)
|
|
59
|
+
# (an attribute the rule leaves out, a registry the constructor adds to: inert, its calls doing nothing)
|
|
60
|
+
for i in S.get('inert') or []:
|
|
61
|
+
if i['store'] != name: continue
|
|
62
|
+
o, parts = self, i['path'].split('.')
|
|
63
|
+
for p in parts[:-1]:
|
|
64
|
+
if p not in vars(o): setattr(o, p, types.SimpleNamespace())
|
|
65
|
+
o = getattr(o, p)
|
|
66
|
+
if parts[-1] not in vars(o): setattr(o, parts[-1], Inert())
|
|
51
67
|
asyncs = decl.get('async') or {}
|
|
52
68
|
def mk(kind, name):
|
|
53
69
|
# (the key by position, or as key= or name=, redis-py's; nx and xx as redis-py's: True where it set, else None)
|
|
@@ -59,7 +75,16 @@ class FakeStore:
|
|
|
59
75
|
self.data[key] = val
|
|
60
76
|
if k.get('nx') or k.get('xx'): return True
|
|
61
77
|
def delete(*a, **k): self.data.pop(kk(a, k), None)
|
|
62
|
-
|
|
78
|
+
# (add: set where the key holds nothing, True where it set; incr: by amount, absent as 0, the new number)
|
|
79
|
+
def add(*a, **k):
|
|
80
|
+
key = kk(a, k)
|
|
81
|
+
if key in self.data: return False
|
|
82
|
+
self.data[key] = k.get('value', a[1] if len(a) > 1 else None)
|
|
83
|
+
return True
|
|
84
|
+
def incr(*a, **k):
|
|
85
|
+
key = kk(a, k); self.data[key] = (self.data.get(key) or 0) + k.get('amount', a[1] if len(a) > 1 else 1)
|
|
86
|
+
return self.data[key]
|
|
87
|
+
f0, key = {'get': get, 'set': set_, 'delete': delete, 'add': add, 'incr': incr}[kind], f"{self.name}.{name}"
|
|
63
88
|
# (where the request says the operation raises, inside a try that catches it)
|
|
64
89
|
def f(*a, **k):
|
|
65
90
|
r = (CUR.get(key) or {}).get('raise')
|
|
@@ -69,15 +94,29 @@ class FakeStore:
|
|
|
69
94
|
async def af(*a, **k): return f(*a, **k)
|
|
70
95
|
return af
|
|
71
96
|
return f
|
|
72
|
-
|
|
73
|
-
|
|
97
|
+
own = set()
|
|
98
|
+
for kind, dflt in (('get', ['get', 'async_get_cache', 'get_cache']), ('set', ['set', 'async_set_cache', 'set_cache']), ('delete', ['delete', 'delete_cache', 'async_delete_cache']), ('add', []), ('incr', [])):
|
|
99
|
+
for m in decl.get(kind) or dflt: setattr(self, m, mk(kind, m)); own.add(m)
|
|
74
100
|
# (a method left out: nothing, as the rule takes it; any other is no method of this store, and fails)
|
|
75
101
|
for m in decl.get('skip') or []:
|
|
76
102
|
async def anop(*a, **k): return None
|
|
77
103
|
setattr(self, m, (lambda *a, **k: anop()) if asyncs.get(m) else (lambda *a, **k: None))
|
|
78
|
-
# (an injected dependency's other methods: each answered by the request's input
|
|
104
|
+
# (an injected dependency's other methods: each answered by the request's input; one left out does nothing, and
|
|
105
|
+
# raises where the request says, as its get, set and delete do)
|
|
79
106
|
for a in S.get('answers') or []:
|
|
80
|
-
if a['patch'].get('store')
|
|
107
|
+
if a['patch'].get('store') != name: continue
|
|
108
|
+
if not a['patch'].get('path'):
|
|
109
|
+
if os.environ.get('GDP_HARNESS_LOG'):
|
|
110
|
+
with open(os.environ['GDP_HARNESS_LOG'], 'a') as f: f.write(f"a store's answer with no method: {json.dumps(a)[:400]}\n")
|
|
111
|
+
continue
|
|
112
|
+
m = a['patch']['path'][-1]
|
|
113
|
+
if a['patch'].get('store') == name and a.get('effect'):
|
|
114
|
+
def rec(key, is_async):
|
|
115
|
+
def f(*x, **k): EFF[key] = True
|
|
116
|
+
async def af(*x, **k): EFF[key] = True
|
|
117
|
+
return af if is_async else f
|
|
118
|
+
setattr(self, m, rec(a['key'], a['async']))
|
|
119
|
+
elif a['patch'].get('store') == name and not (a.get('pass') and m in own): setattr(self, m, stub(a['key'], a['async'], (lambda *x, **k: None) if a.get('pass') else None))
|
|
81
120
|
|
|
82
121
|
def build(spec, stores):
|
|
83
122
|
if 'in' in spec:
|
|
@@ -169,7 +208,7 @@ def state_of(obj, stores):
|
|
|
169
208
|
if f.get('opt'): c[f['name'] + '_has'] = x is not None
|
|
170
209
|
c[f['name']] = (x if x is not None else (f['vals'][0] if f.get('choice') else 0)) if f.get('choice') else enc_num(0 if x is None else x)
|
|
171
210
|
cells[h] = c
|
|
172
|
-
else: cells[h] = {'value': v if l.get('choice') else enc_num(v)}
|
|
211
|
+
else: cells[h] = {'value': v if l.get('choice') else (v.decode('latin-1') if isinstance(v, (bytes, bytearray)) else v) if l.get('str') else enc_num(int(v) if isinstance(v, bool) else v)}
|
|
173
212
|
s[l['name']] = cells
|
|
174
213
|
continue
|
|
175
214
|
v = walk(obj, l['path'])
|
|
@@ -211,7 +250,7 @@ def set_state(obj, stores, state):
|
|
|
211
250
|
for h, c in (v or {}).items():
|
|
212
251
|
at = pre + h + post if '{}' in l['tpl'] else l['tpl']
|
|
213
252
|
if l.get('json'): st.data[at] = json.dumps({f['name']: (c[f['name']] if f.get('choice') else num_in(c[f['name']], False)) for f in l['json'] if not f.get('out') and (not f.get('opt') or c.get(f['name'] + '_has'))})
|
|
214
|
-
else: st.data[at] = c['value'] if l.get('choice') else num_in(c['value'], l.get('float'))
|
|
253
|
+
else: st.data[at] = c['value'] if l.get('choice') or l.get('str') else num_in(c['value'], l.get('float'))
|
|
215
254
|
continue
|
|
216
255
|
if k == 'num': put(obj, l['path'], num_in(v, l.get('float')))
|
|
217
256
|
elif k in ('str', 'choice', 'bool'): put(obj, l['path'], v.encode('latin-1') if k == 'str' and is_bytes(l) and isinstance(v, str) else v)
|
|
@@ -365,6 +404,19 @@ def hello(req):
|
|
|
365
404
|
S['self_stubs'] = []
|
|
366
405
|
for a in req['answers']:
|
|
367
406
|
p = a['patch']
|
|
407
|
+
# (an effect: a call recorded, nothing run, None returned)
|
|
408
|
+
if a.get('effect'):
|
|
409
|
+
def rec(key, is_async):
|
|
410
|
+
def f(*x, **k): EFF[key] = True
|
|
411
|
+
async def af(*x, **k): EFF[key] = True
|
|
412
|
+
return af if is_async else f
|
|
413
|
+
f = rec(a['key'], a['async'])
|
|
414
|
+
if p.get('store'): continue
|
|
415
|
+
if p.get('self'): S['self_stubs'].append((p['self'], {**a, 'effect_fn': f})); continue
|
|
416
|
+
o, name = patch_target(p)
|
|
417
|
+
raw = inspect.getattr_static(o, name, None)
|
|
418
|
+
setattr(o, name, staticmethod(f) if isinstance(raw, staticmethod) else f)
|
|
419
|
+
continue
|
|
368
420
|
if p.get('store'): continue
|
|
369
421
|
if p.get('self'): S['self_stubs'].append((p['self'], a))
|
|
370
422
|
else:
|
|
@@ -387,8 +439,13 @@ def make(args):
|
|
|
387
439
|
try:
|
|
388
440
|
with pinned(): obj = run(S['cls'](**kw))
|
|
389
441
|
finally: sys.settrace(None)
|
|
390
|
-
for name, a in S['self_stubs']: obj.__dict__[name] = stub(a['key'], a['async'], getattr(obj, name) if a.get('pass') else None)
|
|
442
|
+
for name, a in S['self_stubs']: obj.__dict__[name] = a['effect_fn'] if a.get('effect_fn') else stub(a['key'], a['async'], getattr(obj, name) if a.get('pass') else None)
|
|
391
443
|
for name in S.get('inject') or []: setattr(obj, name, build({'store': name}, OBJ_STORES))
|
|
444
|
+
# (fields stated: the object configured so after its constructor, as the claim says)
|
|
445
|
+
for f, v in (S.get('fields') or {}).items(): setattr(obj, f, v)
|
|
446
|
+
# (a module's object stated as a store: the store in its place, this object's while it runs)
|
|
447
|
+
for g in S.get('globals') or []: build({'store': g['name']}, OBJ_STORES)
|
|
448
|
+
set_globals(OBJ_STORES)
|
|
392
449
|
i = len(OBJS) + 1
|
|
393
450
|
OBJS[i] = (obj, OBJ_STORES)
|
|
394
451
|
return i
|
|
@@ -396,12 +453,17 @@ def make(args):
|
|
|
396
453
|
def run(x):
|
|
397
454
|
return S['loop'].run_until_complete(x) if inspect.isawaitable(x) else x
|
|
398
455
|
|
|
456
|
+
def set_globals(stores):
|
|
457
|
+
for g in S.get('globals') or []: setattr(importlib.import_module(g['mod']), g['name'], stores[g['name']])
|
|
458
|
+
|
|
399
459
|
def call(req):
|
|
400
460
|
obj, stores = OBJS[req['id']]
|
|
401
461
|
global OBJ_STORES
|
|
402
462
|
OBJ_STORES = stores
|
|
463
|
+
set_globals(stores)
|
|
403
464
|
NOW[0] = int(req.get('now') or 0)
|
|
404
465
|
CUR.clear(); CUR.update(req.get('answers') or {})
|
|
466
|
+
EFF.clear()
|
|
405
467
|
fn = getattr(obj, req['m']) if S['cls'] is not None else getattr(S['mod'], req['m'])
|
|
406
468
|
kwargs = fixed_args(req['a'], {})
|
|
407
469
|
before = frames(obj if S['cls'] is not None else None)
|
|
@@ -422,7 +484,7 @@ def call(req):
|
|
|
422
484
|
after = frames(obj if S['cls'] is not None else None)
|
|
423
485
|
for k in before:
|
|
424
486
|
if after.get(k) != before[k]: return {'frame': k}
|
|
425
|
-
return {'out': tag(out), **({'err': err} if err is not None else {})}
|
|
487
|
+
return {'out': tag(out), **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
|
|
426
488
|
|
|
427
489
|
def main():
|
|
428
490
|
fin = open(sys.argv[1], 'r'); fout = open(sys.argv[2], 'w')
|
|
@@ -434,7 +496,11 @@ def main():
|
|
|
434
496
|
if op == 'hello': res = hello(req)
|
|
435
497
|
elif op == 'new':
|
|
436
498
|
try: res = {'id': make(req['a'])}
|
|
437
|
-
except Exception as e:
|
|
499
|
+
except Exception as e:
|
|
500
|
+
res = {'err': f"{type(e).__name__}: {e}"[:300]}
|
|
501
|
+
if os.environ.get('GDP_HARNESS_LOG'):
|
|
502
|
+
import traceback
|
|
503
|
+
with open(os.environ['GDP_HARNESS_LOG'], 'a') as f: traceback.print_exc(file=f)
|
|
438
504
|
elif op == 'at':
|
|
439
505
|
try:
|
|
440
506
|
i = make(req['a'])
|
package/dist/core/py/reader.py
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
# arguments carry are read from the repository's own modules (their class annotations, never run).
|
|
6
6
|
#
|
|
7
7
|
# python3 -I core/py/reader.py '{"root": <repo>, "file": <file>, "names": [<classes or functions>]}'
|
|
8
|
-
import ast, builtins, json, os, sys
|
|
8
|
+
import ast, builtins, contextlib, importlib, io, json, os, sys, types
|
|
9
9
|
|
|
10
10
|
BUILTINS = {'min', 'max', 'abs', 'len', 'int', 'float', 'bool', 'str', 'isinstance', 'round', 'sum', 'any', 'all', 'print', 'repr', 'getattr', 'setattr', 'hasattr', 'type', 'list', 'dict', 'set', 'tuple', 'sorted', 'range', 'zip', 'enumerate'}
|
|
11
11
|
# Library functions the executor knows (their meaning, not their code).
|
|
@@ -40,6 +40,25 @@ def injected(d):
|
|
|
40
40
|
f = d.func if isinstance(d, ast.Call) else d.value if isinstance(d, ast.Subscript) else None
|
|
41
41
|
return (dotted(f) or '').split('.')[-1] in ('Depends', 'Provide', 'Inject') if f is not None else False
|
|
42
42
|
|
|
43
|
+
def missing(q):
|
|
44
|
+
"""Why the attribute path q (a module's, `logging.getLo`) fails where it runs, or None: the module object's own method
|
|
45
|
+
(`m.__init__`), or a name a module of Python's own library doesn't have (that module imported to look: the code
|
|
46
|
+
imports it too)."""
|
|
47
|
+
parts = q.split('.')
|
|
48
|
+
for i, n in enumerate(parts[1:], 1):
|
|
49
|
+
if n.startswith('__') and callable(getattr(types.ModuleType, n, None)): return f"{'.'.join(parts[:i + 1])}: the module object's own method (its machinery, outside the subset)"
|
|
50
|
+
if parts[0] not in getattr(sys, 'stdlib_module_names', ()) or parts[0] in ('this', 'antigravity', '__main__'): return None
|
|
51
|
+
try:
|
|
52
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): o = importlib.import_module(parts[0])
|
|
53
|
+
for i, n in enumerate(parts[1:], 1):
|
|
54
|
+
if hasattr(o, n): o = getattr(o, n); continue
|
|
55
|
+
if not isinstance(o, types.ModuleType): return None
|
|
56
|
+
try:
|
|
57
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): o = importlib.import_module('.'.join(parts[:i + 1]))
|
|
58
|
+
except ImportError: return f"{'.'.join(parts[:i + 1])}: {'.'.join(parts[:i])} has no {n} (an AttributeError where it runs)"
|
|
59
|
+
except Exception: return None
|
|
60
|
+
return None
|
|
61
|
+
|
|
43
62
|
class Repo:
|
|
44
63
|
"""The repository's modules, parsed once each, for the classes an annotation names."""
|
|
45
64
|
def __init__(self, root):
|
|
@@ -76,6 +95,22 @@ class Module:
|
|
|
76
95
|
self.imports, self.classes, self.funcs, self.consts = {}, {}, {}, {}
|
|
77
96
|
for n in (self.tree.body if self.tree else []):
|
|
78
97
|
self.scan(n)
|
|
98
|
+
# (the module's variables a function rebinds, `global x`: no constant, every call shares them; and the names the
|
|
99
|
+
# module binds at its top level and in its classes' bodies, or may through `from m import *`: past them and a
|
|
100
|
+
# function's own, a name is a NameError where it runs)
|
|
101
|
+
walk = list(ast.walk(self.tree)) if self.tree else []
|
|
102
|
+
self.rebound = {g for x in walk if isinstance(x, ast.Global) for g in x.names}
|
|
103
|
+
self.star = any(isinstance(x, ast.ImportFrom) and any(a.name == '*' for a in x.names) for x in walk)
|
|
104
|
+
self.bound, todo = set(self.rebound), list(self.tree.body if self.tree else [])
|
|
105
|
+
while todo:
|
|
106
|
+
x = todo.pop()
|
|
107
|
+
if isinstance(x, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): self.bound.add(x.name)
|
|
108
|
+
if isinstance(x, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): continue
|
|
109
|
+
if isinstance(x, ast.Name) and not isinstance(x.ctx, ast.Load): self.bound.add(x.id)
|
|
110
|
+
if isinstance(x, (ast.Import, ast.ImportFrom)): self.bound |= {(a.asname or a.name).split('.')[0] for a in x.names}
|
|
111
|
+
if isinstance(x, (ast.ExceptHandler, ast.MatchAs, ast.MatchStar)) and x.name: self.bound.add(x.name)
|
|
112
|
+
if isinstance(x, ast.MatchMapping) and x.rest: self.bound.add(x.rest)
|
|
113
|
+
todo.extend(x.body if isinstance(x, ast.ClassDef) else ast.iter_child_nodes(x))
|
|
79
114
|
def scan(self, n):
|
|
80
115
|
if isinstance(n, ast.Import):
|
|
81
116
|
for a in n.names: self.imports[(a.asname or a.name).split('.')[0]] = ('module', a.name if a.asname else a.name.split('.')[0])
|
|
@@ -194,7 +229,11 @@ class Reader:
|
|
|
194
229
|
name, t = n.targets[0].attr, self.ty(anns[v.values[0].id], mod)
|
|
195
230
|
if t['k'] == 'opt': t = t['of']
|
|
196
231
|
if t is not None and not any(g['name'] == name for g in fields): fields.append({'name': name, 't': t, 'init': True})
|
|
232
|
+
cattrs = {}
|
|
197
233
|
for n in cdef.body:
|
|
234
|
+
# (a class attribute set to a constant, PREFIX = None, LOCK_PERIOD = 5: read through self as that constant)
|
|
235
|
+
if isinstance(n, ast.Assign) and len(n.targets) == 1 and isinstance(n.targets[0], ast.Name) and isinstance(n.value, ast.Constant) and isinstance(n.value.value, (int, float, str, bool, type(None))) and not isinstance(n.value.value, bytes):
|
|
236
|
+
cattrs[n.targets[0].id] = n.value.value
|
|
198
237
|
if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name):
|
|
199
238
|
ann = n.annotation
|
|
200
239
|
if dotted(ann.value if isinstance(ann, ast.Subscript) else ann) in ('ClassVar', 'typing.ClassVar'): continue
|
|
@@ -212,7 +251,7 @@ class Reader:
|
|
|
212
251
|
finally: self.file, self.supers = file, sup
|
|
213
252
|
methods[n.name] = fid
|
|
214
253
|
else: methods[n.name] = None # another module's method: not read
|
|
215
|
-
r = {'name': q, 'short': cdef.name, 'fields': fields, 'methods': methods, 'bases': bases, 'p': where(mod.path, cdef),
|
|
254
|
+
r = {'name': q, 'short': cdef.name, 'fields': fields, 'methods': methods, 'bases': bases, 'p': where(mod.path, cdef), 'cattrs': cattrs,
|
|
216
255
|
'kinds': sorted(kinds | ({'dataclass'} if dataclass else set()) | ({'frozen'} if frozen else set()) | (set() if total else {'partial'})),
|
|
217
256
|
'own': mod.path == self.file, 'module': mod.name, **({'rets': rets} if rets else {})}
|
|
218
257
|
self.recs[q] = r
|
|
@@ -362,7 +401,8 @@ class Reader:
|
|
|
362
401
|
return [{'s': 'expr', 'p': p, 'x': E(s.value)}]
|
|
363
402
|
if isinstance(s, ast.Pass): return []
|
|
364
403
|
if isinstance(s, (ast.Assign, ast.AnnAssign)):
|
|
365
|
-
|
|
404
|
+
# (a declaration, `x: int`; of a field or an item, `o.f: int`, its object evaluated, and the item's index)
|
|
405
|
+
if s.value is None: return [] if isinstance(s.target, ast.Name) else [{'s': 'expr', 'p': p, 'x': E(y)} for y in ([s.target.value] + ([s.target.slice] if isinstance(s.target, ast.Subscript) else []))]
|
|
366
406
|
targets = s.targets if isinstance(s, ast.Assign) else [s.target]
|
|
367
407
|
x = E(s.value)
|
|
368
408
|
ann = self.ty(s.annotation, mod) if isinstance(s, ast.AnnAssign) else None
|
|
@@ -458,6 +498,7 @@ class Reader:
|
|
|
458
498
|
def name(self, n, mod, p):
|
|
459
499
|
"""What a name is where it is read: a local, a constant, a function or class of the module, an import, a builtin."""
|
|
460
500
|
if self.local_stack and n in self.local_stack[-1]: return {'e': 'var', 'n': n, 'p': p}
|
|
501
|
+
if n in mod.rebound: return {'e': 'no', 'why': f"{n}: a module variable a function rebinds (global {n}), shared by every call", 'p': p}
|
|
461
502
|
if n in mod.funcs: return {'e': 'fn', 'id': n, 'p': p}
|
|
462
503
|
if n in mod.classes:
|
|
463
504
|
q = self.rec_of(mod, mod.classes[n])
|
|
@@ -486,7 +527,9 @@ class Reader:
|
|
|
486
527
|
return {'e': 'ext', 'q': f"{mod.name}.{n}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'global': True, 'p': p}
|
|
487
528
|
if n in ('True', 'False', 'None'): return self.expr(ast.Constant({'True': True, 'False': False, 'None': None}[n]), mod)
|
|
488
529
|
if n in BUILTINS: return {'e': 'builtin', 'n': n, 'p': p}
|
|
489
|
-
|
|
530
|
+
if n not in mod.bound and not mod.star and not hasattr(builtins, n) and not (n.startswith('__') and n.endswith('__')):
|
|
531
|
+
return {'e': 'no', 'why': f"{n}: a name the module doesn't define, import or bind (a NameError where it runs)", 'raises': True, 'p': p}
|
|
532
|
+
return {'e': 'ext', 'q': n, 'text': n, 'p': p}
|
|
490
533
|
def expr(self, x, mod):
|
|
491
534
|
r = self.expr1(x, mod)
|
|
492
535
|
if r.get('e') == 'no' and 'names' not in r: r['names'] = mentioned(x)
|
|
@@ -515,6 +558,8 @@ class Reader:
|
|
|
515
558
|
if d and base in mod.imports and mod.imports[base][0] == 'module' and not (self.local_stack and base in self.local_stack[-1]):
|
|
516
559
|
q = mod.imports[base][1] + d[len(base):]
|
|
517
560
|
if q in KNOWN: return {'e': 'lib', 'q': q, 'p': p}
|
|
561
|
+
why = missing(q) if not self.repo.path_of(q.split('.')[0]) else None
|
|
562
|
+
if why: return {'e': 'no', 'why': why, 'raises': True, 'p': p}
|
|
518
563
|
ret = self.ret_of(q.rpartition('.')[0], q.rpartition('.')[2])
|
|
519
564
|
return {'e': 'ext', 'q': q, 'text': d, 'patch': {'mod': mod.name, 'path': d.split('.')}, 'p': p, **({'ret': ret} if ret else {})}
|
|
520
565
|
return {'e': 'get', 'x': E(x.value), 'f': x.attr, 'p': p, 'text': text(x)}
|
|
@@ -593,7 +638,7 @@ def main():
|
|
|
593
638
|
print(json.dumps({'error': f"{req['file']} doesn't parse"})); return
|
|
594
639
|
out = {'lang': 'python', 'file': os.path.basename(r.file), 'path': r.file, 'module': mod.name, 'root': os.path.abspath(req['root']), 'entries': [],
|
|
595
640
|
# (the module's constants bound to literals, as the code reads them: a law may name them too)
|
|
596
|
-
'consts': {k: v.value for k, v in ((k, r.const_value(mod, v)) for k, v in mod.consts.items()) if isinstance(v, ast.Constant) and isinstance(v.value, (int, float, str, bool)) and not (isinstance(v.value, float) and not v.value.is_integer())}}
|
|
641
|
+
'consts': {k: v.value for k, v in ((k, r.const_value(mod, v)) for k, v in mod.consts.items() if k not in mod.rebound) if isinstance(v, ast.Constant) and isinstance(v.value, (int, float, str, bool)) and not (isinstance(v.value, float) and not v.value.is_integer())}}
|
|
597
642
|
for n in req['names'] or list(mod.classes):
|
|
598
643
|
if n in mod.classes: out['entries'].append({'k': 'class', 'rec': r.rec_of(mod, mod.classes[n])})
|
|
599
644
|
elif n in mod.funcs:
|
package/dist/core/rb/reader.rb
CHANGED
|
@@ -18,8 +18,10 @@ class Reader
|
|
|
18
18
|
def initialize(req)
|
|
19
19
|
@root, @file, @clocks = File.expand_path(req['root']), File.expand_path(req['file']), req['clocks'] || []
|
|
20
20
|
@base = File.basename(@file)
|
|
21
|
-
@consts = {}
|
|
22
|
-
|
|
21
|
+
@consts, @defined, @mods = {}, [], {}
|
|
22
|
+
# (open: a constant may come from what the code requires, a gem's, or a Gemfile's bundle, or be made as it runs)
|
|
23
|
+
@open = %w[Gemfile gems.rb].any? { |g| File.exist?(File.join(@root, g)) } || !Dir.glob(File.join(@root, '*.gemspec')).empty?
|
|
24
|
+
([@file] | Dir.glob(File.join(@root, '**', '*.rb'))).each { |f| index_consts(f) rescue nil }
|
|
23
25
|
@recs, @funcs, @loads = {}, {}, []
|
|
24
26
|
@caught = []
|
|
25
27
|
end
|
|
@@ -28,8 +30,25 @@ class Reader
|
|
|
28
30
|
def index_consts(f)
|
|
29
31
|
walk = lambda do |n, nest|
|
|
30
32
|
case n
|
|
31
|
-
when Prism::ModuleNode, Prism::ClassNode
|
|
33
|
+
when Prism::ModuleNode, Prism::ClassNode
|
|
34
|
+
q = (nest + [n.constant_path.slice]).join('::')
|
|
35
|
+
@defined << q
|
|
36
|
+
# (its singleton methods and the names each one's body calls on it; open where its body may add others)
|
|
37
|
+
md = (@mods[q] ||= {defs: {}, open: false, cls: n.is_a?(Prism::ClassNode)})
|
|
38
|
+
md[:open] = true if n.is_a?(Prism::ClassNode) && n.superclass
|
|
39
|
+
(n.body&.body || []).each do |m|
|
|
40
|
+
if m.is_a?(Prism::DefNode) && m.receiver.is_a?(Prism::SelfNode)
|
|
41
|
+
calls = []
|
|
42
|
+
each_node(m) { |c| calls << c.name.to_s if c.is_a?(Prism::CallNode) && !c.receiver }
|
|
43
|
+
md[:defs][m.name.to_s] = calls
|
|
44
|
+
elsif m.is_a?(Prism::SingletonClassNode) || (m.is_a?(Prism::CallNode) && !%i[attr_reader attr_writer attr_accessor private public protected].include?(m.name))
|
|
45
|
+
md[:open] = true
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
n.body&.body&.each { |m| walk.(m, nest + [n.constant_path.slice]) }
|
|
49
|
+
when Prism::ConstantPathWriteNode then @defined << (nest + [n.target.slice]).join('::')
|
|
32
50
|
when Prism::ConstantWriteNode
|
|
51
|
+
@defined << (nest + [n.name.to_s]).join('::')
|
|
33
52
|
v = n.value
|
|
34
53
|
lit = case v
|
|
35
54
|
when Prism::SymbolNode then {'e' => 'str', 'v' => v.unescaped, 'sym' => true}
|
|
@@ -40,7 +59,29 @@ class Reader
|
|
|
40
59
|
@consts[(nest + [n.name.to_s]).join('::')] = lit.merge('file' => f) if lit
|
|
41
60
|
end
|
|
42
61
|
end
|
|
43
|
-
Prism.parse_file(f).value
|
|
62
|
+
tree = Prism.parse_file(f).value
|
|
63
|
+
tree.statements.body.each { |n| walk.(n, []) }
|
|
64
|
+
each_node(tree) { |n| @open = true if !@open && n.is_a?(Prism::CallNode) && %i[require load autoload const_set const_missing eval instance_eval class_eval module_eval].include?(n.name) }
|
|
65
|
+
end
|
|
66
|
+
# Why Mod.m fails where it runs, a module or class under the root whose singleton methods the reader sees all of: no
|
|
67
|
+
# such method, or its body calls a name nothing defines; else nil.
|
|
68
|
+
def no_method(r, n, nest)
|
|
69
|
+
return nil if @open
|
|
70
|
+
full = r.slice.sub(/\A::/, '')
|
|
71
|
+
q = nest.length.downto(0).map { |i| (nest[0, i] + [full]).join('::') }.find { |k| @mods.key?(k) }
|
|
72
|
+
md = q && @mods[q]
|
|
73
|
+
return nil if !md || md[:open]
|
|
74
|
+
known = ->(m) { md[:defs].key?(m) || (md[:cls] ? Class.new : Module.new).respond_to?(m, true) }
|
|
75
|
+
return "#{full} defines no #{n} (a NoMethodError where it runs)" unless known.(n.to_s)
|
|
76
|
+
gone = md[:defs][n.to_s].reject { |m| known.(m) }
|
|
77
|
+
gone.empty? ? nil : "#{full}.#{n} calls #{gone.first}, which nothing defines (a NameError where it runs)"
|
|
78
|
+
end
|
|
79
|
+
# Whether a constant is defined: under the root (a class, a module, a constant), by Ruby itself, or maybe by what the
|
|
80
|
+
# code requires.
|
|
81
|
+
def defined_const?(n, nest)
|
|
82
|
+
full = n.slice.sub(/\A::/, '')
|
|
83
|
+
@open || nest.length.downto(0).any? { |i| @defined.include?((nest[0, i] + [full]).join('::')) } || @defined.any? { |k| k.end_with?("::#{full}") } ||
|
|
84
|
+
(Object.const_defined?(full) rescue true)
|
|
44
85
|
end
|
|
45
86
|
# A constant's literal, and the file defining it kept (the check loads it before the file read).
|
|
46
87
|
def const(n, nest)
|
|
@@ -395,7 +436,13 @@ class Reader
|
|
|
395
436
|
else
|
|
396
437
|
return no(x, "#{text(x)}: a method of an array") if r.is_a?(Prism::ArrayNode)
|
|
397
438
|
# (another class's code: at the boundary where it is inferred, with the names its arguments mention)
|
|
398
|
-
return no(x, "#{text(x)}: #{r.slice},
|
|
439
|
+
return no(x, "#{text(x)}: #{r.slice}, a constant nothing under the root defines (a NameError where it runs)").merge('raises' => true) if (r.is_a?(Prism::ConstantReadNode) || r.is_a?(Prism::ConstantPathNode)) && !defined_const?(r, @nest)
|
|
440
|
+
if r.is_a?(Prism::ConstantReadNode) || r.is_a?(Prism::ConstantPathNode)
|
|
441
|
+
why = no_method(r, n, @nest)
|
|
442
|
+
return no(x, "#{text(x)}: #{why}").merge('raises' => true) if why
|
|
443
|
+
# (its arguments evaluated, as the code does: what fails there fails the step)
|
|
444
|
+
return no(x, "#{text(x)}: #{r.slice}, another class's code").merge('ext' => "#{r.slice}.#{n}", 'names' => mentioned(args), 'args' => args.map { |a| expr(a) }, 'patch' => {'mod' => r.slice, 'path' => [n.to_s]})
|
|
445
|
+
end
|
|
399
446
|
call({'e' => 'get', 'x' => rv, 'f' => n.to_s, 'p' => p, 'text' => text(x)}, args.map { |a| expr(a) }, x)
|
|
400
447
|
end
|
|
401
448
|
end
|