gdp-wired 0.45.0 → 0.46.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 (120) hide show
  1. package/README.md +58 -7
  2. package/dist/core/bitsets.d.ts +2 -0
  3. package/dist/core/bitsets.js +23 -0
  4. package/dist/core/bmc.js +6 -2
  5. package/dist/core/c/reader.d.ts +9 -1
  6. package/dist/core/c/reader.js +423 -31
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/cli.d.ts +3 -0
  10. package/dist/core/cli.js +204 -38
  11. package/dist/core/compose.js +3 -1
  12. package/dist/core/counts.d.ts +4 -1
  13. package/dist/core/counts.js +314 -85
  14. package/dist/core/cycles.js +8 -1
  15. package/dist/core/cyclic.d.ts +1 -0
  16. package/dist/core/cyclic.js +13 -7
  17. package/dist/core/data-synth.d.ts +3 -0
  18. package/dist/core/data-synth.js +252 -0
  19. package/dist/core/data.d.ts +2 -1
  20. package/dist/core/data.js +223 -24
  21. package/dist/core/discover.js +3 -1
  22. package/dist/core/draft.d.ts +19 -0
  23. package/dist/core/draft.js +53 -0
  24. package/dist/core/dsl.d.ts +37 -3
  25. package/dist/core/dsl.js +167 -26
  26. package/dist/core/effect.d.ts +1 -4
  27. package/dist/core/effect.js +1 -15
  28. package/dist/core/exists.d.ts +1 -0
  29. package/dist/core/exists.js +191 -16
  30. package/dist/core/extract-c.d.ts +2 -0
  31. package/dist/core/extract-c.js +169 -22
  32. package/dist/core/extract-check.d.ts +1 -0
  33. package/dist/core/extract-check.js +66 -0
  34. package/dist/core/extract-go-check.d.ts +1 -1
  35. package/dist/core/extract-go-check.js +2 -1
  36. package/dist/core/extract-go.d.ts +1 -0
  37. package/dist/core/extract-go.js +38 -4
  38. package/dist/core/extract-ir.d.ts +1 -0
  39. package/dist/core/extract-ir.js +15 -0
  40. package/dist/core/extract-jvm.d.ts +1 -1
  41. package/dist/core/extract-jvm.js +2 -0
  42. package/dist/core/extract-orm.d.ts +12 -0
  43. package/dist/core/extract-orm.js +244 -0
  44. package/dist/core/extract-print.js +20 -1
  45. package/dist/core/extract-py.d.ts +1 -0
  46. package/dist/core/extract-py.js +1 -1
  47. package/dist/core/extract-read.d.ts +17 -0
  48. package/dist/core/extract-read.js +5 -5
  49. package/dist/core/extract-rs.js +5 -1
  50. package/dist/core/extract-shapes.js +2 -0
  51. package/dist/core/extract-sol.d.ts +10 -1
  52. package/dist/core/extract-sol.js +70 -22
  53. package/dist/core/extract-step.d.ts +151 -1
  54. package/dist/core/extract-step.js +1232 -60
  55. package/dist/core/extract-swift.js +6 -2
  56. package/dist/core/extract.d.ts +8 -0
  57. package/dist/core/extract.js +61 -5
  58. package/dist/core/fiber-run.d.ts +5 -0
  59. package/dist/core/fiber-run.js +18 -0
  60. package/dist/core/infer.d.ts +4 -1
  61. package/dist/core/infer.js +918 -217
  62. package/dist/core/jvm/JavaReader.java +23 -6
  63. package/dist/core/jvm/Jvm.java +3 -0
  64. package/dist/core/jvm/KtReader.java +6 -5
  65. package/dist/core/laws.d.ts +10 -3
  66. package/dist/core/laws.js +193 -14
  67. package/dist/core/machine.d.ts +15 -1
  68. package/dist/core/machine.js +187 -15
  69. package/dist/core/nonterm.js +14 -1
  70. package/dist/core/orm/harness.js +61 -0
  71. package/dist/core/orm-fixtures/schema.prisma +5 -0
  72. package/dist/core/py/harness.py +183 -10
  73. package/dist/core/py/reader.py +234 -40
  74. package/dist/core/reader-fixtures/README.md +28 -0
  75. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  76. package/dist/core/reader-fixtures/go-685506.go +14 -0
  77. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  78. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  79. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  80. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  81. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  82. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  83. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  84. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  85. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  86. package/dist/core/relation.d.ts +1 -1
  87. package/dist/core/relation.js +29 -2
  88. package/dist/core/relational.js +4 -2
  89. package/dist/core/rs/src/main.rs +8 -2
  90. package/dist/core/sample-cache.d.ts +8 -0
  91. package/dist/core/sample-cache.js +46 -0
  92. package/dist/core/security.d.ts +38 -0
  93. package/dist/core/security.js +88 -0
  94. package/dist/core/sol/harness.py +57 -4
  95. package/dist/core/sol-concrete.d.ts +23 -0
  96. package/dist/core/sol-concrete.js +195 -0
  97. package/dist/core/solver.js +3 -1
  98. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  99. package/dist/core/system.js +1 -1
  100. package/dist/core/transfer.js +22 -9
  101. package/dist/core/translate.js +39 -10
  102. package/dist/core/watch.js +50 -5
  103. package/dist/interchange/format.js +11 -1
  104. package/dist/kernel/cdcl.d.ts +5 -0
  105. package/dist/kernel/cdcl.js +56 -9
  106. package/dist/kernel/epr.js +108 -26
  107. package/dist/kernel/kernel.d.ts +29 -1
  108. package/dist/kernel/kernel.js +325 -62
  109. package/dist/kernel/model-sequence.d.ts +3 -0
  110. package/dist/kernel/model-sequence.js +34 -0
  111. package/dist/kernel/prove.d.ts +10 -3
  112. package/dist/kernel/prove.js +332 -71
  113. package/dist/kernel/reader.d.ts +3 -0
  114. package/dist/kernel/reader.js +101 -14
  115. package/dist/kernel/share.d.ts +1 -0
  116. package/dist/kernel/share.js +27 -0
  117. package/dist/lean-kernel/emit.js +30 -37
  118. package/dist/lean-kernel/lean-terms.js +5 -0
  119. package/dist/lean-kernel/library.js +10 -10
  120. package/package.json +6 -1
