gdp-wired 0.35.0 → 0.37.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.
@@ -40,6 +40,7 @@
40
40
  import * as dsl from "./dsl.js";
41
41
  import { compileFunction, walk } from "./machine.js";
42
42
  import * as I from "./extract-ir.js";
43
+ import { PASS } from "./extract-ir.js";
43
44
  import { Refusal, placed, sourceOf } from "./extract-read.js";
44
45
  import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice } from "./extract-shapes.js";
45
46
  import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pnum, pterm, sortsOf } from "./extract-print.js";
@@ -270,13 +271,27 @@ function builderOf(m, sorts) {
270
271
  const vars = new Set(), maps = new Set();
271
272
  for (const x of xs)
272
273
  I.varsOf(x, vars, maps);
273
- return `{${[...new Set([...vars].filter(n => !m.leasts?.some(l => l.key === n)).map(leastOf)), ...maps].join(', ')}}`;
274
+ return `{${[...new Set([...vars].filter(n => !m.leasts?.some(l => l.key === n)).map(leastOf)), ...maps].filter(n => n !== PASS).join(', ')}}`;
274
275
  };
275
276
  // The least keys: each where it holds, by what, read at the state before the step.
276
277
  if (m.leasts?.length) {
277
278
  const c = ctx();
278
279
  lines.push(` .least({${m.leasts.map(l => `${l.name}: (${envOf(l.where, ...l.by.map(b => b.e))}) => ({where: ${l.key} => ${pb(l.where, P, c)}, by: ${l.key} => [${l.by.map(b => (b.desc ? `desc(${pnum(b.e, P, c)})` : pnum(b.e, P, c))).join(', ')}]})`).join(', ')}})`);
279
280
  }
281
+ // The lists a request carries, the folds' running values, and what every request is assumed to carry in them: each
282
+ // fold's start at 0 and its step at every pass below the list's length (printed over the pass, i$).
283
+ const rec = (name, fs) => `record({${fs.map(f => `${f.name}: ${kindOf(f, sorts, `${name}.${f.name}`)}`).join(', ')}})`;
284
+ for (const q of [...(m.seqs ?? []), ...(m.folds ?? []).map(d => ({ name: d.run, fields: d.fields }))])
285
+ lines.push(` .carriesList(${JSON.stringify(q.name)}, ${rec(q.name, q.fields)})`);
286
+ for (const d of m.folds ?? []) {
287
+ const cell = (i, f) => ({ op: 'cell', map: d.run, key: { op: 'num', e: i }, field: f.name, ...(f.sort.k === 'choice' ? { values: f.sort.values } : {}) });
288
+ const eq = (i, f, t) => (t.s === 'num' ? I.cmp('=', cell(i, f), t.e) : t.s === 'bool' ? I.and(I.or(I.not(cell(i, f)), t.e), I.or(cell(i, f), I.not(t.e))) : t.s === 'str' ? I.keq(cell(i, f), t.e) : I.leq(cell(i, f), t.e));
289
+ const start = I.and(...d.fields.map(f => eq(I.num(0), f, d.init[f.name]))), step = I.and(...d.fields.map(f => eq(I.add(I.nvar(PASS), I.num(1)), f, d.step[f.name])));
290
+ // (the passes over the run's places: one past the list's length, a carried list's or one of the state's)
291
+ const len = I.add(d.len, I.num(1)), text = `all(${d.run}_len.eq(${pnum(len, P, ctx())}), ${pb(start, P, ctx())}, ${d.run}.every((_x, ${PASS}) => ${PASS}.lt(${pnum(d.len, P, ctx())}).implies(${pb(step, P, ctx())})))`;
292
+ const env = envOf(start, step, d.len).slice(1, -1).split(', ').filter(Boolean);
293
+ lines.push(` .assume((${withChoices(`{${[...new Set([...env, d.run, `${d.run}_len`])].join(', ')}}`, text, P)}) => ${text})`);
294
+ }
280
295
  if (!(m.pre.op === 'const' && m.pre.v))
281
296
  lines.push(` .pre((${envOf(m.pre)}) => ${pb(m.pre, P, ctx())})`);
282
297
  const allowed = I.not(m.refuse);
@@ -330,7 +345,7 @@ const isBool = (x, m) => {
330
345
  if (o.op === 'var' && m)
331
346
  return [...m.params, ...m.inputs, ...m.state].some(v => v.name === o.name && v.sort.k === 'bool') || !!m.leasts?.some(l => l.some === o.name);
332
347
  if (o.op === 'cell' && m)
333
- return o.field === 'has' || !!m.maps.find(d => d.name === o.map)?.fields.some(f => f.name === o.field && f.sort.k === 'bool');
348
+ return o.field === 'has' || [...m.maps, ...(m.seqs ?? []), ...(m.folds ?? []).map(d => ({ name: d.run, fields: d.fields }))].some(d => d.name === o.map && d.fields.some(f => f.name === o.field && f.sort.k === 'bool'));
334
349
  return false;
335
350
  };
