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.
Files changed (66) hide show
  1. package/dist/core/c/reader.js +22 -7
  2. package/dist/core/check.js +3 -2
  3. package/dist/core/cli.d.ts +1 -0
  4. package/dist/core/cli.js +136 -6
  5. package/dist/core/counts.d.ts +1 -1
  6. package/dist/core/counts.js +30 -12
  7. package/dist/core/data.d.ts +6 -1
  8. package/dist/core/data.js +894 -152
  9. package/dist/core/dsl.d.ts +2 -0
  10. package/dist/core/dsl.js +88 -10
  11. package/dist/core/effect-prims.js +2 -2
  12. package/dist/core/ex/reader.exs +17 -1
  13. package/dist/core/exists.d.ts +15 -1
  14. package/dist/core/exists.js +263 -41
  15. package/dist/core/extract-c.js +19 -12
  16. package/dist/core/extract-check.d.ts +6 -0
  17. package/dist/core/extract-check.js +49 -3
  18. package/dist/core/extract-ex.js +3 -3
  19. package/dist/core/extract-go-check.js +19 -12
  20. package/dist/core/extract-go.js +20 -5
  21. package/dist/core/extract-jvm.js +63 -14
  22. package/dist/core/extract-print.js +3 -0
  23. package/dist/core/extract-py.js +3 -3
  24. package/dist/core/extract-rb.js +3 -3
  25. package/dist/core/extract-read.d.ts +8 -0
  26. package/dist/core/extract-read.js +55 -0
  27. package/dist/core/extract-rs.js +17 -19
  28. package/dist/core/extract-shapes.js +20 -0
  29. package/dist/core/extract-sol.js +19 -8
  30. package/dist/core/extract-step.d.ts +50 -3
  31. package/dist/core/extract-step.js +289 -58
  32. package/dist/core/extract-swift.js +20 -13
  33. package/dist/core/extract.d.ts +1 -0
  34. package/dist/core/extract.js +27 -2
  35. package/dist/core/fresh.d.ts +2 -2
  36. package/dist/core/fresh.js +7 -3
  37. package/dist/core/go/reader.go +7 -1
  38. package/dist/core/infer.js +115 -42
  39. package/dist/core/jvm/JavaReader.java +10 -2
  40. package/dist/core/jvm/Jvm.java +17 -1
  41. package/dist/core/jvm/KtReader.java +57 -5
  42. package/dist/core/machine.d.ts +1 -2
  43. package/dist/core/machine.js +27 -15
  44. package/dist/core/py/harness.py +77 -11
  45. package/dist/core/py/reader.py +50 -5
  46. package/dist/core/rb/reader.rb +52 -5
  47. package/dist/core/rs/src/main.rs +10 -0
  48. package/dist/core/sol/harness.py +6 -3
  49. package/dist/core/solver.js +5 -4
  50. package/dist/core/system.d.ts +62 -1
  51. package/dist/core/system.js +262 -3
  52. package/dist/core/transfer.js +17 -0
  53. package/dist/core/watch.js +1 -1
  54. package/dist/interchange/check.js +10 -10
  55. package/dist/interchange/format.d.ts +4 -0
  56. package/dist/interchange/format.js +13 -5
  57. package/dist/kernel/cdcl.js +33 -2
  58. package/dist/kernel/epr.js +35 -5
  59. package/dist/kernel/kernel.d.ts +2 -0
  60. package/dist/kernel/kernel.js +67 -40
  61. package/dist/kernel/prove.d.ts +22 -0
  62. package/dist/kernel/prove.js +156 -7
  63. package/dist/lean-kernel/emit.d.ts +9 -3
  64. package/dist/lean-kernel/emit.js +170 -29
  65. package/dist/lean-kernel/library.js +1 -1
  66. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
- import { Refusal, pathOf } from "./extract-read.js";
2
- import { asset, entryNames, extractStep, node, stubbed } from "./extract-step.js";
1
+ import { Refusal, pathOf, readerRun, statedRefusal } from "./extract-read.js";
2
+ import { asset, buildCheck, compileLimit, entryNames, extractStep, node, stubbed } from "./extract-step.js";
3
3
  export { proveRule, proveSteps } from "./dsl.js";
4
4
  const env = () => globalThis.process?.env ?? {};
5
5
  const errText = (e) => { const ls = `${e.stdout ?? ''}\n${e.stderr ?? ''}`.split('\n'); return (ls.filter(l => /\berror:/.test(l)).length ? ls.filter(l => /\berror:/.test(l)) : ls.filter(l => /error|fatal/i.test(l))).slice(0, 4).join(' | ').slice(0, 900) || String(e.message).slice(0, 300); };