@@ -1,3 +1,18 @@
1
+ // A loop's turn as its relation: the linear paths of one turn (kernel.ts's Loop), for a search that reads the relation
2
+ // rather than runs (core/cycles.ts's ranks found from the relation's counterexamples). Untrusted: what is found here is
3
+ // a candidate, and the kernel proves whatever is kept from it.
4
+ //
5
+ // A path is a conjunction of linear rows over the state, the params and the turn's inputs (each a natural), with the
6
+ // state after the turn linear in them: `while`, `assume` and the laws are put in disjunctive form, each `if` of the body
7
+ // decided by the values the path pins (pc = 3, t = 1: an equation of one variable) or split, each truncated difference
8
+ // a ∸ b split on a ≥ b (a − b, or 0 below it), min and max alike. A product of two variables stands for a natural of
9
+ // its own (the path is then larger than the turn: a search must check what it finds against the turn itself).
10
+ //
11
+ // Integers: two naturals that every row and every value reads only as their difference (u − w, as an integer slot is
12
+ // written: kernel.ts's pairs, the DSL's x and x$neg, compare/term's s and s$n), and whose values after the turn are a
13
+ // difference split both ways (u := P ∸ N, w := N ∸ P) or linear, are one integer, u − w: the path then needs no split
14
+ // for them (u − w becomes P − N exactly), and a rank over them is over the integer. Each is named by its first part.
15
+ import { cpair, cunpair } from "./machine.js";
1
16
  import { clock } from "../kernel/prove.js";
2
17
  import { canon, konst, plus, solve, subst, times, vars, work } from "./solver.js";
3
18
  import { bgcd } from "./q.js";
@@ -45,6 +60,8 @@ function alts(e, p, n) {
45
60
  }));
46
61
  case 'if': return chain(e, p, n, alts);
47
62
  case 'get': throw new Refused('a map');
63
+ case 'tup':
64
+ case 'proj': throw new Refused('a tuple key');
48
65
  }
49
66
  }
50
67
  // A row lin <= 0 added (none where the pins decide it: kept or dropped); an equation of one variable pins it.
@@ -152,6 +169,14 @@ function valueAt(e, pins) {
152
169
  return undefined;
153
170
  return e.op === 'add' ? a + b : e.op === 'sub' ? Math.max(0, a - b) : e.op === 'min' ? Math.min(a, b) : e.op === 'max' ? Math.max(a, b) : a * b;
154
171
  }
172
+ case 'tup': {
173
+ const a = valueAt(e.a, pins), b = a === undefined ? undefined : valueAt(e.b, pins);
174
+ return a === undefined || b === undefined ? undefined : cpair(a, b);
175
+ }
176
+ case 'proj': {
177
+ const a = valueAt(e.a, pins);
178
+ return a === undefined ? undefined : cunpair(a)[e.k];
179
+ }
155
180
  case 'get': return undefined;
156
181
  }
157
182
  }
@@ -384,8 +409,10 @@ const renameE = (e, names, f) => {
384
409
  case 'sub':
385
410
  case 'min':
386
411
  case 'max':
387
- case 'prod': return { ...e, a: renameE(e.a, names, f), b: renameE(e.b, names, f) };
388
- case 'mul': return { ...e, a: renameE(e.a, names, f) };
412
+ case 'prod':
413
+ case 'tup': return { ...e, a: renameE(e.a, names, f), b: renameE(e.b, names, f) };
414
+ case 'mul':
415
+ case 'proj': return { ...e, a: renameE(e.a, names, f) };
389
416
  case 'if': return { op: 'if', c: renameC(e.c, names, f), then: renameE(e.then, names, f), else: renameE(e.else, names, f) };
390
417
  case 'get': return { ...e, key: renameE(e.key, names, f) };
391
418
  }
@@ -261,14 +261,16 @@ export function lift(l, r, prefix, shared) {
261
261
  switch (x.op) {
262
262
  case 'var': return { op: 'var', name: n(x.name) };
263
263
  case 'const': return x;
264
- case 'mul': return { ...x, a: e(x.a) };
264
+ case 'mul':
265
+ case 'proj': return { ...x, a: e(x.a) };
265
266
  case 'if': return { op: 'if', c: c(x.c), then: e(x.then), else: e(x.else) };
266
267
  case 'get': return { op: 'get', map: n(x.map), key: e(x.key) };
267
268
  case 'add':
268
269
  case 'sub':
269
270
  case 'min':
270
271
  case 'max':
271
- case 'prod': return { ...x, a: e(x.a), b: e(x.b) };
272
+ case 'prod':
273
+ case 'tup': return { ...x, a: e(x.a), b: e(x.b) };
272
274
  }
273
275
  };
