gdp-wired 0.31.1 → 0.33.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 (84) hide show
  1. package/README.md +95 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/check.js +20 -6
  5. package/dist/core/cli.d.ts +76 -0
  6. package/dist/core/cli.js +636 -0
  7. package/dist/core/dsl.d.ts +6 -4
  8. package/dist/core/dsl.js +30 -16
  9. package/dist/core/effect.d.ts +6 -4
  10. package/dist/core/effect.js +48 -10
  11. package/dist/core/ex/harness.exs +177 -0
  12. package/dist/core/ex/json.exs +46 -0
  13. package/dist/core/ex/reader.exs +462 -0
  14. package/dist/core/exists.d.ts +3 -0
  15. package/dist/core/exists.js +19 -5
  16. package/dist/core/extract-c.d.ts +35 -0
  17. package/dist/core/extract-c.js +424 -0
  18. package/dist/core/extract-check.js +27 -6
  19. package/dist/core/extract-ex.d.ts +16 -0
  20. package/dist/core/extract-ex.js +33 -0
  21. package/dist/core/extract-go-check.d.ts +28 -0
  22. package/dist/core/extract-go-check.js +639 -0
  23. package/dist/core/extract-go.d.ts +231 -0
  24. package/dist/core/extract-go.js +1166 -0
  25. package/dist/core/extract-jvm.d.ts +23 -0
  26. package/dist/core/extract-jvm.js +220 -0
  27. package/dist/core/extract-print.js +17 -7
  28. package/dist/core/extract-py.d.ts +15 -0
  29. package/dist/core/extract-py.js +31 -0
  30. package/dist/core/extract-rb.d.ts +17 -0
  31. package/dist/core/extract-rb.js +31 -0
  32. package/dist/core/extract-read.d.ts +20 -0
  33. package/dist/core/extract-read.js +46 -6
  34. package/dist/core/extract-rs.d.ts +12 -0
  35. package/dist/core/extract-rs.js +306 -0
  36. package/dist/core/extract-shapes.d.ts +2 -0
  37. package/dist/core/extract-shapes.js +6 -5
  38. package/dist/core/extract-step.d.ts +806 -0
  39. package/dist/core/extract-step.js +4141 -0
  40. package/dist/core/extract-swift.d.ts +27 -0
  41. package/dist/core/extract-swift.js +484 -0
  42. package/dist/core/extract-xstate.d.ts +10 -3
  43. package/dist/core/extract-xstate.js +50 -4
  44. package/dist/core/extract.d.ts +22 -3
  45. package/dist/core/extract.js +107 -18
  46. package/dist/core/go/go.mod +3 -0
  47. package/dist/core/go/reader.go +901 -0
  48. package/dist/core/infer.d.ts +4 -0
  49. package/dist/core/infer.js +1838 -69
  50. package/dist/core/jvm/Harness.java +361 -0
  51. package/dist/core/jvm/JavaReader.java +825 -0
  52. package/dist/core/jvm/Jvm.java +332 -0
  53. package/dist/core/jvm/KtReader.java +960 -0
  54. package/dist/core/jvm/Rt.java +10 -0
  55. package/dist/core/laws.d.ts +83 -0
  56. package/dist/core/laws.js +623 -0
  57. package/dist/core/machine.d.ts +2 -0
  58. package/dist/core/machine.js +87 -0
  59. package/dist/core/py/harness.py +328 -0
  60. package/dist/core/py/reader.py +447 -0
  61. package/dist/core/rb/harness.rb +233 -0
  62. package/dist/core/rb/reader.rb +375 -0
  63. package/dist/core/relational.d.ts +49 -0
  64. package/dist/core/relational.js +345 -0
  65. package/dist/core/rs/Cargo.lock +108 -0
  66. package/dist/core/rs/Cargo.toml +14 -0
  67. package/dist/core/rs/src/main.rs +681 -0
  68. package/dist/core/swift/Harness.swift +124 -0
  69. package/dist/core/swift/Main.swift +34 -0
  70. package/dist/core/swift/Package.swift +13 -0
  71. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  72. package/dist/interchange/check.d.ts +16 -0
  73. package/dist/interchange/check.js +111 -0
  74. package/dist/interchange/format.d.ts +150 -0
  75. package/dist/interchange/format.js +678 -0
  76. package/dist/kernel/epr.d.ts +40 -0
  77. package/dist/kernel/epr.js +1882 -0
  78. package/dist/kernel/kernel.d.ts +45 -1
  79. package/dist/kernel/kernel.js +138 -13
  80. package/dist/kernel/prove.d.ts +45 -0
  81. package/dist/kernel/prove.js +658 -51
  82. package/dist/lean-kernel/emit.d.ts +17 -2
  83. package/dist/lean-kernel/emit.js +87 -7
  84. package/package.json +57 -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 {
@@ -289,7 +289,7 @@ export declare class MapRef {
289
289
  readonly init: number;
290
290
  private readonly cells;
291
291
  constructor(name: string, init: number);
292
- at(key: TermLike): Term;
292
+ at(key0: TermLike | Str): Term;
293
293
  set(key: TermLike, value: TermLike): MapWrite;
294
294
  bump(key: TermLike, c?: Cond, by?: TermLike): MapWrite;
295
295
  each(f: (key: Term) => TermLike): MapWrite;
@@ -351,7 +351,7 @@ export declare class CellsRef<V> {
351
351
  readonly kind: Kind<V>;
352
352
  private readonly map;
353
353
  constructor(name: string, kind: Kind<V>, map: (part: string) => MapRef);
354
- at(key: TermLike): V;
354
+ at(key: TermLike | Str): V;
355
355
  set(key: TermLike, value: Writes<V>): PartsWrite;
356
356
  each(f: (key: Term) => Writes<V>): PartsWrite;
357
357
  sum(of: (value: V) => TermLike): Term;
@@ -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]);
@@ -897,7 +900,8 @@ export class MapRef {
897
900
  this.init = init;
898
901
  this.cells = scope?.maps[name];
899
902
  }
900
- at(key) { const k = valOf(key); return new Term({ op: 'get', map: this.name, key: termOf(key) }, this.cells && k !== undefined ? this.cells.cells.get(k) ?? this.cells.dflt : undefined); }
903
+ // (a string key is its interned id, as a map keyed by strings holds it)
904
+ at(key0) { const key = key0 instanceof Str ? key0.id : key0, k = valOf(key); return new Term({ op: 'get', map: this.name, key: termOf(key) }, this.cells && k !== undefined ? this.cells.cells.get(k) ?? this.cells.dflt : undefined); }
901
905
  set(key, value) { return { map: this.name, key: termOf(key), value: termOf(value), concrete: { key: valOf(key), value: valOf(value) } }; }
902
906
  // key's cell plus `by` where `c` holds (the counter every cap keeps).
903
907
  bump(key, c = yes, by = 1) { return this.set(key, when(c, this.at(key).plus(by), this.at(key))); }
@@ -1686,7 +1690,7 @@ export class Rule {
1686
1690
  // For core/discover.ts: the functions and carried lists the rule reads, and the same rule with functions made again
1687
1691
  // and lemmas added to its lists' folds (each proven here, as carriesList proves its own).
1688
1692
  get parts() {
1689
- return { params: this.spec.params, fns: this.spec.fns ?? [], lists: this.spec.lists2 ?? [] };
1693
+ return { params: this.spec.params, inputs: this.spec.inputs, fns: this.spec.fns ?? [], lists: this.spec.lists2 ?? [] };
1690
1694
  }
1691
1695
  withParts(fns, listLemmas = {}) {
1692
1696
  const lists = (this.spec.lists2 ?? []).map(([n, k, fs, ls]) => [n, k, fs, { ...ls, ...(listLemmas[n] ?? {}) }]);
@@ -1777,12 +1781,12 @@ export class Rule {
1777
1781
  lists(...names) {
1778
1782
  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
1783
  }
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) {
1784
+ // 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
1785
+ // per variable of the kind, of one length <name>_len (ItemsRef).
1786
+ items(kinds, lens = {}) {
1783
1787
  const entries = Object.entries(kinds);
1784
1788
  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] });
1789
+ state: [...this.spec.state, ...entries.map(([n]) => [`${n}_len`, lens[n] ?? 0])], items: [...(this.spec.items ?? []), ...entries] });
1786
1790
  }
