gdp-wired 0.44.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 (133) 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 +445 -38
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/check.js +3 -2
  10. package/dist/core/cli.d.ts +4 -0
  11. package/dist/core/cli.js +335 -39
  12. package/dist/core/compose.js +3 -1
  13. package/dist/core/counts.d.ts +5 -2
  14. package/dist/core/counts.js +335 -88
  15. package/dist/core/cycles.js +8 -1
  16. package/dist/core/cyclic.d.ts +1 -0
  17. package/dist/core/cyclic.js +13 -7
  18. package/dist/core/data-synth.d.ts +3 -0
  19. package/dist/core/data-synth.js +252 -0
  20. package/dist/core/data.d.ts +8 -2
  21. package/dist/core/data.js +1113 -172
  22. package/dist/core/discover.js +3 -1
  23. package/dist/core/draft.d.ts +19 -0
  24. package/dist/core/draft.js +53 -0
  25. package/dist/core/dsl.d.ts +39 -3
  26. package/dist/core/dsl.js +250 -31
  27. package/dist/core/effect-prims.js +2 -2
  28. package/dist/core/effect.d.ts +1 -4
  29. package/dist/core/effect.js +1 -15
  30. package/dist/core/ex/reader.exs +17 -1
  31. package/dist/core/exists.d.ts +16 -1
  32. package/dist/core/exists.js +447 -50
  33. package/dist/core/extract-c.d.ts +2 -0
  34. package/dist/core/extract-c.js +185 -31
  35. package/dist/core/extract-check.d.ts +7 -0
  36. package/dist/core/extract-check.js +115 -3
  37. package/dist/core/extract-ex.js +3 -3
  38. package/dist/core/extract-go-check.d.ts +1 -1
  39. package/dist/core/extract-go-check.js +21 -13
  40. package/dist/core/extract-go.d.ts +1 -0
  41. package/dist/core/extract-go.js +58 -9
  42. package/dist/core/extract-ir.d.ts +1 -0
  43. package/dist/core/extract-ir.js +15 -0
  44. package/dist/core/extract-jvm.d.ts +1 -1
  45. package/dist/core/extract-jvm.js +65 -14
  46. package/dist/core/extract-orm.d.ts +12 -0
  47. package/dist/core/extract-orm.js +244 -0
  48. package/dist/core/extract-print.js +23 -1
  49. package/dist/core/extract-py.d.ts +1 -0
  50. package/dist/core/extract-py.js +4 -4
  51. package/dist/core/extract-rb.js +3 -3
  52. package/dist/core/extract-read.d.ts +25 -0
  53. package/dist/core/extract-read.js +60 -5
  54. package/dist/core/extract-rs.js +22 -20
  55. package/dist/core/extract-shapes.js +22 -0
  56. package/dist/core/extract-sol.d.ts +10 -1
  57. package/dist/core/extract-sol.js +89 -30
  58. package/dist/core/extract-step.d.ts +201 -4
  59. package/dist/core/extract-step.js +1514 -111
  60. package/dist/core/extract-swift.js +24 -13
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +88 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/fresh.d.ts +2 -2
  66. package/dist/core/fresh.js +7 -3
  67. package/dist/core/go/reader.go +7 -1
  68. package/dist/core/infer.d.ts +4 -1
  69. package/dist/core/infer.js +1020 -246
  70. package/dist/core/jvm/JavaReader.java +33 -8
  71. package/dist/core/jvm/Jvm.java +20 -1
  72. package/dist/core/jvm/KtReader.java +59 -6
  73. package/dist/core/laws.d.ts +10 -3
  74. package/dist/core/laws.js +193 -14
  75. package/dist/core/machine.d.ts +16 -3
  76. package/dist/core/machine.js +212 -28
  77. package/dist/core/nonterm.js +14 -1
  78. package/dist/core/orm/harness.js +61 -0
  79. package/dist/core/orm-fixtures/schema.prisma +5 -0
  80. package/dist/core/py/harness.py +260 -21
  81. package/dist/core/py/reader.py +278 -39
  82. package/dist/core/rb/reader.rb +52 -5
  83. package/dist/core/reader-fixtures/README.md +28 -0
  84. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  85. package/dist/core/reader-fixtures/go-685506.go +14 -0
  86. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  87. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  88. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  89. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  90. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  91. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  92. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  93. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  94. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  95. package/dist/core/relation.d.ts +1 -1
  96. package/dist/core/relation.js +29 -2
  97. package/dist/core/relational.js +4 -2
  98. package/dist/core/rs/src/main.rs +18 -2
  99. package/dist/core/sample-cache.d.ts +8 -0
  100. package/dist/core/sample-cache.js +46 -0
  101. package/dist/core/security.d.ts +38 -0
  102. package/dist/core/security.js +88 -0
  103. package/dist/core/sol/harness.py +63 -7
  104. package/dist/core/sol-concrete.d.ts +23 -0
  105. package/dist/core/sol-concrete.js +195 -0
  106. package/dist/core/solver.js +8 -5
  107. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  108. package/dist/core/system.d.ts +62 -1
  109. package/dist/core/system.js +263 -4
  110. package/dist/core/transfer.js +39 -9
  111. package/dist/core/translate.js +39 -10
  112. package/dist/core/watch.js +51 -6
  113. package/dist/interchange/check.js +10 -10
  114. package/dist/interchange/format.d.ts +4 -0
  115. package/dist/interchange/format.js +24 -6
  116. package/dist/kernel/cdcl.d.ts +5 -0
  117. package/dist/kernel/cdcl.js +88 -10
  118. package/dist/kernel/epr.js +141 -29
  119. package/dist/kernel/kernel.d.ts +31 -1
  120. package/dist/kernel/kernel.js +391 -101
  121. package/dist/kernel/model-sequence.d.ts +3 -0
  122. package/dist/kernel/model-sequence.js +34 -0
  123. package/dist/kernel/prove.d.ts +30 -1
  124. package/dist/kernel/prove.js +481 -71
  125. package/dist/kernel/reader.d.ts +3 -0
  126. package/dist/kernel/reader.js +101 -14
  127. package/dist/kernel/share.d.ts +1 -0
  128. package/dist/kernel/share.js +27 -0
  129. package/dist/lean-kernel/emit.d.ts +9 -3
  130. package/dist/lean-kernel/emit.js +200 -66
  131. package/dist/lean-kernel/lean-terms.js +5 -0
  132. package/dist/lean-kernel/library.js +10 -10
  133. package/package.json +7 -2
