gdp-wired 0.45.0 → 0.47.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 (126) hide show
  1. package/README.md +61 -8
  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 +4 -0
  10. package/dist/core/cli.js +206 -40
  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-schema.d.ts +90 -0
  27. package/dist/core/effect-schema.js +500 -0
  28. package/dist/core/effect.d.ts +4 -11
  29. package/dist/core/effect.js +3 -79
  30. package/dist/core/exists.d.ts +1 -0
  31. package/dist/core/exists.js +191 -16
  32. package/dist/core/extract-c.d.ts +2 -0
  33. package/dist/core/extract-c.js +169 -22
  34. package/dist/core/extract-check.d.ts +1 -0
  35. package/dist/core/extract-check.js +97 -6
  36. package/dist/core/extract-go-check.d.ts +1 -1
  37. package/dist/core/extract-go-check.js +26 -5
  38. package/dist/core/extract-go.d.ts +8 -0
  39. package/dist/core/extract-go.js +67 -6
  40. package/dist/core/extract-ir.d.ts +1 -0
  41. package/dist/core/extract-ir.js +15 -0
  42. package/dist/core/extract-jvm.d.ts +1 -1
  43. package/dist/core/extract-jvm.js +2 -0
  44. package/dist/core/extract-orm.d.ts +12 -0
  45. package/dist/core/extract-orm.js +244 -0
  46. package/dist/core/extract-print.js +20 -1
  47. package/dist/core/extract-py.d.ts +1 -0
  48. package/dist/core/extract-py.js +1 -1
  49. package/dist/core/extract-read.d.ts +26 -1
  50. package/dist/core/extract-read.js +14 -7
  51. package/dist/core/extract-rs.js +63 -15
  52. package/dist/core/extract-shapes.d.ts +1 -0
  53. package/dist/core/extract-shapes.js +84 -0
  54. package/dist/core/extract-sol.d.ts +10 -1
  55. package/dist/core/extract-sol.js +70 -22
  56. package/dist/core/extract-standalone.d.ts +3 -0
  57. package/dist/core/extract-standalone.js +221 -0
  58. package/dist/core/extract-step.d.ts +151 -1
  59. package/dist/core/extract-step.js +1232 -60
  60. package/dist/core/extract-swift.js +6 -2
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +77 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/infer.d.ts +4 -1
  66. package/dist/core/infer.js +918 -217
  67. package/dist/core/jvm/JavaReader.java +23 -6
  68. package/dist/core/jvm/Jvm.java +3 -0
  69. package/dist/core/jvm/KtReader.java +6 -5
  70. package/dist/core/laws.d.ts +10 -3
  71. package/dist/core/laws.js +226 -23
  72. package/dist/core/machine.d.ts +15 -1
  73. package/dist/core/machine.js +187 -15
  74. package/dist/core/nonterm.js +14 -1
  75. package/dist/core/orm/harness.js +61 -0
  76. package/dist/core/orm-fixtures/schema.prisma +5 -0
  77. package/dist/core/py/harness.py +183 -10
  78. package/dist/core/py/reader.py +234 -40
  79. package/dist/core/reader-fixtures/README.md +28 -0
  80. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  81. package/dist/core/reader-fixtures/go-685506.go +14 -0
  82. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  83. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  84. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  85. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  86. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  87. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  88. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  89. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  90. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  91. package/dist/core/relation.d.ts +1 -1
  92. package/dist/core/relation.js +29 -2
  93. package/dist/core/relational.js +4 -2
  94. package/dist/core/rs/Cargo.toml +1 -1
  95. package/dist/core/rs/src/main.rs +466 -11
  96. package/dist/core/sample-cache.d.ts +8 -0
  97. package/dist/core/sample-cache.js +46 -0
  98. package/dist/core/security.d.ts +38 -0
  99. package/dist/core/security.js +88 -0
  100. package/dist/core/sol/harness.py +57 -4
  101. package/dist/core/sol-concrete.d.ts +23 -0
  102. package/dist/core/sol-concrete.js +195 -0
  103. package/dist/core/solver.js +3 -1
  104. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  105. package/dist/core/system.js +1 -1
  106. package/dist/core/transfer.js +22 -9
  107. package/dist/core/translate.js +39 -10
  108. package/dist/core/watch.js +50 -5
  109. package/dist/interchange/format.js +11 -1
  110. package/dist/kernel/cdcl.d.ts +5 -0
  111. package/dist/kernel/cdcl.js +56 -9
  112. package/dist/kernel/epr.js +108 -26
  113. package/dist/kernel/kernel.d.ts +29 -1
  114. package/dist/kernel/kernel.js +325 -62
  115. package/dist/kernel/model-sequence.d.ts +3 -0
  116. package/dist/kernel/model-sequence.js +34 -0
  117. package/dist/kernel/prove.d.ts +10 -3
  118. package/dist/kernel/prove.js +332 -71
  119. package/dist/kernel/reader.d.ts +3 -0
  120. package/dist/kernel/reader.js +101 -14
  121. package/dist/kernel/share.d.ts +1 -0
  122. package/dist/kernel/share.js +27 -0
  123. package/dist/lean-kernel/emit.js +30 -37
  124. package/dist/lean-kernel/lean-terms.js +5 -0
  125. package/dist/lean-kernel/library.js +10 -10
  126. package/package.json +6 -1
