gdp-wired 0.31.1 → 0.32.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 (72) hide show
  1. package/README.md +82 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/cli.d.ts +66 -0
  5. package/dist/core/cli.js +582 -0
  6. package/dist/core/dsl.d.ts +4 -2
  7. package/dist/core/dsl.js +22 -12
  8. package/dist/core/effect.d.ts +6 -4
  9. package/dist/core/effect.js +48 -10
  10. package/dist/core/ex/harness.exs +177 -0
  11. package/dist/core/ex/json.exs +46 -0
  12. package/dist/core/ex/reader.exs +462 -0
  13. package/dist/core/exists.d.ts +3 -0
  14. package/dist/core/exists.js +3 -1
  15. package/dist/core/extract-c.d.ts +35 -0
  16. package/dist/core/extract-c.js +424 -0
  17. package/dist/core/extract-check.js +27 -6
  18. package/dist/core/extract-ex.d.ts +16 -0
  19. package/dist/core/extract-ex.js +33 -0
  20. package/dist/core/extract-go-check.d.ts +28 -0
  21. package/dist/core/extract-go-check.js +639 -0
  22. package/dist/core/extract-go.d.ts +231 -0
  23. package/dist/core/extract-go.js +1166 -0
  24. package/dist/core/extract-jvm.d.ts +23 -0
  25. package/dist/core/extract-jvm.js +220 -0
  26. package/dist/core/extract-print.js +17 -7
  27. package/dist/core/extract-py.d.ts +15 -0
  28. package/dist/core/extract-py.js +31 -0
  29. package/dist/core/extract-rb.d.ts +17 -0
  30. package/dist/core/extract-rb.js +31 -0
  31. package/dist/core/extract-read.d.ts +20 -0
  32. package/dist/core/extract-read.js +46 -6
  33. package/dist/core/extract-rs.d.ts +12 -0
  34. package/dist/core/extract-rs.js +306 -0
  35. package/dist/core/extract-shapes.d.ts +2 -0
  36. package/dist/core/extract-shapes.js +6 -5
  37. package/dist/core/extract-step.d.ts +806 -0
  38. package/dist/core/extract-step.js +4141 -0
  39. package/dist/core/extract-swift.d.ts +27 -0
  40. package/dist/core/extract-swift.js +484 -0
  41. package/dist/core/extract-xstate.d.ts +10 -3
  42. package/dist/core/extract-xstate.js +50 -4
  43. package/dist/core/extract.d.ts +22 -3
  44. package/dist/core/extract.js +107 -18
  45. package/dist/core/go/go.mod +3 -0
  46. package/dist/core/go/reader.go +901 -0
  47. package/dist/core/infer.js +1770 -52
  48. package/dist/core/jvm/Harness.java +361 -0
  49. package/dist/core/jvm/JavaReader.java +825 -0
  50. package/dist/core/jvm/Jvm.java +332 -0
  51. package/dist/core/jvm/KtReader.java +960 -0
  52. package/dist/core/jvm/Rt.java +10 -0
  53. package/dist/core/laws.d.ts +66 -0
  54. package/dist/core/laws.js +522 -0
  55. package/dist/core/py/harness.py +328 -0
  56. package/dist/core/py/reader.py +447 -0
  57. package/dist/core/rb/harness.rb +233 -0
  58. package/dist/core/rb/reader.rb +375 -0
  59. package/dist/core/rs/Cargo.lock +108 -0
  60. package/dist/core/rs/Cargo.toml +14 -0
  61. package/dist/core/rs/src/main.rs +681 -0
  62. package/dist/core/swift/Harness.swift +124 -0
  63. package/dist/core/swift/Main.swift +34 -0
  64. package/dist/core/swift/Package.swift +13 -0
  65. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  66. package/dist/kernel/epr.d.ts +35 -0
  67. package/dist/kernel/epr.js +1676 -0
  68. package/dist/kernel/prove.d.ts +44 -0
  69. package/dist/kernel/prove.js +657 -50
  70. package/dist/lean-kernel/emit.d.ts +1 -0
  71. package/dist/lean-kernel/emit.js +21 -4
  72. package/package.json +53 -2
@@ -77,7 +77,7 @@ export declare abstract class Kind<V> {
77
77
  abstract decode(name: string, vars: Record<string, number>): Raw;
78
78
  abstract empty(): Raw;
79
79
  sample(_rand: Rand, _bound: number): Raw;
80
- from(init: Raw | ((p: never) => unknown)): Init<V>;
80
+ from(init: Raw | ((p: any) => unknown)): Init<V>;
81
81
  }
82
82
  export type IntLike = Int | Term | number;
83
83
  export declare class Int {
@@ -546,6 +546,7 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
546
546
  get name(): string;
547
547
  get parts(): {
548
548
  params: [string, Kind<unknown>][];
549
+ inputs: [string, Kind<unknown>][];
549
550
  fns: [string, FnDef][];
550
551
  lists: [string, Kind<unknown>, Record<string, ListFold<unknown>>, Record<string, ListLemma>][];
551
552
  };
@@ -570,7 +571,7 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
570
571
  }, M & {
571
572
  [k in N]: ListRef;
572
573
  }, F, R, Su, Q>;