@@ -97,10 +97,10 @@ export function readSwift(at, names, o = {}) {
97
97
  const pkg = swiftPackage(at, o);
98
98
  let out;
99
99
  try {
100
- out = cp.execFileSync(swiftReader(o), [pkg.root, pkg.file ?? '-', names.length ? names.join(',') : '-', o.ctor === undefined ? '-' : String(o.ctor), ...pkg.files], { encoding: 'utf8', maxBuffer: 1 << 29, stdio: ['ignore', 'pipe', 'pipe'] });
100
+ out = cp.execFileSync(swiftReader(o), [pkg.root, pkg.file ?? '-', names.length ? names.join(',') : '-', o.ctor === undefined ? '-' : String(o.ctor), ...pkg.files], { encoding: 'utf8', maxBuffer: 1 << 29, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() });
101
101
  }
102
102
  catch (e) {
103
- throw new Refusal(at, `the Swift reader didn't run (${errText(e)})`);
103
+ throw new Refusal(at, statedRefusal(e) ?? `the Swift reader didn't run (${errText(e)})`);
104
104
  }
105
105
  const mod = JSON.parse(out);
106
106
  mod.module = pkg.target;
@@ -257,10 +257,13 @@ function harnessCode(g, mod, read, cls) {
257
257
  // the request; those left out doing nothing; any other one a crash, which the check reports).
258
258
  const fakes = [], fakeOf = new Map();
259
259
  const init = mod.funcs[cls.methods.__init__ ?? ''], ctorParams = init?.params.filter(p => !p.self) ?? [];
260
+ // (an argument of a protocol of the files read that nothing the rule keeps reads: a fake as a store's, doing nothing)
261
+ const protoOf = (n) => { const pa = ctorParams.find(p => p.name === n), pt = pa?.t.k === 'opt' ? pa.t.of : pa?.t; return pt?.k === 'rec' ? mod.recs[pt.name] : undefined; };
262
+ const faked = (n, a) => a?.k === 'store' || (a?.k === 'inert' && !!protoOf(n)?.swift?.reqs);
260
263
  for (const [name, a] of read.ctor) {
261
- if (a.k !== 'store')
264
+ if (!faked(name, a))
262
265
  continue;
263
- const pa = ctorParams.find(p => p.name === name), pt = pa?.t.k === 'opt' ? pa.t.of : pa?.t, pr = pt?.k === 'rec' ? mod.recs[pt.name] : undefined;
266
+ const pr = protoOf(name);
264
267
  if (!pr?.swift?.reqs)
265
268
  throw new Refusal(cls.p, `${cls.short}(${name}): an injected dependency of a protocol outside the files read (the check can't make one)`);
266
269
  if (pr.swift.assoc)
@@ -297,7 +300,7 @@ function harnessCode(g, mod, read, cls) {
297
300
  const ctor = sw.ctor ?? { labels: [], throws: false, types: [] };
298
301
  const made = ctorParams.map((pa, i) => {
299
302
  const a = read.ctor.find(([n]) => n === pa.name)?.[1], lab = ctor.labels[i] ?? '_', arg = (x) => (lab === '_' ? x : `${lab}: ${x}`);
300
- if (a?.k === 'store')
303
+ if (faked(pa.name, a))
301
304
  return arg(`${fakeOf.get(pa.name)}({ let __s = __GdpStore(); __gdpS.cur[${JSON.stringify(pa.name)}] = __s; return __s }())`);
302
305
  return arg(conv(pa.t, `a?[${i}]?[1]`, mod));
303
306
  });
@@ -435,6 +438,11 @@ function harnessFor(pkg, mod, read, opts) {
435
438
  let et = changed.get(ef) ?? text(ef);
436
439
  if (cls.swift.kind === 'actor')
437
440
  et = et.replace(new RegExp(`\\bactor(\\s+${cls.short}\\b)`), 'final class$1').replace(/\bnonisolated(\(unsafe\))?\s+/g, '');
441
+ // (the lines of the code itself in each file the check appends to: an error past them is the harness's)
442
+ const own = new Map();
443
+ own.set(rel(ef), et.split('\n').length);
444
+ for (const f of g.edits.keys())
445
+ own.set(rel(f), (changed.get(f) ?? text(f)).split('\n').length);
438
446
  changed.set(ef, `${et}\n${code.entry}`);
439
447
  for (const [f, exts] of g.edits)
440
448
  changed.set(f, `${changed.get(f) ?? text(f)}\n${exts.join('\n')}\n`);
@@ -466,12 +474,11 @@ function harnessFor(pkg, mod, read, opts) {
466
474
  fs.mkdirSync(path.dirname(path.join(work, l)), { recursive: true });
467
475
  node('node:fs').symlinkSync(to, path.join(work, l));
468
476
  }
469
- try {
470
- cp.execFileSync(swiftOf(opts), ['build', '--product', 'GdpHarness', '--package-path', work], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 28 });
471
- }
472
- catch (e) {
473
- return { cmd: 'false', args: [], hello: {}, error: `the package doesn't build with the check's harness: ${errText(e)}` };
474
- }
477
+ const built = buildCheck('swift build', () => cp.execFileSync(swiftOf(opts), ['build', '--product', 'GdpHarness', '--package-path', work], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 28, timeout: compileLimit(), killSignal: 'SIGKILL' }), e => `${e.stdout ?? ''}\n${e.stderr ?? ''}`.split('\n').filter(l => /\.swift:\d+:\d+: error:/.test(l)), l => { const m = /([^\s]+\.swift):(\d+):\d+: error:/.exec(l); if (!m)
478
+ return false; const r = path.relative(work, m[1]); if (r.startsWith('GdpHarness/'))
479
+ return false; const n = own.get(r); return n === undefined || Number(m[2]) <= n; });
480
+ if (!('ok' in built))
481
+ return { cmd: 'false', args: [], hello: {}, error: built.why, kind: built.kind };
475
482
  const bin = cp.execFileSync(swiftOf(opts), ['build', '--package-path', work, '--show-bin-path'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
476
483
  return { cmd: `${bin}/GdpHarness`, args: [], hello: {} };
477
484
  }
@@ -62,6 +62,7 @@ export type Name = {
62
62
  export declare function namesOf(m: Model): Name[];
63
63
  export declare function extract(at: Source, opts?: ExtractOptions): Extraction;
64
64
  export declare function fromModel(model: Model, file: string, domains: Record<string, 'nat' | 'int'> | undefined, notes: string[], run: (rule: Rule, sorts: Sorts) => Evidence): Extraction;
65
+ export declare const HARNESS_FAILED = "the check's harness failed, twice (a request past its time or its transport, not the code): ";
65
66
  export declare const toSource: (x: Extraction) => string;
66
67
  export type { Evidence, Model, Term };
67
68
  export { Refusal };
@@ -41,7 +41,7 @@ import * as dsl from "./dsl.js";
41
41
  import { compileFunction, walk } from "./machine.js";
42
42
  import * as I from "./extract-ir.js";
43
43
  import { PASS } from "./extract-ir.js";
44
- import { Refusal, placed, sourceOf } from "./extract-read.js";
44
+ import { Refusal, placed, sourceOf, syntaxError, tooDeep } from "./extract-read.js";
45
45
  import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice } from "./extract-shapes.js";
46
46
  import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pnum, pterm, sortsOf } from "./extract-print.js";
47
47
  import { check } from "./extract-check.js";
@@ -97,6 +97,9 @@ export function extract(at, opts = {}) {
97
97
  try {
98
98
  ;
99
99
  ({ code, file } = sourceOf(at, opts.file, 'input.ts'));
100
+ const bad = syntaxError(code, file);
101
+ if (bad)
102
+ throw new Refusal(file, bad);
100
103
  const fns = Array.isArray(opts.entry) ? opts.entry : opts.functions;
101
104
  const o = { ...opts, entry: (Array.isArray(opts.entry) ? opts.entry[0] : opts.entry) ?? fns?.[0] ?? '', ...(fns ? { functions: fns } : {}) };
102
105
  model = o.entry ? readModel(code, file, o, opts.shape) : inferred(code, file, o, opts.shape);
@@ -105,6 +108,8 @@ export function extract(at, opts = {}) {
105
108
  catch (e) {
106
109
  if (e instanceof Refusal)
107
110
  return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
111
+ if (tooDeep(e))
112
+ return { ok: false, refusals: [{ where: opts.file ?? (typeof at === 'string' && !at.includes('\n') ? at : 'input.ts'), what: 'the source nests too deeply to read' }], notes };
108
113
  throw e;
109
114
  }
110
115
  return { ...fromModel(model, file, opts.domains, notes, (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model) };
@@ -163,10 +168,16 @@ export function fromModel(model, file, domains, notes, run) {
163
168
  if (invariants.length)
164
169
  source = `${source}\n// What every state of the code is: a law about every state is about the code's with these beside it.\nexport const ${identOf(model)}Invariants = [${invariantsOf(model, sorts).map(x => x.replace(/^r\./, `${identOf(model)}Rule.`)).join(', ')}]\n`;
165
170
  const evidence = run(rule, sorts);
171
+ if (evidence.source)
172
+ return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: evidence.source }], notes };
173
+ if (evidence.harness)
174
+ return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: `${HARNESS_FAILED}${evidence.harness}` }], notes };
166
175
  if (evidence.mismatch)
167
176
  return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: `the rule and the code differ: ${evidence.mismatch}` }], notes };
