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,14 @@
1
+ package p
2
+
3
+
4
+ import "sync"
5
+ type C struct {
6
+ mu sync.Mutex
7
+ N int64
8
+ }
9
+ func (c *C) get() int64 { c.mu.Lock(); defer c.mu.Unlock(); return c.N }
10
+ func (c *C) Inc() {
11
+ c.mu.Lock()
12
+ return c.mu.Unlock()
13
+ c.N = c.get() + 1
14
+ }
@@ -0,0 +1,8 @@
1
+ package demo
2
+
3
+ data class Budget(val limit: Int, val spent: Int = 0) {
4
+ init { limit.takeIf { it >= 0 }.let { requireNotNull(it) { "limit" } } }
5
+ fun spend(n: Int): Budget = if (n < 0 || spent + n > limit) else copy(spent = spent + n)
6
+ fun reset(): Budget = copy(spent = 0)
7
+ fun left(): Int = limit - spent
8
+ }
@@ -0,0 +1,7 @@
1
+ package demo
2
+
3
+ data class Budget(val limit: Int, val spent: Int = 0) {
4
+ init { limit.takeIf { it >= 1 }.let { requireNotNull(it) { "limit" } } }
5
+ fun spend(n: Int): Budget = if (n <(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( 0 || spent + n > limit) this else copy(spent = spent + n)
6
+ fun left(): Int = limit - spent
7
+ }
@@ -0,0 +1,3 @@
1
+ package demo
2
+ class C { var x = 0
3
+ fun(xs: List<Int>) { for (v in xs) x += v } }
@@ -0,0 +1,15 @@
1
+ // An actor: each method one step (it has no suspension point), a guard, an Int's trap.
2
+ actor Tally {
3
+ private var n = 0
4
+ let cap: Int
5
+
6
+ init(cap: Int) { self.cap = cap }
7
+
8
+ func add(_ k: Int) -> Bool {
9
+ guard k > 0, n + k <= cap else {[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ return false }
10
+ n += k
11
+ return true
12
+ }
13
+
14
+ func reset() { n = 0 }
15
+ }
@@ -0,0 +1,15 @@
1
+ // An actor: each method one step (it has no suspension point), a guard, an Int's trap.
2
+ actor Tally {
3
+ private var n = 0
4
+ let cap: Int
5
+
6
+ init(cap: Int) { self.cap = cap }
7
+
8
+ func add(_ k: Int) -> Bool {
9
+ guard k > 0, n + k <= cap el[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[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[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[se { return false }
10
+ n += k
11
+ return true
12
+ }
13
+
14
+ func reset() { n = 0 }
15
+ }
@@ -0,0 +1,4 @@
1
+ final class Meter {
2
+ var n =[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ (((0)))
3
+ func tick() { n = n &+ 1 }
4
+ }
@@ -0,0 +1,15 @@
1
+ // PREDICTION: refused; LAW: r.law('n stays zero', ({n}) => n.eq(0))
2
+ protocol Store {
3
+ func get(_ key: String) -> Int?
4
+ func set(_ key: String, value: Int)
5
+ }
6
+ final class Meter {
7
+ let a: Store
8
+ let b: Store[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
9
+ var n = 0
10
+ init(a: Store, b: Store) { self.a = a; self.b = b }
11
+ func tick() {
12
+ a.set("k", value: 1)
13
+ n = b.get("k") ?? 0
14
+ }
15
+ }
@@ -0,0 +1,31 @@
1
+ // The boundary inferred: two injected protocols (a counter called by a key, held as a store; a flag source whose
2
+ // limit() is answered by the request over its declared Int), the entry inferred, a dictionary keyed by a String in the
3
+ // state.
4
+ protocol Counter {
5
+ func get(_ key: String) -> Int?
6
+ func set(_ key: String, value: Int)
7
+ }
8
+ protocol Flags {
9
+ func limit() -> Int
10
+ }
11
+
12
+ final class Limiter {
13
+ private let counter: Counter
14
+ private let flags: Flags
15
+ private var denied: [String: Int] = [:]
16
+
17
+ init(counter: Counter, flags: Flags) {
18
+ self.counter = counter
19
+ self.flags = flags
20
+ }
21
+
22
+ func allow(_ user: String) -> Bool {
23
+ let used = counter.get("hits:\(user)") ?? 0
24
+ guard used < flags.limit() e[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[lse {
25
+ denied[user, default: 0] += 1
26
+ return false
27
+ }
28
+ counter.set("hits:\(user)", value: used + 1)
29
+ return true
30
+ }
31
+ }
@@ -0,0 +1,2 @@
1
+ const Mixin = (b: any) => class extends b {}
2
+ export class C extends extends(Object) { n = 0; go(): void { this.n++ } }
@@ -1,4 +1,4 @@
1
- import type { Law } from './machine.js';
1
+ import { type Law } from './machine.js';
2
2
  import type { Loop } from '../kernel/kernel.js';
3
3
  import { type Lin } from './solver.js';
4
4
  export type Path = {
@@ -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")) }
@@ -61,6 +67,10 @@ impl Reader {
61
67
  }
62
68
  fn load_file(root: &Path, rel: &Path, module: &str, out: &mut Vec<File>) -> Result<(), String> {
63
69
  let src = std::fs::read_to_string(root.join(rel)).map_err(|e| format!("{}: {e}", rel.display()))?;
70
+ // (syn's parser and the lowering recurse on each level of nesting: past MAX_DEPTH brackets the source is refused, said
71
+ // so as core/extract-read.ts's statedRefusal reads it, before any recursion could pass the reader's stack)
72
+ let deep = src.chars().fold((0i64, 0i64), |(d, m), c| match c { '(' | '[' | '{' => (d + 1, m.max(d + 1)), ')' | ']' | '}' => (d - 1, m), _ => (d, m) }).1;
73
+ if deep > MAX_DEPTH { eprintln!("gdp: refused: {}: the source nests {deep} brackets deep (past {MAX_DEPTH})", rel.display()); std::process::exit(3) }
64
74
  let f = syn::parse_file(&src).map_err(|e| format!("{}: {e}", rel.display()))?;
65
75
  let dir: PathBuf = if rel.file_name().map(|n| n == "lib.rs" || n == "main.rs" || n == "mod.rs").unwrap_or(false) { rel.parent().unwrap().to_path_buf() } else { rel.with_extension("") };
66
76
  let mut items = vec![];
@@ -169,7 +179,7 @@ impl Reader {
169
179
  let mut fields = vec![];
170
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)})) } }
171
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();
172
- let generic = !s.generics.params.is_empty();
182
+ let generic = has_type_or_const_params(&s.generics);
173
183
  let mut kinds = vec![json!("value")];
174
184
  if derives.iter().any(|d| d == "Default") { kinds.push(json!("default")) }
175
185
  if generic { kinds.push(json!(format!("generic:{}", text(&s.generics)))) }
@@ -208,7 +218,7 @@ impl Reader {
208
218
  let (mut body, tail) = self.block(block);
209
219
  if !tail.is_null() && tail["e"] != "none" { body.push(json!({"s": "ret", "p": self.at(block.span()), "x": tail})) }
210
220
  let ret = match &sig.output { ReturnType::Default => json!({"k": "none"}), ReturnType::Type(_, t) => self.ty(t) };
211
- let generic = !sig.generics.params.is_empty();
221
+ let generic = has_type_or_const_params(&sig.generics);
212
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();
213
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],
214
224
  "params": params, "ret": ret, "body": body, "async": sig.asyncness.is_some(), "static": is_static, "recv": recv, "decorators": decs, "generic": generic});
@@ -654,7 +664,13 @@ fn assigns(e: &Expr, n: &str) -> bool {
654
664
  false
655
665
  }
656
666
 
667
+ const MAX_DEPTH: i64 = 1000;
668
+ // The reader on a thread of 1 GiB of stack (reserved, not used): MAX_DEPTH levels of syn's recursion fit in it.
657
669
  fn main() {
670
+ let t = std::thread::Builder::new().stack_size(1 << 30).spawn(run).expect("a thread");
671
+ if t.join().is_err() { std::process::exit(101) }
672
+ }
673
+ fn run() {
658
674
  let req: Value = serde_json::from_str(&std::env::args().nth(1).expect("a request")).expect("JSON");
659
675
  let root = PathBuf::from(req["root"].as_str().unwrap());
660
676
  let files = match Reader::load(&root) { Ok(f) => f, Err(e) => { println!("{}", json!({"error": e})); return } };
@@ -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
 
@@ -233,7 +279,7 @@ def send(frm, to, data, value, deploy=False):
233
279
  r = rpc('eth_getTransactionReceipt', [h])
234
280
  if r is not None: break
235
281
  time.sleep(0.002 * (i + 1))
236
- if r is None: return None, 'no receipt'
282
+ if r is None: raise TimeoutError('no receipt for a transaction anvil was sent')
237
283
  if int(r['status'], 16) != 1: return None, 'reverted'
238
284
  return r, None
239
285
 
@@ -475,9 +521,9 @@ def main():
475
521
  if sys.argv[1] == '--replay':
476
522
  req = json.load(open(sys.argv[2]))
477
523
  try: res = replay(req)
478
- except Exception as e: res = {'error': f'{type(e).__name__}: {e}'[:500]}
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')
@@ -489,20 +535,30 @@ def main():
489
535
  if op == 'hello': res = hello(req)
490
536
  elif op == 'new':
491
537
  try: res = {'id': make(req['a'])}
538
+ except OSError: raise
492
539
  except Exception as e: res = {'err': f'{type(e).__name__}: {e}'[:300]}
493
540
  elif op == 'at':
494
541
  try: res = {'id': at(req['a'], req['state'])}
542
+ except OSError: raise
495
543
  except Exception as e: res = {'bad': f'{type(e).__name__}: {e}'[:300]}
496
544
  elif op == 'get': res = {'state': state_of(req['id'])}
497
545
  elif op == 'call': res = call(req)
498
546
  elif op == 'coverage': res = {'hit': []}
499
547
  else: res = {'error': f'no op {op}'}
500
548
  except Exception as e:
501
- res = {'error': f'{type(e).__name__}: {e}'[:500]}
549
+ # (anvil's transport failing, a request past its time: the check's failure, never the code's)
550
+ res = {'error': f'{type(e).__name__}: {e}'[:500], **({'transport': True} if isinstance(e, OSError) else {})}
502
551
  fout.write(json.dumps(res) + '\n'); fout.flush()
503
552
  finally:
504
- 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)
505
560
 
506
561
 
507
562
  if __name__ == '__main__':
563
+ for n in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): signal.signal(n, on_signal)
508
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 {};