336
351
  // The env's names: those the terms read, the choices a literal is printed through, and the maps written.
@@ -15,6 +15,7 @@ export type InferOptions = {
15
15
  minimize?: boolean;
16
16
  remainders?: boolean;
17
17
  join?: number;
18
+ cubes?: number;
18
19
  };
19
20
  export type Found = {
20
21
  law: Law;
@@ -760,7 +760,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
760
760
  return verdictOf(out);
761
761
  };
762
762
  const stats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(performance.now() - t0), stopped: stop() });
763
- const first = opts.first ?? prove(laws);
763
+ const first = opts.first ?? (opts.cubes ? { proven: false, checked: false } : prove(laws));
764
764
  if ((first.proven && first.checked) || first.run)
765
765
  return { ...first, found: [], stats: stats(0, 0, 0) };
766
766
  // --- runs ------------------------------------------------------------------------------------------------------------
@@ -1018,7 +1018,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1018
1018
  // guard in one pass over (at most 1,500 of) the rows. Building candidates takes at most a quarter of the time.
1019
1019
  const guards = [...modes].sort((p, q) => Number(!!q.choice) - Number(!!p.choice) || Number(!!q.bool) - Number(!!p.bool)).slice(0, 8);
1020
1020
  const strideS = Math.max(1, Math.ceil(NS / 1500)), strideK = Math.max(1, Math.ceil(NK / 1500));
1021
- const buildUntil = Math.min(until, now() + (until - now()) / 4);
1021
+ const buildUntil = opts.cubes ? 0 : Math.min(until, now() + (until - now()) / 4);
1022
1022
  for (const [n_, { coef, cells }] of shapes.entries()) {
1023
1023
  if (forms.length > maxCandidates || (n_ % 256 === 0 && (now() > buildUntil || stop())))
1024
1024
  break;
@@ -1436,7 +1436,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1436
1436
  return false;
1437
1437
  }
1438
1438
  };