274
276
  const c = (x) => {
@@ -45,6 +45,12 @@ fn text(t: &impl ToTokens) -> String {
45
45
  }
46
46
  fn no(p: &str, why: String) -> Value { json!({"e": "no", "p": p, "why": why}) }
47
47
  fn sno(p: &str, why: String) -> Value { json!({"s": "no", "p": p, "why": why}) }
48
+ // Lifetimes constrain borrowing but do not select a runtime value type. Preserve
49
+ // refusals for type/const parameters; the existing type and ownership checks still
50
+ // decide whether a lifetime-bearing field, argument or operation can be read.
51
+ fn has_type_or_const_params(g: &syn::Generics) -> bool {
52
+ g.params.iter().any(|p| !matches!(p, syn::GenericParam::Lifetime(_)))
53
+ }
48
54
  fn last_ident(p: &syn::Path) -> String { p.segments.last().map(|s| s.ident.to_string()).unwrap_or_default() }
49
55
  fn path_str(p: &syn::Path) -> String { p.segments.iter().map(|s| s.ident.to_string()).collect::<Vec<_>>().join("::") }
50
56
  fn is_place(v: &Value) -> bool { matches!(v["e"].as_str(), Some("var") | Some("get") | Some("idx")) }
@@ -173,7 +179,7 @@ impl Reader {
173
179
  let mut fields = vec![];
174
180
  if let Fields::Named(f) = &s.fields { for fd in &f.named { fields.push(json!({"name": fd.ident.as_ref().unwrap().to_string(), "t": self.ty(&fd.ty), "rs": text(&fd.ty)})) } }
175
181
  let derives: Vec<String> = s.attrs.iter().filter(|a| a.path().is_ident("derive")).flat_map(|a| text(&a.meta).replace("derive (", "").replace(')', "").split(',').map(|x| x.trim().to_string()).collect::<Vec<_>>()).collect();
176
- let generic = !s.generics.params.is_empty();
182
+ let generic = has_type_or_const_params(&s.generics);
177
183
  let mut kinds = vec![json!("value")];
178
184
  if derives.iter().any(|d| d == "Default") { kinds.push(json!("default")) }
179
185
  if generic { kinds.push(json!(format!("generic:{}", text(&s.generics)))) }
@@ -212,7 +218,7 @@ impl Reader {
212
218
  let (mut body, tail) = self.block(block);
213
219
  if !tail.is_null() && tail["e"] != "none" { body.push(json!({"s": "ret", "p": self.at(block.span()), "x": tail})) }
214
220
  let ret = match &sig.output { ReturnType::Default => json!({"k": "none"}), ReturnType::Type(_, t) => self.ty(t) };
215
- let generic = !sig.generics.params.is_empty();
221
+ let generic = has_type_or_const_params(&sig.generics);
216
222
  let decs: Vec<Value> = attrs.iter().filter(|a| !a.path().is_ident("doc") && !a.path().is_ident("inline") && !a.path().is_ident("must_use") && !a.path().is_ident("allow")).map(|a| json!({"name": format!("attr:{}", text(a.path())), "text": text(&a.meta), "p": self.at(a.span())})).collect();
217
223
  let out = json!({"id": fid, "name": sig.ident.to_string(), "cls": cls, "p": self.at(sig.ident.span()), "span": [file, sig.span().start().line, block.span().end().line],
218
224
  "params": params, "ret": ret, "body": body, "async": sig.asyncness.is_some(), "static": is_static, "recv": recv, "decorators": decs, "generic": generic});
@@ -0,0 +1,8 @@
1
+ import type { State } from './machine.js';
2
+ /** The sampling key, byte-for-byte like the nested-array JSON, without allocating an array for every cell. */
3
+ export declare function sampleStateText(params: Record<string, number>, st: State, defaults: Record<string, number>): string;
4
+ /** A sample table for pure predicates: equal keys share evaluations, never rows or batches. */
5
+ export declare function samplePredicates<T, R>(groups: readonly (readonly T[])[], key: (t: T) => string, test: (t: T, row: R) => boolean): {
6
+ groups: number[][];
7
+ on(rows: readonly R[]): (id: number, row: number) => boolean;
8
+ };
@@ -0,0 +1,46 @@
1
+ /** The sampling key, byte-for-byte like the nested-array JSON, without allocating an array for every cell. */
2
+ export function sampleStateText(params, st, defaults) {
3
+ const number = (n) => Number.isFinite(n) ? String(n) : 'null';
4
+ let maps = '', between = '';
5
+ for (const mp of Object.keys(st.maps)) {
6
+ const cells = st.maps[mp], d = st.defaults?.[mp] ?? defaults[mp] ?? 0, keys = [];
7
+ cells.forEach((v, k) => { if (v !== d)
8
+ keys.push(k); });
9
+ keys.sort((a, b) => a - b);
10
+ let text = '', comma = '';
11
+ for (const k of keys) {
12
+ text += `${comma}[${number(k)},${number(cells.get(k))}]`;
13
+ comma = ',';
14
+ }
15
+ maps += `${between}[${text}]`;
16
+ between = ',';
17
+ }
18
+ return `[${JSON.stringify(params)},${JSON.stringify(st.scalars)},[${maps}],${JSON.stringify(st.defaults ?? null)}]`;
19
+ }
20
+ /** A sample table for pure predicates: equal keys share evaluations, never rows or batches. */
21
+ export function samplePredicates(groups, key, test) {
22
+ const ids = new Map(), predicates = [];
23
+ const indexed = groups.map(group => group.map(t => {
24
+ const k = key(t), was = ids.get(k);
25
+ if (was !== undefined)
26
+ return was;
27
+ const id = predicates.length;
28
+ ids.set(k, id);
29
+ predicates.push(t);
30
+ return id;
31
+ }));
32
+ return {
33
+ groups: indexed,
34
+ on(rows) {
35
+ const memo = predicates.map(() => new Uint8Array(rows.length));
36
+ return (id, row) => {
37
+ const column = memo[id], was = column[row];
38
+ if (was)
39
+ return was === 2;
40
+ const yes = test(predicates[id], rows[row]);
41
+ column[row] = yes ? 2 : 1;
42
+ return yes;
43
+ };
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,38 @@
1
+ import type { Extraction } from './extract.js';
2
+ import type { LawText } from './laws.js';
3
+ export type SecurityKind = 'authorization' | 'isolation' | 'workflow' | 'quota' | 'ledger';
4
+ export type SecuritySpec = {
5
+ name: string;
6
+ method?: string;
7
+ } & ({
8
+ kind: 'authorization';
9
+ effect: string;
10
+ requires: string;
11
+ } | {
12
+ kind: 'workflow';
13
+ effect: string;
14
+ prerequisite: string;
15
+ } | {
16
+ kind: 'quota';
17
+ used: string;
18
+ limit: string;
19
+ } | {
20
+ kind: 'ledger';
21
+ balance: string;
22
+ } | {
23
+ kind: 'isolation';
24
+ map: string;
25
+ identity: string;
26
+ fields: string[];
27
+ key?: string;
28
+ } | {
29
+ kind: 'isolation';
30
+ identity: string;
31
+ seeing: string;
32
+ });
33
+ export type SecurityCandidate = LawText & {
34
+ securityKind: SecurityKind;
35
+ review: 'required';
36
+ };
37
+ export declare function securityLaws(spec: SecuritySpec): SecurityCandidate[];
38
+ export declare function securityTemplates(x: Extraction, max?: number): SecurityCandidate[];
@@ -0,0 +1,88 @@
1
+ // Isolation covers BOTH domains. Quantifying only post-state keys misses deletions; only pre-state
2
+ // keys misses insertions. Presence is checked too, including deleting a foreign zero-valued row.
3
+ export function securityLaws(spec) {
4
+ const make = (expr, suffix = '') => ({ name: spec.name + suffix, expr,
5
+ ...(spec.method ? { method: spec.method } : {}), securityKind: spec.kind, review: 'required' });
6
+ switch (spec.kind) {
7
+ case 'authorization': return [make(`(${spec.effect}) implies (${spec.requires})`)];
8
+ case 'workflow': return [make(`(${spec.effect}) implies old(${spec.prerequisite})`)];
9
+ case 'quota': return [make(`(${spec.used}) <= (${spec.limit})`)];
10
+ case 'ledger': return [make(`(${spec.balance}) >= 0`)];
11
+ case 'isolation': {
12
+ if ('seeing' in spec)
13
+ return [make(`isolated by ${spec.identity} seeing ${spec.seeing}`)];
14
+ const k = spec.key ?? 'securityKey', m = spec.map;
15
+ if (!/^[A-Za-z_]\w*$/.test(k) || [spec.identity, m, ...spec.fields].some(s => (s.match(/[A-Za-z_$][\w$]*/g) ?? []).some(n => n === k)))
16
+ throw new Error('isolation key must be a fresh identifier, not a name in the policy');
17
+ const same = [`${k} in ${m}`, `${k} in old(${m})`, ...spec.fields.map(f => {
18
+ const cell = `${m}[${k}]${f ? `.${f}` : ''}`;
19
+ return `${cell} == old(${cell})`;
20
+ })].map(s => `(${s})`).join(' and ');
21
+ const body = `${k} != (${spec.identity}) implies (${same})`;
22
+ return [make(`forall ${k} in ${m}: ${body}`, ' (new rows)'), make(`forall ${k} in old(${m}): ${body}`, ' (old rows)')];
23
+ }
24
+ }
25
+ }
26
+ // Bounded, deterministic proposals using only extracted structure and names. Bool inputs and each
27
+ // role-choice value are ALTERNATIVE requirements, not inferred policy. No candidate is assumed while
28
+ // checking another. A caller must select the intended law and bind identity to authentication.
29
+ export function securityTemplates(x, max = 48) {
30
+ if (!x.ok || !x.model || !x.rule)
31
+ return [];
32
+ const m = x.model, names = x.names ?? [], out = [];
33
+ const name = (rule, role) => names.find(n => n.rule === rule && (!role || n.role === role));
34
+ const states = m.state.filter(v => !m.outputs.includes(v.name)).flatMap(v => {
35
+ const n = name(v.name, 'state');
36
+ return n && !n.map && !n.none ? [{ v, n }] : [];
37
+ });
38
+ const inputs = m.inputs.filter(v => v.name !== m.event).flatMap(v => {
39
+ const n = name(v.name, 'input');
40
+ return n && !n.none ? [{ v, n }] : [];
41
+ });
42
+ const add = (s) => {
43
+ const laws = securityLaws(s).filter(l => !out.some(o => o.expr === l.expr && o.method === l.method));
44
+ if (out.length + laws.length <= max)
45
+ out.push(...laws); // never truncate an isolation pair
46
+ };
47
+ for (const { v, n } of states) {
48
+ if (v.sort.k !== 'num')
49
+ continue;
50
+ add({ kind: 'ledger', name: `${n.code} never negative`, balance: n.code });
51
+ for (const p of m.params.filter(p => p.sort.k === 'num')) {
52
+ const cap = name(p.name, 'param');
53
+ if (cap)
54
+ add({ kind: 'quota', name: `${n.code} within ${cap.code}`, used: n.code, limit: cap.code });
55
+ }
56
+ }
57
+ for (const { v, n } of inputs) {
58
+ // Arbitrary bool requests, and every value of a role/permission choice: no privileged value guessed.
59
+ const requirements = v.sort.k === 'bool' ? [n.code] : v.sort.k === 'choice' ? v.sort.values.map(c => `${n.code} == ${JSON.stringify(c)}`) : [];
60
+ const effects = states.map(s => ({ expr: `${s.n.code} != old(${s.n.code})`, label: `changing ${s.n.code}` }));
61
+ for (const result of names.filter(r => r.role === 'result' && r.method === n.method && !r.none)) {
62
+ if (m.state.find(s => s.name === result.rule)?.sort.k === 'bool')
63
+ effects.push({ expr: result.code, label: `${n.method} succeeds` });
64
+ }
65
+ for (const req of requirements)
66
+ for (const effect of effects)
67
+ add({ kind: 'authorization', name: `${effect.label} requires ${req}`, method: n.method, effect: effect.expr, requires: req });
68
+ }
69
+ for (const before of states.filter(s => s.v.sort.k === 'bool'))
70
+ for (const after of states.filter(s => s.v.name !== before.v.name)) {
71
+ add({ kind: 'workflow', name: `changing ${after.n.code} only after ${before.n.code}`, effect: `${after.n.code} != old(${after.n.code})`, prerequisite: before.n.code });
72
+ }
73
+ let key = 'securityKey';
74
+ while (names.some(n => n.code === key || n.rule === key))
75
+ key += '_';
76
+ for (const map of m.maps.filter(d => !d.carried && !d.ordered)) {
77
+ const n = name(map.name, 'state');
78
+ if (!n?.map || n.none)
79
+ continue;
80
+ for (const input of inputs.filter(i => i.v.sort.k === (map.key === 'str' ? 'str' : 'num'))) {
81
+ if (names.some(n => n.role === 'result' && n.method === input.n.method))
82
+ add({ kind: 'isolation', name: `reads isolated by ${input.n.code}`, identity: input.n.code, seeing: 'result', method: input.n.method });
83
+ add({ kind: 'isolation', name: `${n.code} isolated by ${input.n.code}`, map: n.code, identity: input.n.code, method: input.n.method,
84
+ fields: map.fields.filter(f => f.name !== 'has').map(f => f.name), key });
85
+ }
86
+ }
87
+ return out;
88
+ }
@@ -15,6 +15,9 @@ How the rule's values are the code's:
15
15
  import json
16
16
  import os
17
17
  import random
18
+ import shutil
19
+ import signal
20
+ import tempfile
18
21
  import socket
19
22
  import subprocess
20
23
  import sys
@@ -67,13 +70,56 @@ class RpcError(Exception):
67
70
  pass
68
71
 
69
72
 
73
+ # anvil's state on disk: none it keeps (--prune-history), and whatever it writes (its cache, a HOME's ~/.foundry) in a
74
+ # directory of this harness's own, gdp-anvil-<pid>-*, removed when it stops. anvil runs under a watchdog in its own
75
+ # session: the harness gone, even killed (SIGKILL, a preempted job), the watchdog stops anvil and removes the directory.
76
+ # What killed runs of earlier harnesses left (their directory, their pid gone; anvil's own ~/.foundry/anvil/tmp state
77
+ # folders past STALE_S unwritten) is removed at start.
78
+ STALE_S = 2 * 3600
79
+ WATCH = 'd=$1; h=$2; shift 2; trap \'kill $a 2>/dev/null; wait $a 2>/dev/null; rm -rf "$d"; exit 0\' TERM INT HUP; HOME="$d" "$@" & a=$!; while kill -0 "$h" 2>/dev/null && kill -0 $a 2>/dev/null; do sleep 0.5; done; kill $a 2>/dev/null; wait $a 2>/dev/null; rm -rf "$d"'
80
+
81
+
82
+ def clean_stale():
83
+ base = tempfile.gettempdir()
84
+ for n in os.listdir(base):
85
+ if not n.startswith('gdp-anvil-'): continue
86
+ try: pid = int(n.split('-')[2])
87
+ except (IndexError, ValueError): continue
88
+ try: os.kill(pid, 0); continue # (its harness still runs)
89
+ except ProcessLookupError: pass
90
+ except PermissionError: continue
91
+ shutil.rmtree(os.path.join(base, n), ignore_errors=True)
92
+ legacy = os.path.join(os.path.expanduser('~'), '.foundry', 'anvil', 'tmp')
93
+ if os.path.isdir(legacy):
94
+ now = time.time()
95
+ for n in os.listdir(legacy):
96
+ p = os.path.join(legacy, n)
97
+ try:
98
+ if now - os.path.getmtime(p) > STALE_S: shutil.rmtree(p, ignore_errors=True) if os.path.isdir(p) else os.remove(p)
99
+ except OSError: pass
100
+
101
+
102
+ def stop_anvil():
103
+ p, d = S.pop('anvil', None), S.pop('anvil_dir', None)
104
+ if p is not None:
105
+ try: os.killpg(p.pid, signal.SIGTERM)
106
+ except (ProcessLookupError, PermissionError): pass
107
+ try: p.wait(timeout=10)
108
+ except subprocess.TimeoutExpired:
109
+ try: os.killpg(p.pid, signal.SIGKILL)
110
+ except (ProcessLookupError, PermissionError): pass
111
+ if d: shutil.rmtree(d, ignore_errors=True)
112
+
113
+
70
114
  def start_anvil():
71
115
  exe = os.environ.get('GDP_ANVIL') or 'anvil'
116
+ clean_stale()
72
117
  for _ in range(20):
73
118
  port = random.randint(20000, 60000)
74
119
  with socket.socket() as s:
75
120
  if s.connect_ex(('127.0.0.1', port)) == 0: continue
76
- p = subprocess.Popen([exe, '--port', str(port), '--silent', '--gas-price', '0', '--base-fee', '0', '--disable-block-gas-limit', '--disable-code-size-limit', '--auto-impersonate', '--accounts', '1', '--hardfork', 'cancun'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
121
+ d = S['anvil_dir'] = tempfile.mkdtemp(prefix=f'gdp-anvil-{os.getpid()}-')
122
+ p = subprocess.Popen(['sh', '-c', WATCH, 'gdp-anvil', d, str(os.getpid()), exe, '--port', str(port), '--silent', '--gas-price', '0', '--base-fee', '0', '--disable-block-gas-limit', '--disable-code-size-limit', '--auto-impersonate', '--accounts', '1', '--hardfork', 'cancun', '--prune-history', '--cache-path', os.path.join(d, 'cache')], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
77
123
  S['anvil'] = p
78
124
  PORT[0] = port
79
125
  for _ in range(100):
@@ -83,7 +129,7 @@ def start_anvil():
83
129
  except Exception:
84
130
  if p.poll() is not None: break
85
131
  time.sleep(0.05)
86
- p.kill()
132
+ stop_anvil()
87
133
  raise RuntimeError('anvil did not start (foundry\'s anvil on the PATH, or $GDP_ANVIL)')
88
134
 
89
135
 
@@ -477,7 +523,7 @@ def main():
477
523
  try: res = replay(req)
478
524
  except Exception as e: res = {'error': f'{type(e).__name__}: {e}'[:500], **({'transport': True} if isinstance(e, OSError) else {})}
479
525
  finally:
480
- if S.get('anvil'): S['anvil'].kill()
526
+ stop_anvil()
481
527
  print(json.dumps(res))
482
528
  return
483
529
  fin = open(sys.argv[1], 'r'); fout = open(sys.argv[2], 'w')
@@ -504,8 +550,15 @@ def main():
504
550
  res = {'error': f'{type(e).__name__}: {e}'[:500], **({'transport': True} if isinstance(e, OSError) else {})}
505
551
  fout.write(json.dumps(res) + '\n'); fout.flush()
506
552
  finally:
507
- if S.get('anvil'): S['anvil'].kill()
553
+ stop_anvil()
554
+
555
+
556
+ def on_signal(n, _f):
557
+ # (stopped by a signal: anvil and its directory go first)
558
+ stop_anvil()
559
+ sys.exit(128 + n)
508
560
 
509
561
 
510
562
  if __name__ == '__main__':
563
+ for n in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): signal.signal(n, on_signal)
511
564
  main()
@@ -0,0 +1,23 @@
1
+ import type { Compiled, SolOptions } from './extract-sol.js';
2
+ import { Refusal } from './extract-read.js';
3
+ type Compiler = (file: string, options: SolOptions, extra?: Record<string, string>) => Compiled;
4
+ export type SolidityHarness = {
5
+ kind: 'repository' | 'constructor' | 'library';
6
+ target: {
7
+ source: string;
8
+ contract: string;
9
+ };
10
+ source: string;
11
+ entry: string;
12
+ constructors: string[];
13
+ overrides: string[];
14
+ addedMethods: string[];
15
+ notes: string[];
16
+ generatedSource?: string;
17
+ };
18
+ export declare class SolidityHarnessRefusal extends Refusal {
19
+ readonly harness: SolidityHarness;
20
+ constructor(cause: Refusal, harness: SolidityHarness);
21
+ }
22
+ export declare function concreteSolidity(file: string, o: SolOptions, original: Compiled, compile: Compiler): Compiled;
23
+ export {};
@@ -0,0 +1,195 @@
1
+ import { Refusal } from "./extract-read.js";
2
+ import { node } from "./extract-step.js";
3
+ export class SolidityHarnessRefusal extends Refusal {
4
+ harness;
5
+ constructor(cause, harness) {
6
+ super(cause.where, cause.what);
7
+ this.harness = harness;
8
+ }
9
+ }
10
+ const contracts = (c) => [...c.ast.values()].flatMap(a => a.nodes.filter(n => n.nodeType === 'ContractDefinition'));
11
+ const source = (c, n) => c.paths.get(Number(n.src.split(':')[2]));
12
+ const text = (c, n) => { const [at, size, id] = n.src.split(':').map(Number); return new TextDecoder().decode(new TextEncoder().encode(c.text.get(id)).slice(at, at + size)); };
13
+ const ctor = (n) => n.nodes.find(n => n.nodeType === 'FunctionDefinition' && n.kind === 'constructor');
14
+ const signature = (f) => `${f.name}(${f.parameters.parameters.map(p => p.typeDescriptions.typeString).join(',')})`;
15
+ const chain = (c, n) => { const ds = contracts(c); return n.linearizedBaseContracts.map(id => ds.find(d => d.id === id)); };
16
+ function mentions(n, id) {
17
+ if (Array.isArray(n))
18
+ return n.some(v => mentions(v, id));
19
+ if (!n || typeof n !== 'object')
20
+ return false;
21
+ const a = n;
22
+ return a.referencedDeclaration === id || Object.values(a).some(v => v && typeof v === 'object' && mentions(v, id));
23
+ }
24
+ function matches(c, candidate, targetSource, targetName, library) {
25
+ const target = contracts(c).find(n => source(c, n) === targetSource && n.name === targetName);
26
+ if (!target)
27
+ return false;
28
+ const bases = chain(c, candidate);
29
+ return library ? bases.some(n => mentions(n.nodes, target.id)) : bases.some(n => n.id === target.id);
30
+ }
31
+ function describe(c, entry, targetSource, targetName, kind, generatedSource) {
32
+ const bases = chain(c, entry), inherited = new Set(), overrides = [], addedMethods = [];
33
+ for (const b of [...bases].reverse())
34
+ for (const f of b.nodes) {
35
+ if (f.nodeType !== 'FunctionDefinition' || f.kind !== 'function')
36
+ continue;
37
+ const s = signature(f);
38
+ if (inherited.has(s) && f.body)
39
+ overrides.push(`${b.name}.${s} (${source(c, b)})`);
40
+ if (b.id === entry.id && f.body && ['public', 'external'].includes(f.visibility) && !inherited.has(s))
41
+ addedMethods.push(s);
42
+ inherited.add(s);
43
+ }
44
+ const constructors = bases.flatMap(b => { const f = ctor(b); return f ? [`${b.name}: ${text(c, f)}`] : []; });
45
+ const h = { kind, target: { source: targetSource, contract: targetName }, source: source(c, entry), entry: entry.name,
46
+ constructors, overrides, addedMethods, ...(generatedSource === undefined ? {} : { generatedSource }), notes: [] };
47
+ h.notes = [
48
+ `Solidity concrete harness (${kind}): ${h.source}:${h.entry} for ${targetSource}:${targetName}; the original source units and function bodies are unchanged`,
49
+ 'harness scope: laws and replay concern this concrete deployment, not every possible subclass or caller of the abstract contract or library',
50
+ 'harness constructor arguments are rule parameters, subject to the original constructor guards; constructors execute as written (listed in extraction.harness.constructors)',
51
+ `harness overrides: ${overrides.length ? overrides.join('; ') : 'none'}; additional public entry points: ${addedMethods.length ? addedMethods.join('; ') : 'none'}`,
52
+ ...(kind === 'constructor' ? ['synthetic subclass: only a constructor forwarding the missing base-constructor arguments; no function implementation or override is invented'] : []),
53
+ ...(kind === 'library' ? ['synthetic library caller: only forwarding functions for internal library functions; no storage context, linked library, or external-call behavior is invented'] : []),
54
+ ];
55
+ return h;
56
+ }
57
+ // The ordinary concrete-contract path is unchanged. An explicit harness can also bind a concrete base.
58
+ export function concreteSolidity(file, o, original, compile) {
59
+ if (original.harness || o.harness === false)
60
+ return original;
61
+ const mode = o.harness;
62
+ if (mode !== undefined && mode !== 'auto' && (!mode || typeof mode !== 'object' || typeof mode.file !== 'string' || !mode.file || (mode.entry !== undefined && (typeof mode.entry !== 'string' || !mode.entry)))) {
63
+ throw new Refusal(file, 'harness must be auto, false, or {file, entry?}');
64
+ }
65
+ const all = contracts(original), own = all.filter(n => source(original, n) === original.paths.get(original.main));
66
+ const wanted = typeof o.entry === 'string' ? all.filter(n => n.name === o.entry) : own;
67
+ if (wanted.length !== 1)
68
+ return original; // The normal reader diagnoses ambiguous/missing entries.
69
+ const target = wanted[0], explicit = typeof o.harness === 'object' ? o.harness : undefined;
70
+ if (!explicit && target.contractKind === 'contract' && !target.abstract)
71
+ return original;
72
+ if (target.contractKind === 'interface')
73
+ throw new Refusal(file, `${target.name}: an interface has no inherited implementation to make concrete`);
74
+ const fs = node('node:fs'), path = node('node:path'), root = path.resolve(o.root ?? path.dirname(file));
75
+ const targetSource = source(original, target), library = target.contractKind === 'library';
76
+ const adopt = (c, entry, kind, generatedSource) => {
77
+ const h = describe(c, entry, targetSource, target.name, kind, generatedSource);
78
+ return { ...c, harness: h };
79
+ };
80
+ const usable = (c) => contracts(c).filter(n => n.contractKind === 'contract' && !n.abstract && matches(c, n, targetSource, target.name, library));
81
+ if (explicit) {
82
+ const p = path.resolve(root, explicit.file), c = compile(p, { ...o, root }), candidates = usable(c).filter(n => !explicit.entry || n.name === explicit.entry);
83
+ if (candidates.length !== 1)
84
+ throw new Refusal(file, `harness ${explicit.file}${explicit.entry ? `:${explicit.entry}` : ''}: expected one concrete ${library ? 'caller of' : 'subclass of'} ${target.name}, found ${candidates.length}`);
85
+ return adopt(c, candidates[0], 'repository');
86
+ }
87
+ // Search source, not a hand-maintained project/name allowlist. solc, not text matching, establishes inheritance.
88
+ const files = [], escaped = target.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), token = new RegExp(`\\b${escaped}\\b`);
89
+ let count = 0;
90
+ const walk = (dir) => {
91
+ for (const d of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
92
+ if (d.name.startsWith('.') || ['node_modules', 'vendor', 'out', 'cache', 'artifacts', 'runs'].includes(d.name))
93
+ continue;
94
+ const p = path.resolve(dir, d.name);
95
+ if (d.isDirectory())
96
+ walk(p);
97
+ else if (d.isFile() && d.name.endsWith('.sol')) {
98
+ if (++count > 4096)
99
+ throw new Refusal(file, 'harness search exceeds 4096 Solidity sources; state harness: {file, entry}');
100
+ if (p !== path.resolve(file) && token.test(fs.readFileSync(p, 'utf8')))
101
+ files.push(p);
102
+ }
103
+ }
104
+ };
105
+ walk(root);
106
+ if (files.length > 64)
107
+ throw new Refusal(file, `${target.name}: more than 64 possible harness sources; state harness: {file, entry}`);
108
+ const found = [];
109
+ for (const p of files) {
110
+ let c;
111
+ try {
112
+ c = compile(p, { ...o, root });
113
+ }
114
+ catch (e) {
115
+ if (e instanceof Refusal)
116
+ continue;
117
+ throw e;
118
+ }
119
+ for (const entry of usable(c))
120
+ if (source(c, entry) === c.paths.get(c.main))
121
+ found.push({ c, entry });
122
+ }
123
+ const preferred = found.filter(({ entry }) => entry.name === `${target.name}Mock` || entry.name === `${target.name}Harness` || entry.name === `${target.name}Test`);
124
+ const candidates = preferred.length ? preferred : found;
125
+ if (candidates.length === 1)
126
+ return adopt(candidates[0].c, candidates[0].entry, 'repository');
127
+ if (candidates.length > 1)
128
+ throw new Refusal(file, `${target.name}: several concrete repository harnesses (${candidates.map(({ c, entry }) => `${source(c, entry)}:${entry.name}`).join(', ')}); state harness: {file, entry}`);
129
+ // New source unit only. Names cannot collide with source units or contracts already in the compilation.
130
+ let entry = `GDPConcrete_${target.name}`, unit = '__gdp_concrete.sol';
131
+ while (all.some(n => n.name === entry))
132
+ entry += '_';
133
+ while ([...original.paths.values()].includes(unit) || fs.existsSync(path.resolve(root, unit)))
134
+ unit = `_${unit}`;
135
+ const imports = new Set([targetSource]), params = [], forwards = [];
136
+ let body, methods;
137
+ const param = (p, i) => {
138
+ if (p.storageLocation === 'storage')
139
+ throw new Refusal(file, `${target.name}: a library storage parameter needs an explicit caller/storage harness`);
140
+ return `${text(original, p.typeName)}${p.storageLocation && p.storageLocation !== 'default' ? ` ${p.storageLocation}` : ''} __gdp_arg${i}`;
141
+ };
142
+ if (library) {
143
+ const fns = target.nodes.filter(n => n.nodeType === 'FunctionDefinition' && n.kind === 'function' && n.visibility !== 'private' && (!o.methods || o.methods.includes(n.name)));
144
+ if (!fns.length)
145
+ throw new Refusal(file, `${target.name}: no library function selected for a concrete caller`);
146
+ for (const f of fns)
147
+ if (f.visibility !== 'internal')
148
+ throw new Refusal(file, `${target.name}.${f.name}: a public/external library call needs a deployed, linked library harness`);
149
+ body = fns.map(f => {
150
+ const ps = f.parameters.parameters, rs = f.returnParameters.parameters;
151
+ const ret = rs.length ? ` returns (${rs.map((p, i) => param(p, i).replace(/ __gdp_arg\d+$/, '')).join(', ')})` : '';
152
+ return `function ${f.name}(${ps.map(param).join(', ')}) external ${['view', 'pure'].includes(f.stateMutability) ? f.stateMutability : ''}${ret} { ${rs.length ? 'return ' : ''}${target.name}.${f.name}(${ps.map((_, i) => `__gdp_arg${i}`).join(', ')}); }`;
153
+ }).join('\n');
154
+ methods = fns.map(f => f.name);
155
+ }
156
+ else {
157
+ const bases = chain(original, target), bound = new Set();
158
+ for (const b of bases) {
159
+ for (const s of b.baseContracts)
160
+ if (s.arguments !== null && s.arguments !== undefined)
161
+ bound.add(s.baseName.referencedDeclaration);
162
+ for (const m of (ctor(b)?.modifiers ?? []))
163
+ if (bases.some(b => b.id === m.modifierName.referencedDeclaration))
164
+ bound.add(m.modifierName.referencedDeclaration);
165
+ }
166
+ const seen = new Set(), missing = [];
167
+ for (const b of bases)
168
+ for (const f of b.nodes) {
169
+ if (f.nodeType !== 'FunctionDefinition' || f.kind === 'constructor')
170
+ continue;
171
+ const sig = signature(f);
172
+ if (!seen.has(sig) && !f.body)
173
+ missing.push(sig);
174
+ seen.add(sig);
175
+ }
176
+ if (missing.length && target.fullyImplemented !== true)
177
+ throw new Refusal(file, `${target.name}: abstract functions remain (${missing.join(', ')}); a constructor-only harness cannot invent their bodies (state a repository harness)`);
178
+ for (const b of bases) {
179
+ const f = ctor(b), ps = (f?.parameters.parameters ?? []);
180
+ if (!ps.length || bound.has(b.id))
181
+ continue;
182
+ imports.add(source(original, b));
183
+ const names = ps.map(p => { const i = params.length; params.push(param(p, i)); return `__gdp_arg${i}`; });
184
+ forwards.push(`${b.name}(${names.join(', ')})`);
185
+ }
186
+ const payable = ctor(target)?.stateMutability === 'payable' ? ' payable' : '';
187
+ body = `constructor(${params.join(', ')})${payable} ${forwards.join(' ')} {}`;
188
+ }
189
+ const generated = `// Generated concrete entry; every original source unit is unchanged.\n${[...imports].map(p => `import ${JSON.stringify(p)};`).join('\n')}\ncontract ${entry}${library ? '' : ` is ${target.name}`} {\n${body}\n}\n`;
190
+ const c = compile(file, { ...o, root }, { [unit]: generated }), selected = contracts(c).find(n => n.name === entry && source(c, n) === unit);
191
+ if (!selected || selected.abstract)
192
+ throw new Refusal(file, `${target.name}: the constructor-only harness is not concrete`);
193
+ const out = adopt({ ...c, main: Number(selected.src.split(':')[2]) }, selected, library ? 'library' : 'constructor', generated);
194
+ return { ...out, harnessMethods: methods };
195
+ }
@@ -90,7 +90,9 @@ export const linOfE = (e) => {
90
90
  case 'min':
91
91
  case 'max':
92
92
  case 'if':
93
- case 'get': return undefined;
93
+ case 'get':
94
+ case 'tup':
95
+ case 'proj': return undefined;
94
96
  }
95
97
  };
96
98
  // l with each name of m's replaced by its form there