168
177
  return { ok: true, rule, ...(invariants.length ? { invariants } : {}), source, model, sorts, evidence, refusals: [], notes };
169
178
  }
179
+ // The check's own failure (twice): no verdict on the code, neither a difference nor a pass.
180
+ export const HARNESS_FAILED = 'the check\'s harness failed, twice (a request past its time or its transport, not the code): ';
170
181
  // A Date holds a time within ±8.64e15 ms; past it the code's Date is invalid (NaN). The rule refuses a step that would
171
182
  // set one there (as it refuses a sum past 2^53), and a start there: its claim stops at the Date's range.
172
183
  const DATE_MAX = 8_640_000_000_000_000;
@@ -337,7 +348,21 @@ function builderOf(m, sorts) {
337
348
  sorts.delete('k$');
338
349
  continue;
339
350
  }
340
- const vals = d.fields.map(f => `${f.name}: ${pterm(w.vals[f.name], P, { m, sorts, atoms: [w.has] }, `${n}.${f.name}`)}`);
351
+ // (a field printed where the key is held; where that reading differs from the term itself, by cases, so a key the
352
+ // step leaves unheld holds what it writes there: a delete's defaults)
353
+ const vals = d.fields.map(f => {
354
+ const t = w.vals[f.name], at = `${n}.${f.name}`, yes = pterm(t, P, { m, sorts, atoms: [w.has] }, at);
355
+ if (w.has.op === 'const' || yes === pterm(t, P, ctx(), at))
356
+ return `${f.name}: ${yes}`;
357
+ let no;
358
+ try {
359
+ no = pterm(t, P, { m, sorts, atoms: [I.not(w.has)] }, at);
360
+ }
361
+ catch {
362
+ return `${f.name}: ${pterm(t, P, ctx(), at)}`;
363
+ }
364
+ return `${f.name}: when(${pb(w.has, P, ctx())}, ${yes}, ${no})`;
365
+ });
341
366
  outs.push([n, `${n}.set(${pk(w.key, P, ctx())}, {${[`has: ${pb(w.has, P, ctx())}`, ...vals].join(', ')}})`]);
342
367
  }
343
368
  // A list's write: its apply over the operations by cases (each under its condition).
@@ -4,6 +4,6 @@ export type FreshLaw = {
4
4
  law: Law;
5
5
  text: string;
6
6
  };
7
- export declare function freshLaws(m: Machine, kinds: Law[], draws: Draws, opts?: {
7
+ export declare const freshLaws: (m: Machine, kinds: Law[], draws: Draws, opts?: {
8
8
  ms?: number;
9
- }): FreshLaw[];
9
+ }) => FreshLaw[];
@@ -9,10 +9,14 @@
9
9
  // (Houdini: a candidate whose goal fails is dropped, the rest proven again). Nothing new is trusted: what is kept is
10
10
  // laws the kernel proves.
11
11
  import { evalC, interpret, seeded } from "./machine.js";
12
- import { clock, proveLaws } from "../kernel/prove.js";
12
+ import { clock, counted, fullRate, proveSetFast, withDeadline } from "../kernel/prove.js";
13
13
  import { allowed, watch } from "./watch.js";
14
14
  const v = (name) => ({ op: 'var', name }), get = (map, key) => ({ op: 'get', map, key });