@@ -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
@@ -201,6 +201,19 @@ final class Reader {
201
201
  func load(_ paths: [String]) {
202
202
  for p in paths {
203
203
  guard let src = try? String(contentsOfFile: p, encoding: .utf8) else { continue }
204
+ // A linear, conservative resource preflight before SwiftParser's error recovery. Deep
205
+ // unclosed delimiters can make that recovery exponential, even in a tiny source file.
206
+ // Count text (including strings/comments), not syntax: this is a reader limit, not a
207
+ // claim that the source is invalid. The compiler still checks every accepted source.
208
+ var depth = 0
209
+ for c in src.utf8 {
210
+ if c == 40 || c == 91 || c == 123 { depth += 1 }
211
+ else if c == 41 || c == 93 || c == 125 { depth = max(0, depth - 1) }
212
+ if depth > 32 {
213
+ FileHandle.standardError.write(Data("gdp: refused: \(p): the source nests delimiter characters past reader limit 32 (including strings and comments)\n".utf8))
214
+ exit(1)
215
+ }
216
+ }
204
217
  let parsed = Parser.parse(source: src)
205
218
  let folded = OperatorTable.standardOperators.foldAll(parsed) { _ in }.as(SourceFileSyntax.self) ?? parsed
206
219
  let rel = p.hasPrefix(root + "/") ? String(p.dropFirst(root.count + 1)) : p
@@ -460,7 +473,7 @@ final class Reader {
460
473
  // The initializer: the one there is, or the one of the arity asked for (ctor); none: the memberwise one (a struct's)
461
474
  // or the default one (a class's whose properties all have initial values).
462
475
  var inits: [(InitializerDeclSyntax, String)] = []
463
- for (mf, d) in t.members { if let i = d.as(InitializerDeclSyntax.self), i.optionalMark == nil { inits.append((i, mf)) } }
476
+ for (mf, d) in t.members { if let i = d.as(InitializerDeclSyntax.self) { inits.append((i, mf)) } }
464
477
  let initId = "\(t.qual).__init__"
465
478
  var ctorJ: J = .null
466
479
  let bare = { (s: String) in s.filter { !$0.isWhitespace } }
@@ -474,15 +487,19 @@ final class Reader {
474
487
  } else if pick.count != 1 {
475
488
  funcs.append((initId, stub(initId, "__init__", t, pick.isEmpty ? "no init of the arity or parameters asked for (ctor)" : "a type with \(pick.count) inits (name one by its arity or its parameters: ctor, e.g. \"(limit: Int)\")")))
476
489
  methodsJ.append(("__init__", .s(initId)))
490
+ } else if pick[0].0.optionalMark != nil {
491
+ funcs.append((initId, stub(initId, "__init__", t, "a failable initializer (init? or init!)")))
492
+ methodsJ.append(("__init__", .s(initId)))
477
493
  } else {
478
494
  let (i, mf) = pick[0]
479
495
  funcs.append((initId, with(file: mf) { initFunc(i, t, ps, initId) }))
480
496
  methodsJ.append(("__init__", .s(initId)))
481
- for (o, of) in inits where o != i {
482
- let labels = o.signature.parameterClause.parameters.map { $0.firstName.text }
483
- let oid = "\(t.qual).__init__/\(labels.joined(separator: ":"))"
484
- funcs.append((oid, with(file: of) { initFunc(o, t, ps, oid) }))
485
- methodsJ.append(("__init__/\(labels.joined(separator: ":"))", .s(oid)))
497
+ for (o, of) in inits {
498
+ let key = "__init__/" + bare(o.signature.parameterClause.trimmedDescription)
499
+ if o == i { methodsJ.append((key, .s(initId))); continue }
500
+ let oid = "\(t.qual).\(key)"
501
+ funcs.append((oid, o.optionalMark != nil ? stub(oid, key, t, "a failable initializer (init? or init!)") : with(file: of) { initFunc(o, t, ps, oid) }))
502
+ methodsJ.append((key, .s(oid)))
486
503
  }
487
504
  ctorJ = ["labels": .a(i.signature.parameterClause.parameters.map { .s($0.firstName.text) }), "throws": .b(i.signature.effectSpecifiers?.trimmedDescription.contains("throws") ?? false),
488
505
  "types": .a(i.signature.parameterClause.parameters.map { .s($0.type.trimmedDescription) })]
@@ -508,6 +525,7 @@ final class Reader {
508
525
  var inits0: J = .null
509
526
  if !own.isEmpty { inits0 = .s("a subclass of \(own[0].qual) (the subset reads a class with no superclass of the code's own)") }
510
527
  recs.append((t.qual, ["name": .s(t.qual), "short": .s(t.name), "fields": .a(fields), "methods": .o(methodsJ), "kinds": .a(kinds), "own": true, "module": "", "p": .s("\(t.file):\(t.line):1"),
528
+ "initializers": ctorArity == nil && ctorSig == nil && inits.count > 1 ? .a(inits.map { .s($0.0.signature.parameterClause.trimmedDescription) }) : .null,
511
529
  "swift": ["kind": .s(t.kind), "qual": .s(t.qual), "file": .s(t.file), "priv": .b(t.priv), "ctor": ctorJ, "sigs": .o(sigs), "refused": inits0,
512
530
  "props": .a(ps.map { ["name": .s($0.name), "t": .s($0.ttext), "let": .b($0.isLet), "kw": .s($0.kw), "init": .b($0.hasInit)] })]]))
513
531
  if !inits0.isNull { funcs.removeAll { $0.0 == initId }; funcs.append((initId, stub(initId, "__init__", t, inits0.str!))) }
@@ -1114,7 +1132,32 @@ final class Reader {
1114
1132
  return ([], no(p, "\(t): a case with associated values, or a static member the context doesn't state"))
1115
1133
  }
1116
1134
  let bt = base.trimmedDescription
1117
- if bt == "self", n == "init" { let (pre, xs) = args(c.arguments); return (pre, X("call", p, [("f", X("get", p, [("x", v("self", p)), ("f", .s("__init__/\(labels.joined(separator: ":"))")), ("text", "self.init")])), ("args", .a(xs)), ("kw", []), ("text", .s(t))])) }
1135
+ if bt == "self", n == "init" {
1136
+ var candidates = selfTy?.members.compactMap { $0.1.as(InitializerDeclSyntax.self) }.filter { $0.signature.parameterClause.parameters.map { $0.firstName.text } == labels } ?? []
1137
+ if candidates.count > 1 {
1138
+ // No contextual guess for literals, operators, generic conversions or overload results.
1139
+ // A declared scalar value or explicit integer conversion has an exact argument type.
1140
+ func exactScalar(_ e: ExprSyntax) -> TT? {
1141
+ if let parens = e.as(TupleExprSyntax.self), parens.elements.count == 1 { return exactScalar(parens.elements.first!.expression) }
1142
+ let integerCast: Bool = { guard let call = e.as(FunctionCallExprSyntax.self), let name = call.calledExpression.as(DeclReferenceExprSyntax.self)?.baseName.text else { return false }; return INTS[name] != nil && local(name) == nil }()
1143
+ guard e.is(DeclReferenceExprSyntax.self) || e.is(MemberAccessExprSyntax.self) || integerCast,
1144
+ let known = typeOf(e).map(resolve), case .n(let name, let parameters) = known,
1145
+ parameters.isEmpty, INTS[name] != nil || name == "Bool" || name == "String" else { return nil }
1146
+ return known
1147
+ }
1148
+ let known = c.arguments.map { exactScalar($0.expression) }
1149
+ candidates = candidates.filter { candidate in
1150
+ let declared = candidate.signature.parameterClause.parameters.map { resolve(parseType($0.type.trimmedDescription)) }
1151
+ return zip(known, declared).allSatisfy { actual, expected in actual == expected }
1152
+ }
1153
+ }
1154
+ guard candidates.count == 1 else { return ([], no(p, "\(t): initializer delegation has ambiguous parameter labels (an exact scalar overload is required)")) }
1155
+ let selected = candidates[0]
1156
+ let key = "__init__/" + selected.signature.parameterClause.trimmedDescription.filter { !$0.isWhitespace }
1157
+ let expected = selected.signature.parameterClause.parameters.map { parseType($0.type.trimmedDescription) }
1158
+ let (pre, xs) = args(c.arguments, expected)
1159
+ return (pre, X("call", p, [("f", X("get", p, [("x", v("self", p)), ("f", .s(key)), ("text", "self.init")])), ("args", .a(xs)), ("kw", []), ("text", .s(t))]))
1160
+ }
1118
1161
  if bt.first?.isUppercase == true, local(bt) == nil, base.is(DeclReferenceExprSyntax.self) || base.is(MemberAccessExprSyntax.self) {
1119
1162
  let tn = bt == "Self" ? selfTy?.name ?? bt : bt
1120
1163
  if let x = ty(named: tn, from: selfTy) {
@@ -280,7 +280,7 @@ export function isolation(m, level) {
280
280
  return ite(sigmaC(e.c), sigma(e.then), sigma(e.else));
281
281
  if (e.op === 'const')
282
282
  return e;
283
- if (e.op === 'mul')
283
+ if (e.op === 'mul' || e.op === 'proj')
284
284
  return { ...e, a: sigma(e.a) };
285
285
  return { ...e, a: sigma(e.a), b: sigma(e.b) };
286
286
  };