@@ -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
+ }
@@ -16,9 +16,10 @@ export const env = globalThis.process?.env ?? {};
16
16
  export const v = (name) => ({ [name]: 1 });
17
17
  export const k = (value) => (value === 0 ? {} : { 1: value });
18
18
  // (Plain loops, no intermediate arrays: these run millions of times in a proof. Each keeps the keys in the order they
19
- // first appear, as a sum over the entries would.)
19
+ // first appear, as a sum over the entries would. Each builds on an object with no prototype, so a variable
20
+ // named __proto__ is a key like any other and one named constructor or toString reads 0 until set.)
20
21
  export function add(...xs) {
21
- const out = {};
22
+ const out = Object.create(null);
22
23
  for (const x of xs)
23
24
  for (const key in x)
24
25
  out[key] = (out[key] ?? 0) + x[key];
@@ -28,7 +29,7 @@ export function add(...xs) {
28
29
  return out;
29
30
  }
30
31
  export const scale = (x, f) => {
31
- const out = {};
32
+ const out = Object.create(null);
32
33
  for (const key in x) {
33
34
  const value = x[key] * f;
34
35
  if (value !== 0)
@@ -37,7 +38,7 @@ export const scale = (x, f) => {
37
38
  return out;
38
39
  };
39
40
  export const sub = (a, b) => {
40
- const out = {};
41
+ const out = Object.create(null);
41
42
  for (const key in a)
42
43
  out[key] = a[key];
43
44
  for (const key in b)
@@ -89,7 +90,9 @@ export const linOfE = (e) => {
89
90
  case 'min':
90
91
  case 'max':
91
92
  case 'if':
92
- case 'get': return undefined;
93
+ case 'get':
94
+ case 'tup':
95
+ case 'proj': return undefined;
93
96
  }
94
97
  };
95
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) {
@@ -1,4 +1,5 @@
1
- import { type Machine } from './machine.js';
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type StepLaw } from '../kernel/kernel.js';
2
3
  import { type Kind, type Rule } from './dsl.js';
3
4
  export type Model = {
4
5
  name: string;
@@ -21,6 +22,7 @@ export declare function asRule(m: Machine, kinds?: Record<string, Kind<unknown>>
21
22
  export type Level = 'atomic' | 'read committed' | 'snapshot';
22
23
  export declare const ISOLATION: Record<Level, Model>;
23
24
  export declare function isolation(m: Machine, level: Level): Machine;
25
+ export declare const readsOf: WeakMap<Machine, string[]>;
24
26
  export type Delivery = 'exactly-once' | 'at-least-once';
25
27
  export declare const DELIVERY: Record<Delivery, Model>;
26
28
  export declare function delivery(m: Machine, pool: string, fields: string[], mode: Delivery, opts?: {
@@ -42,3 +44,62 @@ export declare function expires(cells: Record<string, number>, at: string, opts?
42
44
  key?: string;
43
45
  now?: string;
44
46
  }): Machine;
47
+ export type Env = {
48
+ isolation?: Level;
49
+ expiry?: boolean;
50
+ retries?: boolean;
51
+ flow?: string[];
52
+ apart?: boolean;
53
+ };
54
+ export declare function envOf(text: string | string[]): Env;
55
+ export declare const envText: (e: Env) => string;
56
+ export type InEnv = {
57
+ rule: Rule;
58
+ models: Model[];
59
+ reads: string[];
60
+ part: string;
61
+ act: string;
62
+ id?: string;
63
+ commit?: number;
64
+ level: Level;
65
+ flow?: string[];
66
+ method?: string;
67
+ methods?: number;
68
+ law: (l: Law) => Law;
69
+ step: (s: StepLaw) => StepLaw;
70
+ between: (name: string, a: string, b: string) => Law;
71
+ };
72
+ export type EnvOpts = {
73
+ stores?: string[][];
74
+ own?: string[];
75
+ method?: {
76
+ name: string;
77
+ values: string[];
78
+ };
79
+ failed?: string;
80
+ args?: {
81
+ method: string;
82
+ code: string;
83
+ rule: string;
84
+ }[];
85
+ oks?: {
86
+ method: string;
87
+ rule: string;
88
+ }[];
89
+ };
90
+ export declare function inEnv(r: Rule | Machine, env: Env, o?: EnvOpts): InEnv;
91
+ export declare function shrinkRun<T extends {
92
+ params: Record<string, number>;
93
+ trace: Record<string, unknown>[];
94
+ }>(r: Rule | Machine, w: Law | StepLaw, run: T): T;
95
+ export declare function contend(e: InEnv, w: Law | StepLaw, opts?: {
96
+ bases?: number;
97
+ depth?: number;
98
+ bound?: number;
99
+ seed?: number;
100
+ ms?: number;
101
+ calls?: number;
102
+ }): {
103
+ params: Record<string, number>;
104
+ trace: Record<string, unknown>[];
105
+ } | undefined;