1787
1791
  // A table of nodes, empty at the start (NodeTable): a tree in the state, made one node a step.
1788
1792
  nodes(name, of, children, folds = {}) {
@@ -2785,7 +2789,8 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2785
2789
  && facts.filter(readsParams).every(f => holds(f, params));
2786
2790
  const cap = watchWork.n + perTrial * budget.trials;
2787
2791
  try {
2788
- for (let trial = 0; trial < budget.trials && watchWork.n <= cap; trial++) {
2792
+ const late = () => budget.until !== undefined && performance.now() > budget.until;
2793
+ for (let trial = 0; trial < budget.trials && watchWork.n <= cap && !late(); trial++) {
2789
2794
  // (`mixed`: the trials in turn at bounds 1 to 4, every fourth near)
2790
2795
  const bound = budget.mixed ? 1 + trial % 4 : budget.bound, guided = guides, near = budget.mixed && trial % 4 ? undefined : budget.near;
2791
2796
  const params = r.randomParams(rand, bound);
@@ -2803,7 +2808,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2803
2808
  for (const { w, on } of watching)
2804
2809
  if (!('then' in w) && !on.start(st))
2805
2810
  return broken(w, '@start', st);
2806
- for (let d = 0, tries = 0; d < budget.depth && tries < 40 && watchWork.n <= cap; tries++) {
2811
+ for (let d = 0, tries = 0; d < budget.depth && tries < 40 && watchWork.n <= cap && !late(); tries++) {
2807
2812
  const input = r.randomInput(rand, bound, params);
2808
2813
  if (near)
2809
2814
  for (const x of m.inputs)
@@ -2875,7 +2880,7 @@ export function proveRule(r, laws, opts = {}) {
2875
2880
  // (A step law broken so is refused, proveSteps below: it holds from every state the laws allow, reached or not.)
2876
2881
  if (refuted)
2877
2882
  return refuted.run ? refutedVerdict(refuted) : searched(r, laws, [], refutedVerdict(refuted), opts);
2878
- const out = proveLaws(r.machine, withKinds(r, laws));
2883
+ const out = (opts.fast ? proveSetFast : proveLaws)(r.machine, withKinds(r, laws));
2879
2884
  const v = { ...verdictOf(out), ...(out.witnesses && out.proven ? { witnesses: out.witnesses } : {}) };
2880
2885
  return searched(r, laws, [], v, opts);
2881
2886
  }
@@ -2925,12 +2930,19 @@ function searched(r, laws, stepLaws, v, opts) {
2925
2930
  return v;
2926
2931
  // The deeper runs; then runs over small values (keys that meet, small params), whose requests meet their
2927
2932
  // assumption's equalities and clocks, or near the counterexample the verdict ends at.
2933
+ // (the three within the search's budget again, on the wall: past it they stop, and the search starts as it would)
2934
+ const ms = typeof opts.search === 'object' && opts.search.ms !== undefined ? opts.search.ms : 10_000, runsUntil = performance.now() + ms;
2928
2935
  for (const b of [deeperBudget, { ...deeperBudget, bound: 1, seed: 31, states: false }, { ...deeperBudget, trials: 1200, seed: 41, states: false, mixed: true, ...(v.witness ? { near: v.witness } : {}) }]) {
2929
- const deeper = refuteByRuns(r, laws, stepLaws, b);
2936
+ const deeper = refuteByRuns(r, laws, stepLaws, { ...b, until: runsUntil });
2930
2937
  if (deeper?.run)
2931
2938
  return refutedVerdict(deeper);
2932
2939
  }
2933
2940
  const until = clock() + (typeof opts.search === 'object' && opts.search.ms !== undefined ? opts.search.ms : 10_000);
2941
+ // (the search's end on the wall too: kernel/prove.ts's withWall, past which every goal is unknown)
2942
+ return withWall(performance.now() + Math.max(0, until - clock()), () => searchedUntil(r, laws, stepLaws, v, opts, until));
2943
+ }
2944
+ function searchedUntil(r, laws, stepLaws, v, opts, until) {
2945
+ const any = opts.from === 'any';
2934
2946
  // 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
2947
  // by the interpreter. The shallow depths first, within a fortieth of the search's budget (at most 250 ms, counted in
2936
2948
  // the cost model's work: kernel/prove.ts's `counted` with `full`); the deeper ones only where the invariant search
@@ -2940,8 +2952,8 @@ function searched(r, laws, stepLaws, v, opts) {
2940
2952
  let reached = 0;
2941
2953
  const ghosted = stepGhosts(r.machine, stepLaws);
2942
2954
  // (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);
2955
+ // counts, a wide rule's past twice its wall time; and the last runs always, the search's tail on the wall too)
2956
+ 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
2957
  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
2958
  const shallow = bounded(Math.min(250, total / 40), 1);
2947
2959
  if (shallow)
@@ -2988,13 +3000,15 @@ function searched(r, laws, stepLaws, v, opts) {
2988
3000
  const ms = until - clock() - tail;
2989
3001
  if (ms < 500)
2990
3002
  return v;
2991
- const inf = inferLaws(rule, [...fresh.map(f => f.law), ...laws], stepLaws, { ms, ...(rule === r && !fresh.length ? { first: v } : {}) });
3003
+ // (the search's own wall ends where the tail begins: the last bounded runs keep it)
3004
+ const tailAt = () => performance.now() + Math.max(0, until - tail - clock());
3005
+ const inf = withWall(tailAt(), () => inferLaws(rule, [...fresh.map(f => f.law), ...laws], stepLaws, { ms, ...(rule === r && !fresh.length ? { first: v } : {}) }));
2992
3006
  if (!(inf.proven && inf.checked)) {
2993
3007
  // The sum of each map the step writes (withMapSums): the search again over the rule with them, within half of what
2994
3008
  // is left (at most 20 s), where a law of cells against a total needs one (no ERC20 balance past the supply).
2995
3009
  const summed = rule.withMapSums();
2996
3010
  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) });
3011
+ const inf2 = withWall(tailAt(), () => inferLaws(summed, [...fresh.map(f => f.law), ...laws], stepLaws, { ms: Math.min(20_000, (until - clock() - tail) / 2) }));
2998
3012
  if (inf2.proven && inf2.checked) {
2999
3013
  const { found, stats: _s2, ...verdict } = inf2;
3000
3014
  void _s2;
@@ -3002,7 +3016,7 @@ function searched(r, laws, stepLaws, v, opts) {
3002
3016
  }
3003
3017
  }
3004
3018
  // (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));
3019
+ const deep = bounded(Math.max(0, Math.min(until - clock(), ghosted && !laws.length ? 10_000 : Infinity)), Math.max(1, reached), true);
3006
3020
  if (deep)
3007
3021
  return refutedBy(deep);
3008
3022
  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