573
- items<T extends Record<string, Kind<unknown>>>(kinds: T): Rule<P, I, S & {
574
+ items<T extends Record<string, Kind<unknown>>>(kinds: T, lens?: Partial<Record<keyof T & string, number>>): Rule<P, I, S & {
574
575
  [k in keyof T & string as `${k}_len`]: Term;
575
576
  }, M & {
576
577
  [k in keyof T]: ItemsRef<T[k] extends Kind<infer V> ? V : never>;
@@ -866,6 +867,7 @@ export type ProveOptions = {
866
867
  cycles?: boolean;
867
868
  };
868
869
  from?: 'reachable' | 'any';
870
+ fast?: boolean;
869
871
  };
870
872
  export declare class Unproven extends Error {
871
873
  readonly verdict: Verdict;
package/dist/core/dsl.js CHANGED
@@ -19,7 +19,7 @@ import { argsKey, machineTerms, carriedView, compileFunction, divName, divisor,
19
19
  import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
20
20
  import { someHolds, substVars, substVarsE } from "./exists.js";
21
21
  import { check, checkRecur, foldObligations, loopObligations, substC, sumMachine } from "../kernel/kernel.js";
22
- import { certLoop, clock, counted, factsFor, fullRate, grow, proveLaws, proveLiveness, proveStepLaws, usualProof, withDeadline } from "../kernel/prove.js";
22
+ import { certLoop, clock, counted, factsFor, fullRate, grow, proveLaws, proveLiveness, proveSetFast, proveStepLaws, usualProof, withDeadline, withWall } from "../kernel/prove.js";
23
23
  import { certCyclic, certOn, crossCyclic, cyclicOn, foldNodes, proveCyclic, quietly, recurNodes, translatedProof, uncovered } from "./cyclic.js";
24
24
  import { discover } from "./discover.js";
25
25
  import { inferLaws } from "./infer.js";
@@ -195,6 +195,9 @@ export class Kind {
195
195
  // A runtime value of the kind (what encode takes), for comparing a rule with the code it describes (compare).
196
196
  sample(_rand, _bound) { throw new Error('this kind draws no runtime values'); }
197
197
  // A state variable of this kind starting at a runtime value, or at a value over the params: `.state({open: bool.from(true)})`.
198
+ // (a start over the params: the params' kinds aren't known here, so its argument is any, a printed rule's
199
+ // `int.from(({n}) => n.times(2))` typechecking as it runs)
200
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
198
201
  from(init) { return { kind: this, init }; }
199
202
  }
200
203
  const v = (name) => new Term({ op: 'var', name }, scope?.vars[name]);
@@ -1686,7 +1689,7 @@ export class Rule {
1686
1689
  // For core/discover.ts: the functions and carried lists the rule reads, and the same rule with functions made again
1687
1690
  // and lemmas added to its lists' folds (each proven here, as carriesList proves its own).
1688
1691
  get parts() {
1689
- return { params: this.spec.params, fns: this.spec.fns ?? [], lists: this.spec.lists2 ?? [] };
1692
+ return { params: this.spec.params, inputs: this.spec.inputs, fns: this.spec.fns ?? [], lists: this.spec.lists2 ?? [] };
1690
1693
  }
1691
1694
  withParts(fns, listLemmas = {}) {
1692
1695
  const lists = (this.spec.lists2 ?? []).map(([n, k, fs, ls]) => [n, k, fs, { ...ls, ...(listLemmas[n] ?? {}) }]);
@@ -1777,12 +1780,12 @@ export class Rule {
1777
1780
  lists(...names) {
1778
1781
  return this.with({ maps: [...this.spec.maps, ...names.map(n => [n, 0])], state: [...this.spec.state, ...names.map(n => [`${n}_len`, 0])], lists: [...(this.spec.lists ?? []), ...names] });
1779
1782
  }
1780
- // Lists whose items are values of a kind, each empty at the start: one list per variable of the kind, of one length
1781
- // <name>_len (ItemsRef).
1782
- items(kinds) {
1783
+ // Lists whose items are values of a kind, each empty at the start (or `lens[name]` items of 0: a C array's): one list
1784
+ // per variable of the kind, of one length <name>_len (ItemsRef).
1785
+ items(kinds, lens = {}) {
1783
1786
  const entries = Object.entries(kinds);
1784
1787
  return this.with({ maps: [...this.spec.maps, ...entries.flatMap(([n, k]) => k.vars(n).map(part => [part, 0]))],
1785
- state: [...this.spec.state, ...entries.map(([n]) => [`${n}_len`, 0])], items: [...(this.spec.items ?? []), ...entries] });
1788
+ state: [...this.spec.state, ...entries.map(([n]) => [`${n}_len`, lens[n] ?? 0])], items: [...(this.spec.items ?? []), ...entries] });
1786
1789
  }
1787
1790
  // A table of nodes, empty at the start (NodeTable): a tree in the state, made one node a step.
1788
1791
  nodes(name, of, children, folds = {}) {
@@ -2875,7 +2878,7 @@ export function proveRule(r, laws, opts = {}) {
2875
2878
  // (A step law broken so is refused, proveSteps below: it holds from every state the laws allow, reached or not.)
2876
2879
  if (refuted)
2877
2880
  return refuted.run ? refutedVerdict(refuted) : searched(r, laws, [], refutedVerdict(refuted), opts);
2878
- const out = proveLaws(r.machine, withKinds(r, laws));
2881
+ const out = (opts.fast ? proveSetFast : proveLaws)(r.machine, withKinds(r, laws));
2879
2882
  const v = { ...verdictOf(out), ...(out.witnesses && out.proven ? { witnesses: out.witnesses } : {}) };
2880
2883
  return searched(r, laws, [], v, opts);
2881
2884
  }
@@ -2931,6 +2934,11 @@ function searched(r, laws, stepLaws, v, opts) {
2931
2934
  return refutedVerdict(deeper);
2932
2935
  }
2933
2936
  const until = clock() + (typeof opts.search === 'object' && opts.search.ms !== undefined ? opts.search.ms : 10_000);
2937
+ // (the search's end on the wall too: kernel/prove.ts's withWall, past which every goal is unknown)
2938
+ return withWall(performance.now() + Math.max(0, until - clock()), () => searchedUntil(r, laws, stepLaws, v, opts, until));
2939
+ }
2940
+ function searchedUntil(r, laws, stepLaws, v, opts, until) {
2941
+ const any = opts.from === 'any';
2934
2942
  // Bounded runs (core/bmc.ts): a law broken k steps from the start, a model of the kernel's k-step goal, the run taken
2935
2943
  // by the interpreter. The shallow depths first, within a fortieth of the search's budget (at most 250 ms, counted in
2936
2944
  // the cost model's work: kernel/prove.ts's `counted` with `full`); the deeper ones only where the invariant search
@@ -2940,8 +2948,8 @@ function searched(r, laws, stepLaws, v, opts) {
2940
2948
  let reached = 0;
2941
2949
  const ghosted = stepGhosts(r.machine, stepLaws);
2942
2950
  // (with the step laws' ghosts, a wall stop too, at the budget: their goals cost the cost model more than its clock
2943
- // counts, a wide rule's past twice its wall time)
2944
- const bounded = (ms, from) => counted(fullRate, () => findBoundedRun(ghosted?.machine ?? r.machine, [...laws, ...(ghosted?.laws ?? [])], { ms, from, steps: true, ...(ghosted ? { wall: performance.now() + ms } : {}), progress: k => { reached = k; } }), true);
2951
+ // counts, a wide rule's past twice its wall time; and the last runs always, the search's tail on the wall too)
2952
+ const bounded = (ms, from, wall = !!ghosted) => counted(fullRate, () => findBoundedRun(ghosted?.machine ?? r.machine, [...laws, ...(ghosted?.laws ?? [])], { ms, from, steps: true, ...(wall ? { wall: performance.now() + ms } : {}), progress: k => { reached = k; } }), true);
2945
2953
  const refutedBy = (b) => refutedVerdict({ goal: `${b.law} @step (a run of ${b.depth} steps from the start)`, witness: b.witness, run: { params: b.params, trace: b.trace.map(shownRequest) } });
2946
2954
  const shallow = bounded(Math.min(250, total / 40), 1);
2947
2955
  if (shallow)
@@ -2988,13 +2996,15 @@ function searched(r, laws, stepLaws, v, opts) {
2988
2996
  const ms = until - clock() - tail;
2989
2997
  if (ms < 500)
2990
2998
  return v;
2991
- const inf = inferLaws(rule, [...fresh.map(f => f.law), ...laws], stepLaws, { ms, ...(rule === r && !fresh.length ? { first: v } : {}) });
2999
+ // (the search's own wall ends where the tail begins: the last bounded runs keep it)
3000
+ const tailAt = () => performance.now() + Math.max(0, until - tail - clock());
3001
+ const inf = withWall(tailAt(), () => inferLaws(rule, [...fresh.map(f => f.law), ...laws], stepLaws, { ms, ...(rule === r && !fresh.length ? { first: v } : {}) }));
2992
3002
  if (!(inf.proven && inf.checked)) {
2993
3003
  // The sum of each map the step writes (withMapSums): the search again over the rule with them, within half of what
2994
3004
  // is left (at most 20 s), where a law of cells against a total needs one (no ERC20 balance past the supply).
2995
3005
  const summed = rule.withMapSums();
2996
3006
  if (summed && until - clock() - tail > 1000) {
2997
- const inf2 = inferLaws(summed, [...fresh.map(f => f.law), ...laws], stepLaws, { ms: Math.min(20_000, (until - clock() - tail) / 2) });
3007
+ const inf2 = withWall(tailAt(), () => inferLaws(summed, [...fresh.map(f => f.law), ...laws], stepLaws, { ms: Math.min(20_000, (until - clock() - tail) / 2) }));
2998
3008
  if (inf2.proven && inf2.checked) {
2999
3009
  const { found, stats: _s2, ...verdict } = inf2;
3000
3010
  void _s2;
@@ -3002,7 +3012,7 @@ function searched(r, laws, stepLaws, v, opts) {
3002
3012
  }
3003
3013
  }
3004
3014
  // (a step law's ghost: at most 10 s of it, as its goals cost more than the laws')
3005
- const deep = bounded(Math.max(0, Math.min(until - clock(), ghosted && !laws.length ? 10_000 : Infinity)), Math.max(1, reached));
3015
+ const deep = bounded(Math.max(0, Math.min(until - clock(), ghosted && !laws.length ? 10_000 : Infinity)), Math.max(1, reached), true);
3006
3016
  if (deep)
3007
3017
  return refutedBy(deep);
3008
3018
  return { ...v, why: [v.why, `the search found nothing that proves it in ${Math.round(inf.stats.ms)} ms`].filter(Boolean).join('; ') };
@@ -1,9 +1,12 @@
1
1
  import type { Kind, Rule } from './dsl.js';
2
2
  import { type Rand } from './machine.js';
3
+ import { type Source } from './extract-read.js';
3
4
  import { type ExtractOptions, type Extraction } from './extract.js';
5
+ export { proveRule, proveSteps } from './dsl.js';
4
6
  type Mod = Record<string, any>;
5
- export type EffectOptions = ExtractOptions & {
6
- effect: Mod;
7
+ export type EffectOptions = Omit<ExtractOptions, 'entry'> & {
8
+ entry?: string;
9
+ effect?: Mod;
7
10
  modules?: Record<string, unknown>;
8
11
  };
9
12
  export type Runner = {
@@ -19,7 +22,7 @@ export type Runner = {
19
22
  set: (mod: string, ref: unknown, v: unknown) => unknown;
20
23
  };
21
24
  export declare function runner(E: Mod): Runner;
22
- export declare function extractEffect(code: string, opts: EffectOptions): Extraction;
25
+ export declare function extractEffect(at: Source, opts?: EffectOptions): Extraction;
23
26
  export type Service<S> = {
24
27
  effect: Mod;
25
28
  make: (params: Record<string, unknown>) => unknown;
@@ -44,4 +47,3 @@ export declare function fromSchema(schema: {
44
47
  ast: unknown;
45
48
  }>;
46
49
  }): Kind<any>;
47
- export {};
@@ -6,9 +6,11 @@
6
6
  // (true where calls don't interleave). What is read and refused, with the reasons, is in
7
7
  // skills/gdp-wired/references/writing-rules.md ("Effect services") and research/effect/README.md.
8
8
  //
9
- // const x = extractEffect(code, {file: 'limiter.ts', entry: 'make', effect: await import('effect')})
9
+ // const x = extractEffect('./limiter.ts') // a path or a URL; the service inferred; effect from the file's project
10
+ // proveRule(x.rule!, [x.rule!.law('never below zero', ({tokens}) => tokens.atLeast(0))])
10
11
  //
11
- // The check runs the code on the Effect given: the service made, and each request run, by Effect.runSyncExit with a
12
+ // {entry: 'make'} names the service, {effect} gives the module, {code, file} reads code in memory; the code-first form,
13
+ // extractEffect(code, {file, entry, effect}), stays. The check runs the code on that Effect: the service made, and each request run, by Effect.runSyncExit with a
12
14
  // Clock fixed at the request's time (4.x's TestClock.setTime yields to its scheduler, which runSync can't), every Ref
13
15
  // read after it. `conforms(rule, service)` runs a rule written by hand beside a running service; `fromSchema(schema)` is
14
16
  // a Schema's kind.
@@ -17,10 +19,11 @@ import * as dsl from "./dsl.js";
17
19
  import { interpret, seeded } from "./machine.js";
18
20
  import { allowed } from "./watch.js";
19
21
  import * as I from "./extract-ir.js";
20
- import { Refusal, bare as strip, impure, memberName, placed, refuse, shapeOf, text } from "./extract-read.js";
21
- import { readFactory } from "./extract-shapes.js";
22
- import { fromModel } from "./extract.js";
22
+ import { Refusal, bare as strip, beside, impure, memberName, placed, refuse, shapeOf, sourceOf, text } from "./extract-read.js";
23
+ import { readFactory, setupOf } from "./extract-shapes.js";
24
+ import { fromModel, namesOf } from "./extract.js";
23
25
  import { check } from "./extract-check.js";
26
+ export { proveRule, proveSteps } from "./dsl.js";
24
27
  const REFS = new Set(['Ref', 'SynchronizedRef', 'SubscriptionRef', 'TxRef']), MAKES = ['make', 'makeUnsafe', 'unsafeMake'];
25
28
  const STM = (api) => `${api}: STM (v3) is not read (a Ref, SynchronizedRef, or v4's TxRef is)`, MATCH = (x) => `${x}: a matcher (write the dispatch as a switch on _tag, or ifs)`;
26
29
  // Where on a path the step has changed a Ref so far (a condition in the heap, so merges and helpers carry it).
@@ -353,12 +356,19 @@ export function runner(E) {
353
356
  throw new Error(x.error); return x.value; };
354
357
  return { run, exit, get: (mod, ref) => run(E[mod].get(ref)), set: (mod, ref, v) => run(E[mod].set(ref, v)) };
355
358
  }
356
- export function extractEffect(code, opts) {
357
- const file = opts.file ?? 'input.ts', E = opts.effect;
358
- let m;
359
+ export function extractEffect(at, opts = {}) {
360
+ let m, code, file, E;
359
361
  try {
360
- m = readFactory(code, placed(file), opts, s => factoryOf(s, opts.entry));
362
+ ;
363
+ ({ code, file } = sourceOf(at, opts.file, 'input.ts'));
364
+ E = opts.effect ?? beside(file, 'effect');
365
+ if (!E)
366
+ throw new Refusal(file, 'no effect package resolves from the file (install it in its project, or give it: {effect: await import(\'effect\')})');
367
+ const entry = opts.entry ?? serviceOf(code, file, opts);
368
+ m = readFactory(code, placed(file), { ...opts, entry }, s => factoryOf(s, entry));
361
369
  m.file = file;
370
+ if (!opts.entry)
371
+ m.notes.unshift(`the entry inferred: ${entry}, the file's one make effect`);
362
372
  }
363
373
  catch (e) {
364
374
  if (e instanceof Refusal)
@@ -367,7 +377,35 @@ export function extractEffect(code, opts) {
367
377
  }
368
378
  // The modules the code imports, by specifier (effect, effect/<Module>), and the check's runner.
369
379
  const model = m, modules = { effect: E, ...Object.fromEntries(Object.entries(E).map(([k, x]) => [`effect/${k}`, x])), 'gdp-wired:effect': runner(E), ...opts.modules };
370
- return fromModel(model, file, opts.domains, [], (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, modules, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) }));
380
+ return { ...fromModel(model, file, opts.domains, [], (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, modules, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model) };
381
+ }
382
+ // The service a file has: of its declarations (the exported ones first), those whose make effect reads, one make effect
383
+ // however many names reach it (make, and a Layer of it).
384
+ function serviceOf(code, file, opts) {
385
+ const s = setupOf(code, placed(file), {}, opts.files), found = [];
386
+ const exported = (st) => !!(ts.canHaveModifiers(st) && ts.getModifiers(st)?.some(x => x.kind === ts.SyntaxKind.ExportKeyword));
387
+ for (const pass of [true, false]) {
388
+ for (const st of s.sf.statements.filter(x => exported(x) === pass)) {
389
+ const names = ts.isVariableStatement(st) ? st.declarationList.declarations.flatMap(d => (ts.isIdentifier(d.name) ? [d.name.text] : []))
390
+ : (ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st)) && st.name ? [st.name.text, ...(ts.isClassDeclaration(st) ? st.members.flatMap(x => (ts.isPropertyDeclaration(x) && ts.isIdentifier(x.name) ? [`${st.name.text}.${x.name.text}`] : [])) : [])] : [];
391
+ for (const n of names) {
392
+ try {
393
+ const f = factoryOf(s, n);
394
+ if (!found.some(([, g]) => g === f.fn))
395
+ found.push([n, f.fn]);
396
+ }
397
+ catch (e) {
398
+ if (!(e instanceof Refusal))
399
+ throw e;
400
+ }
401
+ }
402
+ }
403
+ if (found.length)
404
+ break;
405
+ }
406
+ if (found.length > 1)
407
+ throw new Refusal(file, `several services in the file (${found.map(([n]) => n).join(', ')}): name one (entry)`);
408
+ return found[0]?.[0] ?? refuse(s.sf.statements[0] ?? s.sf, 'no make effect in the file (an Effect.gen whose Refs its methods write, a function returning one, Effect.fn, or Layer.effect of one): name the entry');
371
409
  }
372
410
  export function conforms(r, svc, opts) {
373
411
  const R = runner(svc.effect), rand = seeded(opts.seed ?? 1), g = r.compiled(), interp = interpret(r.machine), isEffect = (x) => svc.effect.Effect.isEffect(x);
@@ -0,0 +1,177 @@
1
+ # The Elixir side of the extractor's check (core/extract-step.ts's checkStep): the module compiled from its file as it
2
+ # ships (its clock calls read the request's time: System.monotonic_time, system_time, os_time, DateTime.utc_now,
3
+ # :os.system_time, :erlang.system_time), its state made the way the module makes it (a GenServer started with its
4
+ # init's argument, an Agent with its start_link), set and read through :sys, each request a call of the module's own,
5
+ # one JSON line a request over two named pipes.
6
+ #
7
+ # elixir core/ex/harness.exs <in-fifo> <out-fifo>
8
+ Code.require_file("json.exs", __DIR__)
9
+ import Bitwise
10
+
11
+ defmodule GdpClock do
12
+ def now, do: :persistent_term.get(:gdp_now, 0)
13
+ def int(_ \\ nil), do: now()
14
+ def utc_now(_ \\ nil), do: DateTime.from_unix!(now())
15
+ end
16
+
17
+ # An answered call's value: the request's input for it, None (nil) where it says so; every process reads it.
18
+ defmodule GdpAnswer do
19
+ def a(key), do: (case Map.get(:persistent_term.get(:gdp_ans, %{}), key) do nil -> nil; %{"none" => true} -> nil; spec -> GdpHarness.arg(spec) end)
20
+ end
21
+
22
+ defmodule GdpHarness do
23
+ @clock %{{[:System], :monotonic_time} => :int, {[:System], :system_time} => :int, {[:System], :os_time} => :int, {[:DateTime], :utc_now} => :utc_now,
24
+ {:os, :system_time} => :int, {:erlang, :system_time} => :int, {:erlang, :monotonic_time} => :int}
25
+ def hello(req) do
26
+ ast = Code.string_to_quoted!(File.read!(req["path"]), file: req["path"])
27
+ # (an answered call of another module's function: the call made the stub's, by the module's and function's names)
28
+ ans = Map.new(for a <- req["answers"] || [], a["patch"]["mod"], do: {{a["patch"]["mod"], List.last(a["patch"]["path"])}, a["key"]})
29
+ ast = Macro.prewalk(ast, fn
30
+ {{:., m, [mod, f]}, m2, args} = x ->
31
+ key = case mod do {:__aliases__, _, parts} -> parts; a -> a end
32
+ name = case mod do {:__aliases__, _, parts} -> Enum.map_join(parts, ".", &to_string/1); a -> inspect(a) end
33
+ case {ans[{name, to_string(f)}], @clock[{key, f}]} do
34
+ {k, _} when is_binary(k) -> {{:., m, [{:__aliases__, m, [:GdpAnswer]}, :a]}, m2, [k]}
35
+ {_, nil} -> x
36
+ {_, g} -> {{:., m, [{:__aliases__, m, [:GdpClock]}, g]}, m2, args}
37
+ end
38
+ x -> x
39
+ end)
40
+ Code.compile_quoted(ast, req["path"])
41
+ Process.put(:s, req |> Map.put("mod", Module.concat([req["module"]])))
42
+ %{"ok" => true}
43
+ end
44
+ def s(k), do: Process.get(:s)[k]
45
+ def leaf_t(l), do: (case l["t"] do %{"k" => "opt", "of" => o} -> o; t -> t || %{} end)
46
+ def enc(v) when is_integer(v), do: Integer.to_string(v)
47
+ def enc(v) when is_float(v), do: (if v == Float.floor(v), do: Integer.to_string(trunc(v)), else: "f:#{v}")
48
+ def enc(%DateTime{} = d), do: Integer.to_string(DateTime.to_unix(d))
49
+ def enc(v), do: "?:#{inspect(v)}"
50
+ def tag(v) when is_boolean(v) or is_nil(v), do: v
51
+ def tag(v) when is_number(v), do: %{"n" => enc(v)}
52
+ def tag(v) when is_atom(v) or is_binary(v), do: %{"s" => to_string(v)}
53
+ def tag(v), do: %{"o" => inspect(v) |> String.slice(0, 40)}
54
+ def arg(%{"in" => v} = a) do
55
+ cond do
56
+ a["sym"] && is_binary(v) -> String.to_atom(v)
57
+ a["float"] -> v * 1.0
58
+ is_binary(v) and Regex.match?(~r/^-?\d+$/, v) -> String.to_integer(v)
59
+ true -> v
60
+ end
61
+ end
62
+ def arg(%{"none" => true}), do: nil
63
+ def state_of(st) do
64
+ for l <- s("leaves"), l["kind"] not in ["frame", "map"], into: %{} do
65
+ v = Map.get(st, String.to_atom(hd(l["path"])))
66
+ {l["name"], case l["kind"] do
67
+ "none" -> v == nil
68
+ "num" -> if v == nil, do: "0", else: enc(v)
69
+ k when k in ["str", "choice"] -> if v == nil, do: "", else: to_string(v)
70
+ "bool" -> v == true
71
+ end}
72
+ end
73
+ end
74
+ def put(st, state) do
75
+ st = Enum.reduce(s("leaves"), st, fn l, acc ->
76
+ f = String.to_atom(hd(l["path"])); v = state[l["name"]]; t = leaf_t(l)
77
+ case l["kind"] do
78
+ "num" -> n = String.to_integer(v); Map.put(acc, f, if(t["dt"], do: DateTime.from_unix!(n), else: if(t["k"] == "float", do: n * 1.0, else: n)))
79
+ k when k in ["str", "choice"] -> Map.put(acc, f, if(t["sym"], do: String.to_atom(v), else: v))
80
+ "bool" -> Map.put(acc, f, v)
81
+ _ -> acc
82
+ end
83
+ end)
84
+ Enum.reduce(s("leaves"), st, fn l, acc -> if l["kind"] == "none" and state[l["name"]] == true, do: Map.put(acc, String.to_atom(hd(l["path"])), nil), else: acc end)
85
+ end
86
+ # The object: the module's own process (a GenServer, an Agent) or the state itself (plain functions).
87
+ def make(a) do
88
+ Process.put(:last_make, a)
89
+ mod = s("mod"); args = Enum.map(a, fn [_, spec] -> arg(spec) end)
90
+ case s("shape") do
91
+ "genserver" ->
92
+ init = if s("init")["k"] == "tuple", do: List.to_tuple(Enum.map(s("init")["names"], fn n -> Enum.find_value(a, fn [k, spec] -> k == n && arg(spec) end) end)), else: hd(args ++ [nil])
93
+ {:ok, pid} = GenServer.start(mod, init); {:pid, pid}
94
+ "agent" ->
95
+ {:ok, pid} = if function_exported?(mod, :start_link, 1), do: (Process.flag(:trap_exit, true); mod.start_link([])), else: Agent.start(fn -> struct(mod) end)
96
+ {:pid, pid}
97
+ _ -> {:val, if(function_exported?(mod, :new, 0), do: mod.new(), else: struct(mod))}
98
+ end
99
+ end
100
+ def get({:pid, pid}), do: :sys.get_state(pid)
101
+ def get({:val, v}), do: v
102
+ def set({:pid, pid} = o, st), do: (:sys.replace_state(pid, fn x -> put(x, st) end); o)
103
+ def set({:val, v}, st), do: {:val, put(v, st)}
104
+ # A call; where it fails (a raise, a crash of the process), the object as it was before it (a fresh process given
105
+ # the state it had: the step refused leaves it so).
106
+ def call(o, m, a) do
107
+ before = get(o)
108
+ case call1(o, m, a) do
109
+ {_, {:err, _}} = r -> {elem(r, 0) |> revive(before), elem(r, 1)}
110
+ r -> r
111
+ end
112
+ end
113
+ defp revive({:pid, pid} = o, st) do
114
+ if Process.alive?(pid), do: (:sys.replace_state(pid, fn _ -> st end); o), else: (case make_fresh() do {:pid, p2} -> :sys.replace_state(p2, fn _ -> st end); {:pid, p2}; v -> v end)
115
+ end
116
+ defp revive(o, _), do: o
117
+ defp make_fresh, do: Process.get(:last_make) |> make()
118
+ def call1(o, m, a) do
119
+ msg = s("msgs")[m]; args = Enum.map(a, fn [_, spec] -> arg(spec) end); mod = s("mod")
120
+ try do
121
+ case {msg["kind"], o} do
122
+ {"handle_call", {:pid, pid}} -> {o, GenServer.call(pid, mk(msg, args))}
123
+ {"handle_cast", {:pid, pid}} -> GenServer.cast(pid, mk(msg, args)); :sys.get_state(pid); {o, nil}
124
+ {"agent", {:pid, pid}} -> {o, apply(mod, String.to_atom(msg["fun"]), [pid | args])}
125
+ {"pure", {:val, v}} ->
126
+ case apply(mod, String.to_atom(msg["fun"]), [v | args]) do
127
+ {:error, e} -> {o, {:err, inspect(e)}}
128
+ {:ok, %{} = n} -> {{:val, n}, nil}
129
+ %{} = n -> {{:val, n}, nil}
130
+ r -> {o, r}
131
+ end
132
+ end
133
+ rescue e -> {o, {:err, Exception.message(e) |> String.slice(0, 300)}}
134
+ catch :exit, r -> {o, {:err, "exit: #{inspect(r) |> String.slice(0, 300)}"}}
135
+ end
136
+ end
137
+ defp mk(%{"n" => 0, "atom" => true, "tag" => t}, _), do: String.to_atom(t)
138
+ defp mk(%{"tag" => t}, args), do: List.to_tuple([String.to_atom(t) | args])
139
+ end
140
+
141
+ [fin, fout] = System.argv()
142
+ # (the input first, then the output: the order the check opens them in)
143
+ # (a port reading the pipe line by line: Erlang's own file reads of a pipe wait for a full buffer)
144
+ port = Port.open({:spawn_executable, System.find_executable("cat")}, [:binary, {:line, 1 <<< 24}, {:args, [fin]}, :eof])
145
+ {:ok, out} = File.open(fout, [:write, :binary])
146
+ objs = :ets.new(:objs, [:set, :public])
147
+ lines = Stream.resource(fn -> "" end, fn acc ->
148
+ receive do
149
+ {^port, {:data, {:eol, l}}} -> {[acc <> l], ""}
150
+ {^port, {:data, {:noeol, l}}} -> {[], acc <> l}
151
+ {^port, :eof} -> {:halt, acc}
152
+ end
153
+ end, fn _ -> :ok end)
154
+ lines |> Enum.each(fn line ->
155
+ req = GdpJson.decode(line)
156
+ if req["now"], do: :persistent_term.put(:gdp_now, (if is_binary(req["now"]), do: String.to_integer(req["now"]), else: req["now"]))
157
+ res = try do
158
+ case req["op"] do
159
+ "hello" -> GdpHarness.hello(req)
160
+ "new" -> (try do o = GdpHarness.make(req["a"]); i = :ets.info(objs, :size) + 1; :ets.insert(objs, {i, o}); %{"id" => i} rescue e -> %{"err" => Exception.message(e)} catch :exit, r -> %{"err" => inspect(r)} end)
161
+ "at" ->
162
+ (try do o = GdpHarness.make(req["a"]) |> GdpHarness.set(req["state"]); i = :ets.info(objs, :size) + 1; :ets.insert(objs, {i, o}); %{"id" => i} rescue e -> %{"bad" => Exception.message(e)} catch :exit, r -> %{"bad" => inspect(r)} end)
163
+ "get" -> [{_, o}] = :ets.lookup(objs, req["id"]); %{"state" => GdpHarness.state_of(GdpHarness.get(o))}
164
+ "call" ->
165
+ :persistent_term.put(:gdp_ans, req["answers"] || %{})
166
+ [{_, o}] = :ets.lookup(objs, req["id"])
167
+ {o2, r} = GdpHarness.call(o, req["m"], req["a"])
168
+ :ets.insert(objs, {req["id"], o2})
169
+ case r do {:err, e} -> %{"out" => nil, "err" => e}; v -> %{"out" => GdpHarness.tag(v)} end
170
+ "coverage" -> %{"hit" => []}
171
+ op -> %{"error" => "no op #{op}"}
172
+ end
173
+ rescue e -> %{"error" => Exception.message(e) |> String.slice(0, 500)}
174
+ catch :exit, r -> %{"error" => "exit: #{inspect(r) |> String.slice(0, 500)}"}
175
+ end
176
+ IO.binwrite(out, GdpJson.encode(res) <> "\n")
177
+ end)
@@ -0,0 +1,46 @@
1
+ # A small JSON codec for the Elixir reader and harness (an Elixir older than 1.18 has none built in).
2
+ defmodule GdpJson do
3
+ def encode(nil), do: "null"
4
+ def encode(true), do: "true"
5
+ def encode(false), do: "false"
6
+ def encode(x) when is_integer(x), do: Integer.to_string(x)
7
+ def encode(x) when is_float(x), do: :erlang.float_to_binary(x, [:short])
8
+ def encode(x) when is_atom(x), do: encode(Atom.to_string(x))
9
+ def encode(x) when is_binary(x), do: "\"" <> esc(x) <> "\""
10
+ def encode(x) when is_list(x), do: "[" <> Enum.map_join(x, ",", &encode/1) <> "]"
11
+ def encode(%{} = m), do: "{" <> Enum.map_join(m, ",", fn {k, v} -> encode(to_string(k)) <> ":" <> encode(v) end) <> "}"
12
+ def encode(x) when is_tuple(x), do: encode(Tuple.to_list(x))
13
+ defp esc(s), do: s |> String.replace("\\", "\\\\") |> String.replace("\"", "\\\"") |> String.replace("\n", "\\n") |> String.replace("\t", "\\t") |> String.replace("\r", "\\r")
14
+
15
+ def decode(s), do: (s |> String.trim() |> value() |> elem(0))
16
+ defp ws(s), do: String.trim_leading(s)
17
+ defp value("{" <> r), do: obj(ws(r), %{})
18
+ defp value("[" <> r), do: arr(ws(r), [])
19
+ defp value("\"" <> r), do: str(r, "")
20
+ defp value("true" <> r), do: {true, r}
21
+ defp value("false" <> r), do: {false, r}
22
+ defp value("null" <> r), do: {nil, r}
23
+ defp value(r) do
24
+ [n] = Regex.run(~r/^-?\d+(\.\d+)?([eE][-+]?\d+)?/, r)
25
+ {if(String.contains?(n, [".", "e", "E"]), do: String.to_float(n), else: String.to_integer(n)), binary_part(r, byte_size(n), byte_size(r) - byte_size(n))}
26
+ end
27
+ defp obj("}" <> r, m), do: {m, r}
28
+ defp obj(r, m) do
29
+ {k, r} = value(ws(r)); ":" <> r = ws(r); {v, r} = value(ws(r))
30
+ case ws(r) do "," <> r -> obj(ws(r), Map.put(m, k, v)); "}" <> r -> {Map.put(m, k, v), r} end
31
+ end
32
+ defp arr("]" <> r, l), do: {Enum.reverse(l), r}
33
+ defp arr(r, l) do
34
+ {v, r} = value(ws(r))
35
+ case ws(r) do "," <> r -> arr(ws(r), [v | l]); "]" <> r -> {Enum.reverse([v | l]), r} end
36
+ end
37
+ defp str("\"" <> r, acc), do: {acc, r}
38
+ defp str("\\" <> <<c, r::binary>>, acc) do
39
+ case c do
40
+ ?n -> str(r, acc <> "\n"); ?t -> str(r, acc <> "\t"); ?r -> str(r, acc <> "\r")
41
+ ?u -> <<h::binary-size(4), r2::binary>> = r; str(r2, acc <> <<String.to_integer(h, 16)::utf8>>)
42
+ _ -> str(r, acc <> <<c>>)
43
+ end
44
+ end
45
+ defp str(<<c::utf8, r::binary>>, acc), do: str(r, acc <> <<c::utf8>>)
46
+ end