15
- export function freshLaws(m, kinds, draws, opts = {}) {
15
+ // The budget is counted (kernel/prove.ts's cost model), as the invariant search's is: what is found is the same on any
16
+ // machine. Houdini's set proofs are proveSetFast's, each round reusing the goals the last one settled.
17
+ // (the deadline too, so a round's goals stop at the budget's end)
18
+ export const freshLaws = (m, kinds, draws, opts = {}) => counted(fullRate, () => withDeadline(clock() + (opts.ms ?? 5000), () => fresh(m, kinds, draws, opts)), true);
19
+ function fresh(m, kinds, draws, opts) {
16
20
  const maps = Object.entries(m.maps ?? {}).filter(([n]) => !(m.inputMaps ?? []).includes(n));
17
21
  if (!maps.length || m.history)
18
22
  return [];
@@ -90,7 +94,7 @@ export function freshLaws(m, kinds, draws, opts = {}) {
90
94
  while (alive.length && clock() < until) {
91
95
  let out;
92
96
  try {
93
- out = proveLaws(m, [...kinds, ...alive.map(f => f.law)]);
97
+ out = proveSetFast(m, [...kinds, ...alive.map(f => f.law)]);
94
98
  }
95
99
  catch {
96
100
  return [];
@@ -56,7 +56,7 @@ func main() {
56
56
  for _, f := range files {
57
57
  a, err := parser.ParseFile(fset, f, nil, parser.SkipObjectResolution)
58
58
  if err != nil {
59
- fail(err)
59
+ refuse("the source doesn't parse: " + strings.SplitN(err.Error(), "\n", 2)[0])
60
60
  }
61
61
  asts = append(asts, a)
62
62
  }
@@ -283,6 +283,12 @@ func fail(err error) {
283
283
  os.Exit(1)
284
284
  }
285
285
 
286
+ // A source the reader can't read, said so (core/extract-read.ts's statedRefusal).
287
+ func refuse(why string) {
288
+ fmt.Fprintln(os.Stderr, "gdp: refused: "+why)
289
+ os.Exit(3)
290
+ }
291
+
286
292
  // --- positions ------------------------------------------------------------------------------------------------------
287
293
  func pos(p token.Pos) string {
288
294
  if !p.IsValid() {
@@ -32,7 +32,7 @@
32
32
  // rules it out (and the most of those seen) is added; a chosen candidate that nothing supports, or that makes a proof slow, is dropped; the set proven as a whole
33
33
  // is the answer, after each chosen candidate the proof doesn't need is taken out again
34
34
  import { quietly } from "./cyclic.js";
35
- import { all, any, atMost, carriedView, compileC, compileE, loadJs, divisorsIn, evalC, evalE, get, interpret, machineTerms, fnValue, modName, n, not, plus, same, searchSeeded, times, walk, withArithmetic, x } from "./machine.js";
35
+ import { all, any, atMost, carriedView, compileC, compileE, fastStep, divisorsIn, evalC, evalE, get, interpret, machineTerms, fnValue, modName, n, not, plus, same, seeded, times, walk, withArithmetic, x } from "./machine.js";
36
36
  import { bool, proveRule, proveSteps, verdictOf } from "./dsl.js";
37
37
  import { allowed, keysOf, linKey, watch } from "./watch.js";
38
38
  import { clock, counted, fullWork, decideLaw, decideNote, machineKey, memoHits, withStrict, fullRate, grow, keyValue, lawInstances, proveLaw, proveLaws, proveSetFast, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees, withWall, withWork } from "../kernel/prove.js";
@@ -208,7 +208,7 @@ function pairingOf(m) {
208
208
  // key's key is of its map's, and two keys compared (k = src) are of one sort. Union-find over those places; a law's own
209
209
  // keys are named apart (`L:law:key`). What a view of a law needs of it: its keys' sorts, the composed keys its reads
210
210
  // name, its guards on its keys alone, the maps read at a plain key of a sort, and the keys a state holds of a sort.
211
- function keySorts(m, laws, pairing) {
211
+ function keySorts(m, laws, pairing, fine = false) {
212
212
  const parent = new Map();
213
213
  const find = (a) => { const p2 = parent.get(a); if (p2 === undefined || p2 === a)
214
214
  return a; const r = find(p2); parent.set(a, r); return r; };
@@ -216,7 +216,7 @@ function keySorts(m, laws, pairing) {
216
216
  parent.set(ra, rb); };
217
217
  const composed = new Set(), plainRead = new Set();
218
218
  const split = (key, name) => {
219
- if (!pairing?.n)
219
+ if (!pairing?.n || fine)
220
220
  return undefined;
221
221
  const lin = new Map();
222
222
  if (!linKey(key, () => true, 1, lin))
@@ -228,7 +228,8 @@ function keySorts(m, laws, pairing) {
228
228
  const a = hi && name(hi[0]), b = lo && name(lo[0]);
229
229
  return a && b ? [a, b] : undefined;
230
230
  };
231
- // (a key of three or more parts, N²·a + N·b + c: its parts, each a place of its own, `${k}:${i}`)
231
+ // (a key of three or more parts, N²·a + N·b + c: its parts, each a place of its own, `${k}:${i}`; `fine`, the engine's:
232
+ // of two parts too, so a map's row and column are sorts of their own unless a key read in both unites them)
232
233
  const arity = new Map();
233
234
  const parts = (key, name) => {
234
235
  if (!pairing?.n)
@@ -237,7 +238,7 @@ function keySorts(m, laws, pairing) {
237
238
  if (!linKey(key, () => true, 1, lin) || (lin.get('1') ?? 0) !== pairing.c)
238
239
  return undefined;
239
240
  const vs = [...lin].filter(([v, c]) => v !== '1' && c).sort((a, b) => b[1] - a[1]), ns = vs.map(([v]) => name(v));
240
- return vs.length >= 3 && vs.every(([, c], i) => c === pairing.n ** (vs.length - 1 - i)) && ns.every(Boolean) ? ns : undefined;
241
+ return vs.length >= (fine ? 2 : 3) && vs.every(([, c], i) => c === pairing.n ** (vs.length - 1 - i)) && ns.every(Boolean) ? ns : undefined;
241
242
  };
242
243
  const kids = (t, f) => { for (const v of Object.values(t))
243
244
  if (v && typeof v === 'object')
@@ -294,6 +295,13 @@ function keySorts(m, laws, pairing) {
294
295
  union(a, b);
295
296
  return;
296
297
  }
298
+ // (`fine`: a key compared with a cell, as a value it holds (Table[a·N + k] = v + 1), is of the cells' values' sort)
299
+ if (fine && t.op === '=')
300
+ for (const [c, e] of [[t.a, t.b], [t.b, t.a]]) {
301
+ const vr = e.op === 'var' ? e : e.op === 'add' && e.a.op === 'var' && e.b.op === 'const' ? e.a : undefined;
302
+ if (c.op === 'get' && c.map in (m.maps ?? {}) && vr && name(vr.name))
303
+ union(name(vr.name), `V:${c.map}`);
304
+ }
297
305
  // (a write at every key of k parts at one: z = N²·n + N·k + v)
298
306
  if (t.op === '=' && t.a.op === 'var' && name(t.a.name)?.startsWith('M:')) {
299
307
  const mp = name(t.a.name).slice(2), ps = parts(t.b, name);
@@ -312,6 +320,15 @@ function keySorts(m, laws, pairing) {
312
320
  walk({ op: 'get', map: mp, key: w.key }, rule);
313
321
  walk(w.value, rule);
314
322
  }
323
+ // (`fine`: a value written to a cell, an input or one past it, of the cells' values' sort)
324
+ if (fine) {
325
+ const leaves = (e) => (e.op === 'if' ? [...leaves(e.then), ...leaves(e.else)] : [e]);
326
+ for (const l of leaves(w.value)) {
327
+ const vr = l.op === 'var' ? l : l.op === 'add' && l.a.op === 'var' && l.b.op === 'const' ? l.a : undefined;
328
+ if (vr && rule(vr.name))
329
+ union(vr.name, `V:${mp}`);
330
+ }
331
+ }
315
332
  }
316
333
  for (const e of Object.values(m.step.state ?? {}))
317
334
  walk(e, rule);
@@ -767,25 +784,37 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
767
784
  if ((first.proven && first.checked) || first.run)
768
785
  return { ...first, found: [], stats: stats(0, 0, 0) };
769
786
  // --- runs ------------------------------------------------------------------------------------------------------------
770
- const run = interpret(m), rand = searchSeeded(17), kinds = rule ? rule.kindsOfState() : [];
787
+ const run = interpret(m), rand = seeded(17), kinds = rule ? rule.kindsOfState() : [];
771
788
  const given = rule ? [...rule.kindLaws().filter(k => !laws.some(l => l.name === k.name)), ...laws] : laws;
772
789
  const randomParams = (bound, r = rand) => (rule ? rule.randomParams(r, bound) : Object.fromEntries(m.params.map(p => [p, r(bound + 1)])));
773
790
  const randomInput = (params, bound, r = rand) => (rule ? rule.randomInput(r, bound, params)
774
791
  : { ...Object.fromEntries(m.inputs.map(i => [i, r(bound + 1)])), ...Object.fromEntries((m.inputMaps ?? []).map(i => [i, new Map()])) });
775
- const samples = [], cap = 3000;
776
- const keep = (s) => { if (samples.length < cap)
777
- samples.push(s);
778
- else if (rand(4) === 0)
779
- samples[rand(cap)] = s; };
792
+ // (each state once: a machine with no requests walks one path, and its copies pushed out the caller's states (opts.seen))
793
+ const samples = [], cap = 3000, keys = [], held = new Set();
794
+ const mapsText = (st) => JSON.stringify(Object.values(st.maps).map(c => [...c]));
795
+ let offered = 0;
796
+ // (how many states offered held each value of each state variable: `rare`, below)
797
+ const stateVars = Object.keys(m.state), seenAt = stateVars.map(() => new Map()), withMaps = Object.keys(m.maps ?? {}).length > 0;
798
+ const keep = (s) => {
799
+ offered++;
800
+ stateVars.forEach((v, i) => { const x2 = s.st.scalars[v] ?? 0; seenAt[i].set(x2, (seenAt[i].get(x2) ?? 0) + 1); });
801
+ const k = JSON.stringify([s.params, s.st.scalars, s.st.defaults ?? 0]) + mapsText(s.st), i = held.has(k) ? -1 : samples.length < cap ? samples.length : rand(4) === 0 ? rand(cap) : -1;
802
+ if (i < 0)
803
+ return;
804
+ if (i < samples.length)
805
+ held.delete(keys[i]);
806
+ samples[i] = s;
807
+ keys[i] = k;
808
+ held.add(k);
809
+ };
780
810
  for (const st of opts.seen ?? [])
781
811
  if (!m.params.length)
782
812
  keep({ params: {}, st });
783
813
  trace('start');
784
- const mapsText = (st) => JSON.stringify(Object.values(st.maps).map(c => [...c]));
785
- // Counted: `runs` requests tried at least, and on until the samples are full (a trial keeps its start at least, so as
786
- // many trials as they hold fill them), the trials at most `runs` or that many. Timed: `runsMs` of wall time.
814
+ // Counted: `runs` requests tried at least, and on until as many states as the samples hold were offered (a trial offers
815
+ // its start at least), the trials at most `runs` or that many. Timed: `runsMs` of wall time.
787
816
  const runsTimed = timed || opts.runsMs !== undefined, runsUntil = Math.min(wallUntil, performance.now() + (opts.runsMs ?? 500)), least = opts.runs ?? Math.min(inferRuns, Math.max(2000, 4 * ms));
788
- const moreRuns = (trial) => (runsTimed ? performance.now() < runsUntil : trial < Math.max(cap, least) && (used.tries < least || samples.length < cap) && !stop());
817
+ const moreRuns = (trial) => (runsTimed ? performance.now() < runsUntil : trial < Math.max(cap, least) && (used.tries < least || offered < cap) && !stop());
789
818
  let trials = 0;
790
819
  // (an assumption with "there exists", a value the request brings, may admit no request at a small bound, a multiple
791
820
  // of 5 but 0, say: a trial whose steps moved nothing doubles the bound at once)
@@ -793,21 +822,41 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
793
822
  for (let trial = 0, bound = 2, stuck = false; moreRuns(trial); trial++, bound = trial % 20 === 0 || stuck ? (bound >= 1024 ? 2 : bound * 2) : bound) {
794
823
  stuck = false;
795
824
  trials++;
796
- const params = randomParams(bound);
797
- if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m))
798
- continue;
799
- let st;
800
- try {
801
- st = run.init(params);
825
+ // (a rule with maps: one trial in four goes on from a sample, of 64 drawn, holding the value of a state variable the
826
+ // fewest states offered held, its requests at the smallest bound. The hull's bounds come from the states past the
827
+ // usual, which runs from the start seldom reach (a ticket lock's service at 2 in 2 to 9 of 3,000 samples, the join
828
+ // then dropping the forms they left too tight one at a time), and a key or two at a time step on from them. On rules
829
+ // of scalars alone, CHC's and ITS's programs, measured, it cost more than it found: s_split_22 29 -> 7 of 40 seeds)
830
+ const rare = withMaps && trial % 4 === 3 && stateVars.length > 0 && samples.length >= 64;
831
+ let params, st;
832
+ if (rare) {
833
+ const v = rand(stateVars.length), seen = (q) => seenAt[v].get(q.st.scalars[stateVars[v]] ?? 0) ?? 0;
834
+ let q0 = samples[rand(samples.length)];
835
+ for (let q = 1; q < 64; q++) {
836
+ const o = samples[rand(samples.length)];
837
+ if (seen(o) < seen(q0))
838
+ q0 = o;
839
+ }
840
+ ;
841
+ ({ params, st } = q0);
802
842
  }
803
- catch {
804
- continue;
843
+ else {
844
+ // (params at a bound of their own every other trial, at 0 one in twenty: a small budget with large costs, all-0 params)
845
+ params = randomParams(trial % 20 === 1 ? 0 : trial % 2 ? bound : 2 ** rand(11));
846
+ if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m))
847
+ continue;
848
+ try {
849
+ st = run.init(params);
850
+ }
851
+ catch {
852
+ continue;
853
+ }
854
+ keep({ params, st });
805
855
  }
806
- keep({ params, st });
807
856
  let took = 0;
808
857
  for (let d = 0, tries = 0; d < 40 && tries < 200; tries++) {
809
858
  used.tries++;
810
- const input = randomInput(params, bound);
859
+ const input = randomInput(params, rare ? 2 : bound);
811
860
  let next;
812
861
  try {
813
862
  if (!allowed(m, run, params, st, input))
@@ -1020,9 +1069,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1020
1069
  s += c * vals[i][j]; return s; };
1021
1070
  const keyNots = plain.filter(i => !atoms[i].param && !atoms[i].int && !atoms[i].term);
1022
1071
  // The guards: the choices first, then yes/nos, then small naturals, at most eight; each shape's largest value per
1023
- // guard in one pass over (at most 1,500 of) the rows. Building candidates takes at most a quarter of the time.
1072
+ // guard in one pass over (at most 3,000 of) the rows: with each state kept once a stride skips states, not copies, and a
1073
+ // guard's bound past a skipped one is no law (break_safe's i1 + 1 <= i0 → 27 <= i0). Building candidates takes at most
1074
+ // a quarter of the time.
1024
1075
  const guards = [...modes].sort((p, q) => Number(!!q.choice) - Number(!!p.choice) || Number(!!q.bool) - Number(!!p.bool)).slice(0, 8);
1025
- const strideS = Math.max(1, Math.ceil(NS / 1500)), strideK = Math.max(1, Math.ceil(NK / 1500));
1076
+ const strideS = Math.max(1, Math.ceil(NS / 3000)), strideK = Math.max(1, Math.ceil(NK / 3000));
1026
1077
  const buildUntil = opts.cubes ? 0 : Math.min(until, now() + (until - now()) / 4);
1027
1078
  for (const [n_, { coef, cells }] of shapes.entries()) {
1028
1079
  if (forms.length > maxCandidates || (n_ % 256 === 0 && (now() > buildUntil || stop())))
@@ -1076,16 +1127,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1076
1127
  // seldom meets a bound between two times: until[k] + E <= now, reached at the instant its lease ends).
1077
1128
  if (w < 0 || !Number.isFinite(written))
1078
1129
  continue;
1079
- const wr = { atom: w, value: 1, hi: Infinity }, near = (dv) => (dv < 0 ? [0] : [dv, ...bounds.filter(b => b > dv).slice(0, 1)]);
1130
+ // (only where it bounds lower than the guard's own form, which a shape of three has none of)
1131
+ const wr = { atom: w, value: 1, hi: Infinity }, near = (dv) => (dv < 0 ? [0] : [dv, ...bounds.filter(b => b > dv).slice(0, 1)]), alone = (v) => (coef.length > 2 ? Infinity : v);
1080
1132
  if (written < d)
1081
1133
  for (const dv of near(written))
1082
1134
  if (dv < d)
1083
1135
  forms.push({ coef, d: dv, cells, guard: wr, size: sizeOf(coef) + 55 });
1084
1136
  here.forEach((mode, g) => { for (const [value, dv] of mostW[g])
1085
- if (mode.values.includes(value) && dv < Math.min(written, most[g].get(value)))
1137
+ if (mode.values.includes(value) && dv < Math.min(written, alone(most[g].get(value))))
1086
1138
  for (const e of near(dv))
1087
1139
  forms.push({ coef, d: e, cells, guard: { atom: mode.atom, value }, also: [wr], size: sizeOf(coef) + 65 }); });
1088
- keyNots.forEach((s, g) => { if (Number.isFinite(awayW[g]) && awayW[g] < Math.min(written, away[g]))
1140
+ keyNots.forEach((s, g) => { if (Number.isFinite(awayW[g]) && awayW[g] < Math.min(written, alone(away[g])))
1089
1141
  for (const e of near(awayW[g]))
1090
1142
  forms.push({ coef, d: e, cells, guard: { keyNot: s }, also: [wr], size: sizeOf(coef) + 70 }); });
1091
1143
  }
@@ -1462,11 +1514,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1462
1514
  const ctis = [];
1463
1515
  // (a law about keys is evaluated at every tuple of the state's keys, as watch does: counted as that many evaluations)
1464
1516
  const lawful = (params, st) => {
1517
+ const k = keysOf(4, st).length, cost = given.reduce((s, l) => s + (l.forall ? k ** (1 + (l.keys?.length ?? 0)) : 0), 0);
1518
+ // (a state whose laws' tuples cost more than a million evaluations is no sample: one such check took sharded_kv's whole
1519
+ // budget, five keys at 40 values)
1520
+ if (cost > 1e6)
1521
+ return false;
1465
1522
  used.watched += given.length;
1466
- const k = keysOf(4, st).length;
1467
- for (const l of given)
1468
- if (l.forall)
1469
- used.evals += k ** (1 + (l.keys?.length ?? 0));
1523
+ used.evals += cost;
1470
1524
  try {
1471
1525
  return given.every(l => watch(m, run, l, params, 4).start(st));
1472
1526
  }
@@ -2614,7 +2668,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2614
2668
  }
2615
2669
  };
2616
2670
  const enumerated = () => {
2617
- const ks = sorts, comp = ks.composedMaps.length && pairing?.n ? [ks.find('hi'), ks.find('lo')] : undefined;
2671
+ const ks = keySorts(m, callerLaws, pairing, true), comp = ks.composedMaps.length && pairing?.n ? [ks.find('hi'), ks.find('lo')] : undefined;
2618
2672
  const multi = [...ks.arity].map(([mp, k]) => ({ mp, slots: Array.from({ length: k }, (_, i) => ks.find(`${mp}:${i}`)) }));
2619
2673
  const ss = [...new Set([...ks.plainRead.map(mp => ks.find(`M:${mp}`)), ...(comp ?? []), ...multi.flatMap(q => q.slots)])];
2620
2674
  // (a map's values of a key's sort, and the sorts an order compares: e < Ep[a] makes Ep's values epochs, ordered)
@@ -2653,7 +2707,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2653
2707
  // (a function of a key whose values are a composed map's rows: Pending[idn(x)·N + y])
2654
2708
  const fnHi = Object.keys(m.fns ?? {}).filter(f => comp && ss.includes(ks.find(`F:${f}`)) && vf(`V:${f}`) === vf(comp[0]));
2655
2709
  const placesOf = (s) => (comp ? comp.filter(c => c === s).length + fnHi.filter(f => ks.find(`F:${f}`) === s).length : 0);
2656
- const width = ss.map(s => Math.min(3, Math.max(ordered(s) ? 2 : 0, ks.plainMaps(s).length ? 1 : 0, placesOf(s) + (placesOf(s) >= 2 ? 1 : 0), ...multi.map(q => q.slots.filter(c => c === s).length), ...callerLaws.map(l => [l.forall, ...(l.keys ?? [])].filter(b => b && ks.sortOf(l, b) === s).length))));
2710
+ // (a two-part map whose row is a function's value: the function's argument and the column, places of their sorts)
2711
+ const fnRows = Object.keys(m.fns ?? {}).flatMap(f => multi.filter(q => q.slots.length === 2 && ss.includes(ks.find(`F:${f}`)) && vf(`V:${f}`) === vf(q.slots[0])).map(q => ({ f, q })));
2712
+ const rowPlaces = (s) => fnRows.filter(({ f }) => ks.find(`F:${f}`) === s).length + fnRows.filter(({ q }) => q.slots[1] === s).length;
2713
+ const width = ss.map(s => Math.min(3, Math.max(ordered(s) ? 2 : 0, ks.plainMaps(s).length ? 1 : 0, placesOf(s) + (placesOf(s) >= 2 ? 1 : 0), ...multi.map(q => { const c = q.slots.filter(c2 => c2 === s).length; return c + (c >= 2 ? 1 : 0); }), rowPlaces(s) + (rowPlaces(s) >= 2 ? 1 : 0), ...callerLaws.map(l => [l.forall, ...(l.keys ?? [])].filter(b => b && ks.sortOf(l, b) === s).length))));
2657
2714
  // (a key's own bounds and domain: a caller's law's guards on one key of the sort, k < 64, k < size)
2658
2715
  const bounds = new Map();
2659
2716
  for (const l of callerLaws) {
@@ -2766,7 +2823,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2766
2823
  // few others that keep its facts on the sort's keys (its values reversed, and each turned by one), each run as its
2767
2824
  // own machine; their states' rows read under their table. One table alone is a fact of it, not of the rule: ring's
2768
2825
  // ids, every node past another one's below it)
2769
- const tables = [{ m, run, js: m.history || m.counts ? undefined : loadJs(m), fns: {} }];
2826
+ const tables = [{ m, run, js: fastStep(m), fns: {} }];
2770
2827
  for (const [f, fn] of Object.entries(m.fns ?? {})) {
2771
2828
  const arg = ks.find(`F:${f}`);
2772
2829
  if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history || m.counts)
@@ -2786,13 +2843,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2786
2843
  return false;
2787
2844
  } }); });
2788
2845
  if (keeps && tables.length < 4)
2789
- tables.push({ m: m2, run: interpret(m2), js: loadJs(m2), fns: { [f]: fn2 } });
2846
+ tables.push({ m: m2, run: interpret(m2), js: fastStep(m2), fns: { [f]: fn2 } });
2790
2847
  }
2791
2848
  }
2792
2849
  const stepIn = (tb, params, st, input) => {
2793
2850
  try {
2794
2851
  if (tb.js)
2795
- return tb.js.step(params, tb.js.fork(st), input);
2852
+ return tb.js(params, st, input);
2796
2853
  return allowed(tb.m, tb.run, params, st, input) ? tb.run.step(params, st, input) : undefined;
2797
2854
  }
2798
2855
  catch {
@@ -2972,9 +3029,16 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2972
3029
  mapsAt.push(ks.composedMaps);
2973
3030
  covers.push(i === j ? [i] : [i, j]);
2974
3031
  } }));
3032
+ // (and a two-part map's row a function of a key, as a composed map's: Pending[idn(x)·N + y])
3033
+ for (const { f, q } of fnRows)
3034
+ keys.forEach((a, i) => keys.forEach((b, j) => { if (a === ks.find(`F:${f}`) && b === q.slots[1]) {
3035
+ places.push(ks.composeAll([get(f, x(vars[i])), x(vars[j])]));
3036
+ mapsAt.push([q.mp]);
3037
+ covers.push(i === j ? [i] : [i, j]);
3038
+ } }));
2975
3039
  const names = ['x', 'y', 'z', 'w', 'u'].slice(0, keys.length), fns = Object.keys(m.fns ?? {}).filter(f => ordered(`V:${f}`) && ss.includes(ks.find(`F:${f}`)));
2976
3040
  const extra = [...keys.flatMap((q, i) => (ordered(q) ? [{ name: names[i], term: x(vars[i]) }] : [])), ...fns.flatMap(f => keys.flatMap((q, i) => (q === ks.find(`F:${f}`) ? [{ name: `${f}(${names[i]})`, term: get(f, x(vars[i])) }] : [])))];
2977
- const frame = all(...keys.flatMap((s, i) => [...(comp && s === comp[1] && !bounds.has(s) ? [atMost(x(vars[i]), n(pairing.n - 1))] : []), ...[...new Set((bounds.get(s) ?? []).map(g => JSON.stringify(substC(g, { vars: { [KEY]: x(vars[i]) }, maps: {}, flags: {} }))))].map(t => JSON.parse(t)), ...keys.slice(0, i).flatMap((t, j) => (t === s ? [not(same(x(vars[j]), x(vars[i])))] : []))]));
3041
+ const frame = all(...keys.flatMap((s, i) => [...(((comp && s === comp[1]) || multi.some(q => q.slots.slice(1).includes(s))) && !bounds.has(s) ? [atMost(x(vars[i]), n(pairing.n - 1))] : []), ...[...new Set((bounds.get(s) ?? []).map(g => JSON.stringify(substC(g, { vars: { [KEY]: x(vars[i]) }, maps: {}, flags: {} }))))].map(t => JSON.parse(t)), ...keys.slice(0, i).flatMap((t, j) => (t === s ? [not(same(x(vars[j]), x(vars[i])))] : []))]));
2978
3042
  const vi = views.length;
2979
3043
  addView({ vars, names, places, covers, frame, need: keys.length, printable: false }, mapsAt, st => keys.map(s => ks.valuesAt(st, s)), Math.max(2, Math.floor(64 ** (1 / keys.length))), extra, true);
2980
3044
  // (the rows: every small state's, distinct, at most 20,000; the view's own rows stop at its first states, the shallow
@@ -3126,7 +3190,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3126
3190
  for (const f of live)
3127
3191
  byView.set(f.view, [...(byView.get(f.view) ?? []), f]);
3128
3192
  let read = 0, still = 0, lastKill = 0;
3129
- const r = instance(grow, share, searchSeeded(29 + k), most5, q => {
3193
+ const r = instance(grow, share, seeded(29 + k), most5, q => {
3130
3194
  if (read >= most5 || (read >= (k ? 0 : least5) && still >= quiet) || stop())
3131
3195
  return false;
3132
3196
  states++;
@@ -4135,7 +4199,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4135
4199
  return { ...first, proven: false, found: (cubesOut ?? []).filter(f => f.cube.length <= opts.cubes).map(f => ({ law: lawFor(f), text: textOf(f) })), stats: stats(0, 0, 0) };
4136
4200
  }
4137
4201
  for (;;) {
4138
- if (now() > jUntil || stop()) {
4202
+ // (`join` 0: no round, the engine's alone)
4203
+ if (now() > jUntil || opts.join === 0 || stop()) {
4139
4204
  why = 'time';
4140
4205
  break;
4141
4206
  }
@@ -4451,6 +4516,14 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4451
4516
  if (!last.goal)
4452
4517
  break;
4453
4518
  const name = goalName(last.goal), stuckOn = chosen.find(f => lawFor(f).name === name);
4519
+ // (the join's control states no state reached, one law for all, unproven with every law of the set assumed (their
4520
+ // instances shared among more laws: a model none of the join's proofs met): each its own law, as the join has them
4521
+ // once one is broken)
4522
+ if (stuckOn?.nevers && !last.run) {
4523
+ chosen = chosen.flatMap(f => (f === stuckOn ? f.nevers.map(c => ({ ...f, nevers: undefined, ...(c.length > 1 ? { never: c } : { unreachable: c[0] }) })) : [f]));
4524
+ forget();
4525
+ continue;
4526
+ }
4454
4527
  if (last.run) {
4455
4528
  // A real run breaks it: a candidate is false (dropped); a law of the caller's is false (the answer).
4456
4529
  if (!stuckOn)
@@ -35,8 +35,16 @@ public final class JavaReader implements Jvm.Env {
35
35
  public static void main(String[] argv) throws Exception {
36
36
  Map<?, ?> req = (Map<?, ?>) parse(argv[0]);
37
37
  JavaReader r = new JavaReader();
38
- System.out.println(json(r.read(req)));
38
+ String out = null;
39
+ try { out = json(r.read(req)); } catch (RuntimeException | Error e) {
40
+ if (Jvm.overflowed(e)) Jvm.refuse("the source nests too deeply to read");
41
+ // (javac's error recovery leaves trees the walk can't read: the errors it reported are the reason)
42
+ if (r.errs.isEmpty()) Jvm.failed("Java", e);
43
+ Jvm.refuse("the source doesn't compile: " + String.join(" | ", r.errs.subList(0, Math.min(3, r.errs.size()))));
44
+ }
45
+ System.out.println(out);
39
46
  }
47
+ final List<String> errs = new ArrayList<>();
40
48
 
41
49
  Map<String, Object> read(Map<?, ?> req) throws IOException {
42
50
  String root = (String) req.get("root"), file = (String) req.get("file"), cp = (String) req.get("classpath");
@@ -44,9 +52,9 @@ public final class JavaReader implements Jvm.Env {
44
52
  StandardJavaFileManager fm = jc.getStandardFileManager(null, null, StandardCharsets.UTF_8);
45
53
  List<String> opts = new ArrayList<>(List.of("-proc:none", "-Xlint:none", "-sourcepath", root));
46
54
  if (cp != null && !cp.isEmpty()) { opts.add("-cp"); opts.add(cp); }
47
- List<String> errs = new ArrayList<>();
48
55
  JavacTask task = (JavacTask) jc.getTask(new StringWriter(), fm, d -> { if (d.getKind() == Diagnostic.Kind.ERROR) errs.add(d.getMessage(null)); }, opts, null, fm.getJavaFileObjects(file));
49
56
  Iterable<? extends CompilationUnitTree> cus = task.parse();
57
+ if (!errs.isEmpty()) Jvm.refuse("the source doesn't parse: " + String.join(" | ", errs.subList(0, Math.min(3, errs.size()))));
50
58
  task.analyze();
51
59
  trees = Trees.instance(task); els = task.getElements(); types = task.getTypes(); sp = trees.getSourcePositions();
52
60
  CompilationUnitTree cu = cus.iterator().next();
@@ -48,6 +48,20 @@ public final class Jvm {
48
48
  return n.contains(".") || n.contains("e") || n.contains("E") ? (Object) Double.parseDouble(n) : (Object) Long.parseLong(n);
49
49
  }
50
50
  static String json(Object o) { StringBuilder b = new StringBuilder(); json(o, b); return b.toString(); }
51
+ // A source a reader can't read, said so on stderr (core/extract-read.ts's statedRefusal): a syntax error, or nesting
52
+ // past the reader's stack (javac's parser and the walk recurse on each level), found anywhere in a throw's causes.
53
+ static void refuse(String why) { System.err.println("gdp: refused: " + why.replace('\n', ' ')); System.exit(3); }
54
+ // A reader's own failure on a source it parsed (javac's internal assertions on a tree it recovered, a type the walk
55
+ // couldn't resolve): refused, the reason naming the failure and where, so it is never read as a missing tool.
56
+ static void failed(String lang, Throwable e) {
57
+ Throwable r = e; while (r.getCause() != null) r = r.getCause();
58
+ StackTraceElement at = r.getStackTrace().length > 0 ? r.getStackTrace()[0] : null;
59
+ // (the compiler's own failure, javac's or Kotlin's, on what it recovered from the source: the source is past it)
60
+ if (at != null && (at.getClassName().startsWith("com.sun.tools.javac") || at.getClassName().startsWith("org.jetbrains.kotlin") || at.getClassName().startsWith("com.intellij")))
61
+ refuse("the " + lang + " compiler failed on this source (" + r.getClass().getSimpleName() + ")");
62
+ refuse("the " + lang + " reader failed on this source (" + r.getClass().getSimpleName() + (at != null ? " at " + at.getClassName() + "." + at.getMethodName() + ":" + at.getLineNumber() : "") + ")");
63
+ }
64
+ static boolean overflowed(Throwable t) { for (; t != null; t = t.getCause()) if (t instanceof StackOverflowError) return true; return false; }
51
65
  static void json(Object o, StringBuilder b) {
52
66
  if (o == null) b.append("null");
53
67
  else if (o instanceof String s) {
@@ -106,7 +120,7 @@ public final class Jvm {
106
120
  static final Set<String> LOCKS = Set.of("java.util.concurrent.locks.ReentrantLock", "java.util.concurrent.locks.Lock", "java.util.concurrent.locks.ReentrantReadWriteLock", "java.util.concurrent.locks.ReadWriteLock", "java.util.concurrent.locks.StampedLock", "kotlinx.coroutines.sync.Mutex");
107
121
  static final List<String> UNITS = List.of("NANOSECONDS", "MICROSECONDS", "MILLISECONDS", "SECONDS", "MINUTES", "HOURS", "DAYS");
108
122
  static final long[] NANOS = {1L, 1_000L, 1_000_000L, 1_000_000_000L, 60_000_000_000L, 3_600_000_000_000L, 86_400_000_000_000L};
109
- static String prim(JT t) { return PRIM.contains(t.n) ? t.n : BOX.get(t.n); }
123
+ static String prim(JT t) { return t == null ? null : PRIM.contains(t.n) ? t.n : BOX.get(t.n); } // (null: a type the reader could not resolve)
110
124
  static boolean num(JT t) { String q = prim(t); return q != null && !q.equals("boolean") && !q.equals("void"); }
111
125
  static boolean integral(JT t) { String q = prim(t); return q != null && Set.of("int", "long", "short", "byte", "char").contains(q); }
112
126
  static boolean floating(JT t) { String q = prim(t); return "float".equals(q) || "double".equals(q); }
@@ -186,6 +200,8 @@ public final class Jvm {
186
200
 
187
201
  // An operand at a type (Java's binary promotion made explicit: the executor computes at its operands' type).
188
202
  static Map<String, Object> at(Map<String, Object> v, JT from, JT to) {
203
+ // (a boxed value unboxed: null is a NullPointerException)
204
+ if (from != null && to != null && BOX.containsKey(from.n) && PRIM.contains(to.n) && !to.n.equals("void")) v = x("expect", (String) v.get("p"), "x", v, "text", String.valueOf(v.getOrDefault("text", from.n)), "npe", true);
189
205
  Map<String, Object> it = ity(to);
190
206
  if (it == null || (from != null && Objects.equals(prim(from), prim(to)))) return v;
191
207
  if ("int".equals(v.get("e"))) { Map<String, Object> c = new LinkedHashMap<>(v); c.put("ity", it); return c; }