1439
- const houdiniUntil = Math.min(until, now() + Math.max(500, (until - now()) / 4));
1439
+ const houdiniUntil = opts.cubes ? 0 : Math.min(until, now() + Math.max(500, (until - now()) / 4));
1440
1440
  for (let quiet = 0; samples.length && now() < houdiniUntil && !stop() && quiet < 3;) {
1441
1441
  const killed = new Set();
1442
1442
  for (let tries = 0; tries < 400 && now() < houdiniUntil && !stop(); tries++) {
@@ -2173,7 +2173,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2173
2173
  // (a step law's goal: its step from a state the set allows)
2174
2174
  const stepLawOf = new Map(stepLaws.map(sl => [sl.name, sl]));
2175
2175
  // (the engine runs after a join that finds nothing, on a rule whose scalars the runs held at few values: below)
2176
- let follows;
2176
+ let follows, cubesOut;
2177
2177
  const engineFollows = () => (follows ??= !!sorts && callerLaws.some(l => l.keys?.length) && atoms.every((a, i) => a.cell || a.param || !!a.term || a.view !== undefined || i >= valsS.length || new Set(valsS[i]).size <= 4));
2178
2178
  const stepWith = (name, form, ctx) => {
2179
2179
  const ctxLaws = [...ctx, ...(form ? [form] : [])].map(lawFor), ls = [...given, ...ctxLaws], mm = forLaws(ctxLaws).m, sl = form ? undefined : stepLawOf.get(name);
@@ -2728,10 +2728,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2728
2728
  // few others that keep its facts on the sort's keys (its values reversed, and each turned by one), each run as its
2729
2729
  // own machine; their states' rows read under their table. One table alone is a fact of it, not of the rule: ring's
2730
2730
  // ids, every node past another one's below it)
2731
- const tables = [{ m, run, js: m.history ? undefined : loadJs(m), fns: {} }];
2731
+ const tables = [{ m, run, js: m.history || m.counts ? undefined : loadJs(m), fns: {} }];
2732
2732
  for (const [f, fn] of Object.entries(m.fns ?? {})) {
2733
2733
  const arg = ks.find(`F:${f}`);
2734
- if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history)
2734
+ if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history || m.counts)
2735
2735
  continue;
2736
2736
  const dom = keyDom(arg), vals = dom.map(k => { try {
2737
2737
  return fnValue(fn, k);
@@ -3170,6 +3170,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3170
3170
  const near = (f) => (f.cube.some(l => atomsIn(formOf([l])).some(i => callerMaps.has(atoms[i].parts[0][0].split(AT)[2] ?? ''))) ? 0 : 1);
3171
3171
  // (the rounds over the data-filtered pool cut to its minimal cubes)
3172
3172
  const minPool = env.GDP_POOL !== '0' ? minimal(enumerated()) : { kept: enumerated(), by: new Map() }, made = minPool.kept;
3173
+ if (opts.cubes) {
3174
+ cubesOut = made;
3175
+ return;
3176
+ }
3173
3177
  const tEngine = vnow();
3174
3178
  let cubes = [];
3175
3179
  // (in turn by the maps a cube reads, those reading the caller's first: one of each kind before a second of any; in
@@ -4081,6 +4085,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4081
4085
  });
4082
4086
  }
4083
4087
  };
4088
+ // (the cubes alone: the engine's enumeration on the small instance and the data filter, then out)
4089
+ if (opts.cubes) {
4090
+ engine();
4091
+ return { ...first, proven: false, found: (cubesOut ?? []).filter(f => f.cube.length <= opts.cubes).map(f => ({ law: lawFor(f), text: textOf(f) })), stats: stats(0, 0, 0) };
4092
+ }
4084
4093
  for (;;) {
4085
4094
  if (now() > jUntil || stop()) {
4086
4095
  why = 'time';
@@ -177,6 +177,10 @@ export type SomeProof = {
177
177
  body: C;
178
178
  sub?: Record<string, E>;
179
179
  ghost?: true;
180
+ map?: {
181
+ name: string;
182
+ at: E;
183
+ };
180
184
  };
181
185
  export { unreachable } from '../kernel/kernel.js';
182
186
  export declare const x: (name: string) => E;
@@ -40,7 +40,7 @@ def resolve(q):
40
40
  class FakeStore:
41
41
  """A store as the caller stated it: get, set and delete over a dict that keeps what is set (no expiry)."""
42
42
  def __init__(self, decl, name=None):
43
- self.data = {}
43
+ self.data, self.name = {}, name
44
44
  for path, v in (decl.get('attrs') or {}).items():
45
45
  o, parts = self, path.split('.')
46
46
  for p in parts[:-1]:
@@ -54,7 +54,12 @@ class FakeStore:
54
54
  key = k.get('key', a[0] if a else None); val = k.get('value', a[1] if len(a) > 1 else None)
55
55
  self.data[key] = val
56
56
  def delete(*a, **k): self.data.pop(k.get('key', a[0] if a else None), None)
57
- f = {'get': get, 'set': set_, 'delete': delete}[kind]
57
+ f0, key = {'get': get, 'set': set_, 'delete': delete}[kind], f"{self.name}.{name}"
58
+ # (where the request says the operation raises, inside a try that catches it)
59
+ def f(*a, **k):
60
+ r = (CUR.get(key) or {}).get('raise')
61
+ if r is not None: raise raised(r)
62
+ return f0(*a, **k)
58
63
  if asyncs.get(name):
59
64
  async def af(*a, **k): return f(*a, **k)
60
65
  return af
@@ -67,7 +72,7 @@ class FakeStore:
67
72
  setattr(self, m, (lambda *a, **k: anop()) if asyncs.get(m) else (lambda *a, **k: None))
68
73
  # (an injected dependency's other methods: each answered by the request's input)
69
74
  for a in S.get('answers') or []:
70
- if a['patch'].get('store') == name: setattr(self, a['patch']['path'][-1], stub(a['key'], a['async']))
75
+ if a['patch'].get('store') == name and not a.get('pass'): setattr(self, a['patch']['path'][-1], stub(a['key'], a['async']))
71
76
 
72
77
  def build(spec, stores):
73
78
  if 'in' in spec:
@@ -76,6 +81,7 @@ def build(spec, stores):
76
81
  if spec.get('none'): return None
77
82
  if spec.get('inert'): return Inert()
78
83
  if 'store' in spec: return stores.setdefault(spec['store'], FakeStore(S['stores'].get(spec['store'], {}), spec['store']))
84
+ if 'list' in spec: return [build(x, stores) for x in spec['list']]
79
85
  if 'rec' in spec:
80
86
  cls = resolve(spec['rec'])
81
87
  f = {k: build(v, stores) for k, v in spec['f'].items()}
@@ -217,15 +223,27 @@ class Clock:
217
223
  def perf_counter(self): return float(NOW[0])
218
224
  def __getattr__(self, n): return getattr(self.real, n)
219
225
 
220
- def stub(key, is_async):
221
- def value():
226
+ def raised(r):
227
+ """The exception a stub raises where the request says: the class a handler names, made without its arguments."""
228
+ cls = eval(r[1], vars(importlib.import_module(r[0])))
229
+ try: return cls('gdp: raised where the request says')
230
+ except Exception:
231
+ e = cls.__new__(cls); e.args = ('gdp: raised where the request says',); return e
232
+
233
+ def stub(key, is_async, orig=None):
234
+ # (orig: a call left out, run as it is unless the request says it raises)
235
+ def value(a_, k_):
222
236
  a = CUR.get(key)
237
+ if a is not None and a.get('raise') is not None: raise raised(a['raise'])
238
+ if orig is not None: return orig(*a_, **k_)
223
239
  if a is None or a.get('none'): return None
224
240
  return build(a, {})
225
241
  if is_async:
226
- async def f(*a, **k): return value()
242
+ async def f(*a, **k):
243
+ v = value(a, k)
244
+ return (await v) if orig is not None and inspect.isawaitable(v) else v
227
245
  return f
228
- def g(*a, **k): return value()
246
+ def g(*a, **k): return value(a, k)
229
247
  return g
230
248
 
231
249
  def patch_target(p):
@@ -245,11 +263,11 @@ def hello(req):
245
263
  for a in req['answers']:
246
264
  p = a['patch']
247
265
  if p.get('store'): continue
248
- if p.get('self'): S['self_stubs'].append((p['self'], stub(a['key'], a['async'])))
266
+ if p.get('self'): S['self_stubs'].append((p['self'], a))
249
267
  else:
250
268
  o, name = patch_target(p)
251
269
  raw = inspect.getattr_static(o, name, None)
252
- f = stub(a['key'], a['async'])
270
+ f = stub(a['key'], a['async'], getattr(o, name) if a.get('pass') else None)
253
271
  setattr(o, name, staticmethod(f) if isinstance(raw, staticmethod) else classmethod(lambda cls, *x, **k: f(*x, **k)) if isinstance(raw, classmethod) else f)
254
272
  S['cls'] = getattr(mod, req['cls'].rpartition('.')[2]) if req.get('cls') else None
255
273
  S['loop'] = asyncio.new_event_loop()
@@ -265,7 +283,7 @@ def make(args):
265
283
  sys.settrace(tracer)
266
284
  try: obj = run(S['cls'](**kw))
267
285
  finally: sys.settrace(None)
268
- for name, f in S['self_stubs']: obj.__dict__[name] = f
286
+ for name, a in S['self_stubs']: obj.__dict__[name] = stub(a['key'], a['async'], getattr(obj, name) if a.get('pass') else None)
269
287
  for name in S.get('inject') or []: setattr(obj, name, build({'store': name}, OBJ_STORES))
270
288
  i = len(OBJS) + 1
271
289
  OBJS[i] = (obj, OBJ_STORES)
@@ -5,7 +5,7 @@
5
5
  # arguments carry are read from the repository's own modules (their class annotations, never run).
6
6
  #
7
7
  # python3 -I core/py/reader.py '{"root": <repo>, "file": <file>, "names": [<classes or functions>]}'
8
- import ast, json, os, sys
8
+ import ast, builtins, json, os, sys
9
9
 
10
10
  BUILTINS = {'min', 'max', 'abs', 'len', 'int', 'float', 'bool', 'str', 'isinstance', 'round', 'sum', 'any', 'all', 'print', 'repr', 'getattr', 'setattr', 'hasattr', 'type', 'list', 'dict', 'set', 'tuple', 'sorted', 'range', 'zip', 'enumerate'}
11
11
  # Library functions the executor knows (their meaning, not their code).
@@ -96,6 +96,7 @@ class Reader:
96
96
  self.file = os.path.abspath(file)
97
97
  self.recs, self.funcs = {}, {}
98
98
  self.local_stack = []
99
+ self.caught = [] # (the names the handlers being read bind their exceptions to)
99
100
 
100
101
  # --- types -------------------------------------------------------------------------------------------------------
101
102
  def find_class(self, mod, name, depth=0):
@@ -301,7 +302,12 @@ class Reader:
301
302
  return [{'s': 'if', 'p': p, 'c': E(s.test), 'then': self.block(s.body, mod), 'else': self.block(s.orelse, mod)}]
302
303
  if isinstance(s, ast.Return): return [{'s': 'ret', 'p': p, **({'x': E(s.value)} if s.value is not None else {})}]
303
304
  if isinstance(s, ast.Raise):
304
- return [{'s': 'fail', 'p': p, 'why': f"raise {text(s.exc) if s.exc else ''}".strip(), **({'x': E(s.exc)} if s.exc else {})}]
305
+ # (the class raised and its bases; a bare raise, or of the exception a handler caught, a re-raise)
306
+ x = s.exc.func if isinstance(s.exc, ast.Call) else s.exc
307
+ re = x is None or (isinstance(x, ast.Name) and x.id in self.caught)
308
+ cls = None if re else self.exc_class(x, mod)
309
+ return [{'s': 'fail', 'p': p, 'why': f"raise {text(s.exc) if s.exc else ''}".strip(), **({'x': E(s.exc)} if s.exc else {}), **({'reraise': True} if re else {}),
310
+ **({'cls': cls[0], **({'open': True} if cls[1] else {})} if cls else {})}]
305
311
  if isinstance(s, ast.Assert):
306
312
  return [{'s': 'if', 'p': p, 'c': E(s.test), 'then': [], 'else': [{'s': 'fail', 'p': p, 'why': f"assert {text(s.test)}"}]}]
307
313
  if isinstance(s, (ast.With, ast.AsyncWith)):
@@ -318,12 +324,50 @@ class Reader:
318
324
  ret = self.ret_of(m, a.name)
319
325
  names[a.asname or a.name] = {'mod': m, 'name': a.name, **({'ret': ret} if ret else {})}
320
326
  return [{'s': 'import', 'p': p, 'names': names}]
321
- if isinstance(s, (ast.For, ast.AsyncFor, ast.While)): return [{'s': 'no', 'p': p, 'why': f"a loop ({type(s).__name__.lower().replace('async', 'async ')})"}]
322
- if isinstance(s, ast.Try) or type(s).__name__ == 'TryStar': return [{'s': 'no', 'p': p, 'why': 'try/except (an exception caught: the subset reads one only as the step\'s failure)'}]
327
+ # (a loop over a collection: a fold, where it is over a list the request carries; a while loop isn't one)
328
+ if isinstance(s, ast.For): return [{'s': 'for', 'p': p, 'to': self.target(s.target, mod), 'over': E(s.iter), 'body': self.block(s.body, mod), 'els': self.block(s.orelse, mod)}]
329
+ if isinstance(s, ast.Continue): return [{'s': 'continue', 'p': p}]
330
+ if isinstance(s, ast.Break): return [{'s': 'break', 'p': p}]
331
+ if isinstance(s, (ast.AsyncFor, ast.While)): return [{'s': 'no', 'p': p, 'why': f"a loop ({type(s).__name__.lower().replace('async', 'async ')})"}]
332
+ if type(s).__name__ == 'TryStar': return [{'s': 'no', 'p': p, 'why': 'try/except* (exception groups)'}]
333
+ if isinstance(s, ast.Try):
334
+ hs = []
335
+ for h in s.handlers:
336
+ ts = [] if h.type is None else h.type.elts if isinstance(h.type, ast.Tuple) else [h.type]
337
+ cs = [self.exc_class(t, mod) for t in ts]
338
+ self.caught.append(h.name)
339
+ try: body = self.block(h.body, mod)
340
+ finally: self.caught.pop()
341
+ hs.append({'p': where(self.file, h), 'names': [c[0][0] for c in cs], **({'any': True} if h.type is None else {'mro': cs[0][0], 'raise': [mod.name, text(ts[0])]}),
342
+ **({'open': True} if cs and cs[0][1] else {}), **({'as': h.name} if h.name else {}), 'body': body})
343
+ return [{'s': 'try', 'p': p, 'body': self.block(s.body, mod), 'handlers': hs, 'els': self.block(s.orelse, mod), 'fin': self.block(s.finalbody, mod)}]
323
344
  if isinstance(s, (ast.Global, ast.Nonlocal)): return [{'s': 'no', 'p': p, 'why': f"{type(s).__name__.lower()} (a variable every call shares)"}]
324
345
  if isinstance(s, ast.Match): return [{'s': 'no', 'p': p, 'why': 'match'}]
325
346
  if isinstance(s, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): return [{'s': 'no', 'p': p, 'why': f"a {'class' if isinstance(s, ast.ClassDef) else 'function'} defined in a function (a closure)"}]
326
347
  return [{'s': 'no', 'p': p, 'why': f"{type(s).__name__} (a statement outside the subset)"}]
348
+ def exc_class(self, x, mod, depth=0):
349
+ """A class an except or a raise names: its qualified name then its bases' ([names], open: some the reader can't know)."""
350
+ d = dotted(x)
351
+ if d is None or depth > 8: return [text(x)], True
352
+ head, *rest = d.split('.')
353
+ if not rest and head not in mod.imports and head not in mod.classes:
354
+ b = getattr(builtins, head, None)
355
+ if isinstance(b, type) and issubclass(b, BaseException): return [f"builtins.{c.__name__}" for c in b.__mro__ if c is not object], False
356
+ hit = self.find_class(mod, head) if not rest else None
357
+ imp = mod.imports.get(head)
358
+ if hit is None and imp:
359
+ q = f"{imp[1]}.{imp[2]}" if imp[0] == 'name' else imp[1]
360
+ q = '.'.join([q, *rest])
361
+ sub = self.repo.path_of(q.rpartition('.')[0])
362
+ hit = self.find_class(Module(self.repo, sub), q.rpartition('.')[2]) if sub else None
363
+ if hit is None: return [q], True
364
+ if hit is None: return [d], True
365
+ cm, cdef = hit
366
+ out, op = [f"{cm.name}.{cdef.name}"], False
367
+ for b in cdef.bases:
368
+ bs, bo = self.exc_class(b, cm, depth + 1)
369
+ out += [n for n in bs if n not in out]; op = op or bo
370
+ return out, op
327
371
  def target(self, t, mod):
328
372
  p = where(self.file, t)
329
373
  if isinstance(t, ast.Name): return {'e': 'var', 'n': t.id, 'p': p}
@@ -405,6 +449,11 @@ class Reader:
405
449
  if isinstance(x, ast.Call):
406
450
  f = E(x.func)
407
451
  if f.get('e') == 'ext' and f.get('q') in KNOWN: f = {'e': 'lib', 'q': f['q'], 'p': f['p']}
452
+ # any, all or sum of one generator: a loop over its collection (a fold), its value the accumulator's
453
+ g = x.args[0] if len(x.args) == 1 and not x.keywords and isinstance(x.args[0], (ast.GeneratorExp, ast.ListComp)) else None
454
+ if g and f.get('e') == 'builtin' and f.get('n') in ('any', 'all', 'sum') and len(g.generators) == 1 and not g.generators[0].is_async:
455
+ c = g.generators[0]
456
+ return {'e': 'fold', 'f': f['n'], 'to': self.target(c.target, mod), 'over': E(c.iter), 'x': E(g.elt), 'ifs': [E(i) for i in c.ifs], 'p': p, 'text': text(x)}
408
457
  args = [E(a) if not isinstance(a, ast.Starred) else {'e': 'no', 'why': f"{text(a)}: *args", 'p': p} for a in x.args]
409
458
  kw = [[k.arg, E(k.value)] if k.arg else ['**', {'e': 'no', 'why': f"**{text(k.value)}", 'p': p}] for k in x.keywords]
410
459
  return {'e': 'call', 'f': f, 'args': args, 'kw': kw, 'p': p, 'text': text(x)}
@@ -450,6 +499,10 @@ def main():
450
499
  for n, f in mod.funcs.items():
451
500
  if n not in r.funcs: r.funcs[n] = r.func(f, mod, None, n)
452
501
  out['recs'] = {k: v for k, v in r.recs.items() if v}
502
+ # The executor's own failures' bases, and the class a stub raises for a handler of every exception.
503
+ out['kinds'] = {n: [f"builtins.{c.__name__}" for c in getattr(builtins, n).__mro__ if c is not object] for n in ('KeyError', 'TypeError', 'AttributeError', 'ZeroDivisionError', 'ValueError')}
504
+ out['exc'] = {'mro': ['builtins.Exception', 'builtins.BaseException'], 'raise': ['builtins', 'Exception']}
505
+ out['lists'] = True
453
506
  out['funcs'] = r.funcs
454
507
  print(json.dumps(out))
455
508
 
@@ -41,7 +41,9 @@ end
41
41
  # An answered call's value: the request's input for it (core/extract-step.ts's answers), None where it says so.
42
42
  CUR = {}
43
43
  def answer(key) = (a = CUR[key]).nil? || a['none'] ? nil : build(a)
44
- def stub(key) = proc { |*_a, **_k| answer(key) }
44
+ # (a call inside a rescue's begin: raises the class the request says; one left out runs as it is unless it raises)
45
+ def raising(key) = (r = CUR[key]&.[]('raise')) && raise(Object.const_get(r), 'gdp: raised where the request says')
46
+ def stub(key) = proc { |*_a, **_k| raising(key); answer(key) }
45
47
  # A store (stated, or an injected dependency inferred): get, set and delete over a Hash that keeps what is set; its
46
48
  # other methods answered.
47
49
  class GdpStore
@@ -51,6 +53,7 @@ class GdpStore
51
53
  {'get' => %w[get], 'set' => %w[set], 'delete' => %w[delete]}.each do |kind, dflt|
52
54
  (decl[kind] || dflt).each do |m|
53
55
  define_singleton_method(m) do |*a, **k|
56
+ raising("#{name}.#{m}")
54
57
  key = k[:key] || a[0]
55
58
  case kind
56
59
  when 'get' then @data[key]
@@ -62,7 +65,7 @@ class GdpStore
62
65
  end
63
66
  # (a method left out: nothing, as the rule takes it; any other is no method of this store, and fails)
64
67
  (decl['skip'] || []).each { |m| define_singleton_method(m) { |*_a, **_k| nil } }
65
- S['answers'].each { |x| define_singleton_method(x['patch']['path'][-1], &stub(x['key'])) if x['patch']['store'] == name }
68
+ S['answers'].each { |x| define_singleton_method(x['patch']['path'][-1], &stub(x['key'])) if x['patch']['store'] == name && !x['pass'] }
66
69
  end
67
70
  end
68
71
  # (each object's stores, by its id; the one being made's in $stores)
@@ -134,7 +137,9 @@ def call_args(m, specs)
134
137
  n = name.to_s
135
138
  if S['clocks'].include?(n) && %i[key keyreq].include?(kind) then kw[name] = GdpStatedClock.new; next end
136
139
  spec = given[n]
137
- next if spec.nil? || spec['dflt'] || spec['inert']
140
+ next if spec.nil? || spec['dflt']
141
+ # (an argument the rule doesn't read: nil where it is required, else its default)
142
+ if spec['inert'] then kind == :req ? pos << nil : kind == :keyreq ? kw[name] = nil : nil; next end
138
143
  if spec['store'] && %i[key keyreq].include?(kind) then kw[name] = build(spec); next end
139
144
  %i[key keyreq].include?(kind) ? kw[name] = build(spec) : pos << build(spec)
140
145
  end
@@ -165,8 +170,8 @@ def hello(req)
165
170
  S['answers'].each do |a|
166
171
  next unless (mod = a['patch']['mod'])
167
172
  c = mod.split('::').reject(&:empty?).reduce(Object) { |o, n| o.const_defined?(n, false) ? o.const_get(n, false) : o.const_set(n, Module.new) }
168
- m, st = a['patch']['path'][-1], stub(a['key'])
169
- c.singleton_class.prepend(Module.new { define_method(m, &st) })
173
+ m, st, key = a['patch']['path'][-1], stub(a['key']), a['key']
174
+ c.singleton_class.prepend(Module.new { a['pass'] ? define_method(m) { |*x, **k, &b| raising(key); super(*x, **k, &b) } : define_method(m, &st) })
170
175
  end
171
176
  {'ok' => true}
172
177
  end
@@ -21,6 +21,7 @@ class Reader
21
21
  @consts = {}
22
22
  Dir.glob(File.join(@root, '**', '*.rb')).each { |f| index_consts(f) rescue nil }
23
23
  @recs, @funcs, @loads = {}, {}, []
24
+ @caught = []
24
25
  end
25
26
 
26
27
  # --- constants of the code: Mod::NAME = literal, from every file under the root -----------------------------------
@@ -269,18 +270,59 @@ class Reader
269
270
  op = s.respond_to?(:binary_operator) ? s.binary_operator : s.operator
270
271
  [{'s' => 'set', 'p' => p, 'to' => t, 'x' => binop(op, t, expr(s.value), s)}, *(tail ? ret.(t) : [])]
271
272
  when Prism::CallNode
272
- if s.name == :raise && !s.receiver then return [{'s' => 'fail', 'p' => p, 'why' => "raise #{text(s.arguments || s)}".sub(/raise raise/, 'raise')}] end
273
+ if s.name == :raise && !s.receiver
274
+ # (the class raised and its bases; a bare raise, or of the exception a rescue bound, a re-raise)
275
+ a0 = s.arguments&.arguments&.first
276
+ a0 = a0.receiver if a0.is_a?(Prism::CallNode) && a0.name == :new && a0.receiver
277
+ return [{'s' => 'fail', 'p' => p, 'why' => 'raise', 'reraise' => true}] if a0.nil? || (a0.is_a?(Prism::LocalVariableReadNode) && @caught.include?(a0.name.to_s))
278
+ k = a0.is_a?(Prism::ConstantReadNode) || a0.is_a?(Prism::ConstantPathNode) ? exc_class(a0.slice) : [['RuntimeError', 'StandardError', 'Exception'], false]
279
+ return [{'s' => 'fail', 'p' => p, 'why' => "raise #{text(s.arguments || s)}".sub(/raise raise/, 'raise'), 'cls' => k[0], **(k[1] ? {'open' => true} : {})}]
280
+ end
273
281
  if s.name == :synchronize && s.block.is_a?(Prism::BlockNode) && s.receiver
274
282
  return [{'s' => 'with', 'p' => p, 'items' => [{'x' => expr(s.receiver)}], 'body' => block(body_of(s.block.body), tail)}]
275
283
  end
276
284
  ret.(expr(s))
277
285
  when Prism::ParenthesesNode then block(body_of(s.body), tail)
278
286
  when Prism::WhileNode, Prism::UntilNode, Prism::ForNode then [{'s' => 'no', 'p' => p, 'why' => 'a loop'}]
279
- when Prism::BeginNode then [{'s' => 'no', 'p' => p, 'why' => 'begin/rescue (an exception caught: the subset reads one only as the step\'s failure)'}]
287
+ when Prism::BeginNode
288
+ # begin/rescue/else/ensure (a method's own rescue too): each rescue with the classes it names (none: StandardError)
289
+ body = block(body_of(s.statements), tail && !s.else_clause)
290
+ return body unless s.rescue_clause || s.else_clause || s.ensure_clause
291
+ hs, rc = [], s.rescue_clause
292
+ while rc
293
+ again = false
294
+ each_node(rc) { |n| again ||= n.is_a?(Prism::RetryNode) }
295
+ return [{'s' => 'no', 'p' => p, 'why' => 'retry (a loop back into begin)'}] if again
296
+ names = rc.exceptions.empty? ? ['StandardError'] : rc.exceptions.map(&:slice)
297
+ ks = names.map { |n| exc_class(n) }
298
+ as = rc.reference.respond_to?(:name) ? rc.reference.name.to_s : nil
299
+ @caught << as
300
+ hb = block(body_of(rc.statements), tail)
301
+ @caught.pop
302
+ hs << {'p' => where(rc), 'names' => ks.map { |k| k[0][0] }, 'mro' => ks[0][0], **(ks[0][1] ? {'open' => true} : {}), 'raise' => names[0], **(as ? {'as' => as} : {}), 'body' => hb}
303
+ rc = rc.respond_to?(:subsequent) ? rc.subsequent : rc.consequent
304
+ end
305
+ [{'s' => 'try', 'p' => p, 'body' => body, 'handlers' => hs, 'els' => s.else_clause ? block(body_of(s.else_clause), tail) : [], 'fin' => s.ensure_clause ? block(body_of(s.ensure_clause.statements), false) : []}]
280
306
  when Prism::DefNode, Prism::ClassNode, Prism::ModuleNode then [{'s' => 'no', 'p' => p, 'why' => 'a definition inside a method'}]
281
307
  else ret.(expr(s))
282
308
  end
283
309
  end
310
+ # A class an exception is: its name and its bases' ([names], open: some the reader can't know), from the file's
311
+ # classes, else Ruby's own.
312
+ def exc_class(name, depth = 0)
313
+ name = name.sub(/\A::/, '')
314
+ @classes ||= classes
315
+ hit = @classes[name] || @classes.find { |k, _| k.end_with?("::#{name}") }&.last
316
+ if hit && depth < 8
317
+ sup = hit[0].superclass
318
+ return [[name], true] unless sup
319
+ b = exc_class(sup.slice, depth + 1)
320
+ return [[name, *b[0]], b[1]]
321
+ end
322
+ k = (Object.const_get(name) rescue nil)
323
+ return [k.ancestors.grep(Class).map(&:name) - %w[Object BasicObject], false] if k.is_a?(Class) && k <= Exception
324
+ [[name], true]
325
+ end
284
326
  def ivar(name, n) = {'e' => 'get', 'x' => {'e' => 'var', 'n' => 'self', 'p' => where(n)}, 'f' => name, 'p' => where(n), 'text' => name}
285
327
  def binop(op, a, b, n)
286
328
  o = {:+ => '+', :- => '-', :* => '*', :/ => '//', :% => '%'}[op.to_sym]
@@ -372,4 +414,9 @@ end
372
414
  out['recs'] = r.instance_variable_get(:@recs)
373
415
  out['funcs'] = r.instance_variable_get(:@funcs)
374
416
  out['loads'] = r.loads
417
+ # The executor's own failures' bases (nil read as a number: a NoMethodError or a TypeError by the operand's side), and
418
+ # the class a stub raises for a rescue of every StandardError.
419
+ std = ->(k) { k.ancestors.grep(Class).map(&:name) - %w[Object BasicObject] }
420
+ out['kinds'] = {'KeyError' => std.(KeyError), 'ZeroDivisionError' => std.(ZeroDivisionError), 'AttributeError' => std.(NoMethodError)}
421
+ out['exc'] = {'mro' => %w[StandardError Exception], 'raise' => 'StandardError'}
375
422
  puts JSON.generate(out)
@@ -12,7 +12,7 @@ import { someHolds } from "./exists.js";
12
12
  export const isStepLaw = (w) => 'then' in w;
13
13
  // A request's environment: the params, its inputs and queries, and the step's flags decided (as ?name).
14
14
  export function requestEnv(m, run, params, st, input) {
15
- const env = { ...params, ...numbersOf(input), ...run.queries(params, st, input) }, seen = carriedView(m, st, input);
15
+ const env = { ...params, ...numbersOf(input), ...run.queries(params, st, input) }, seen = carriedView(m, st, input, undefined, params);
16
16
  for (const [name, c] of Object.entries(m.step.flags ?? {}))
17
17
  env[`?${name}`] = evalC(c, env, seen, m) ? 1 : 0;
18
18
  return env;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.35.0",
3
+ "version": "0.37.0",
4
4
  "description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
5
5
  "keywords": [
6
6
  "verification",