gdp-wired 0.34.0 → 0.36.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.
@@ -70,6 +70,7 @@ export type Machine = {
70
70
  assume?: C;
71
71
  history?: History;
72
72
  sums?: Record<string, Sum>;
73
+ counts?: Record<string, Counted>;
73
74
  fns?: Record<string, Fn>;
74
75
  facts?: Law[];
75
76
  leasts?: Record<string, Least>;
@@ -136,6 +137,12 @@ export type Sum = {
136
137
  key: string;
137
138
  term: E;
138
139
  };
140
+ export type Counted = {
141
+ j: string;
142
+ key: string;
143
+ below: E;
144
+ body: E;
145
+ };
139
146
  export type MapUpdate = {
140
147
  key: E;
141
148
  value: E;
@@ -219,7 +226,7 @@ export declare function evalC(c: C, env: Env, st: State, m: Machine): boolean;
219
226
  export declare function compileE(e: E, m: Machine): (env: Env, st: State) => number;
220
227
  export declare function compileC(c: C, m: Machine): (env: Env, st: State) => boolean;
221
228
  export declare function leastsIn(m: Machine, env: Env, st: State): Env;
222
- export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string): State;
229
+ export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string, params?: Env): State;
223
230
  export declare const numbersOf: (input: Request) => Record<string, number>;
224
231
  export declare function interpret(m: Machine): {
225
232
  init: (params: Env) => State;
@@ -448,11 +448,26 @@ export function leastsIn(m, env, st) {
448
448
  }
449
449
  const empty = { scalars: {}, maps: {} };
450
450
  // The state as a step reads it: with the maps the request carries (cells past them read 0), each checked natural.
451
- export function carriedView(m, st, input, rename = map => map) {
452
- if (!m.inputMaps?.length)
451
+ // A request's counts (Machine.counts) are read at this view too: each count map's cell at x, computed when read, the sum
452
+ // of its body over the keys below its bound, j at x (CountMachine.lean's cntOf at CReach's view: the params, the request's
453
+ // numbers, the state, the maps it carries).
454
+ class CountCells extends Map {
455
+ at;
456
+ constructor(at) {
457
+ super();
458
+ this.at = at;
459
+ }
460
+ get(x) { let v = super.get(x); if (v === undefined) {
461
+ v = this.at(x);
462
+ super.set(x, v);
463
+ } return v; }
464
+ }
465
+ export function carriedView(m, st, input, rename = map => map, params) {
466
+ const counts = Object.entries(m.counts ?? {});
467
+ if (!m.inputMaps?.length && !counts.length)
453
468
  return st;
454
469
  const maps = { ...st.maps }, defaults = { ...st.defaults };
455
- for (const map of m.inputMaps) {
470
+ for (const map of m.inputMaps ?? []) {
456
471
  const cells = input[map];
457
472
  if (!(cells instanceof Map))
458
473
  throw new RangeError(`input ${map} must be a Map of naturals`);
@@ -463,6 +478,21 @@ export function carriedView(m, st, input, rename = map => map) {
463
478
  maps[rename(map)] = cells;
464
479
  defaults[rename(map)] = 0;
465
480
  }
481
+ if (counts.length) {
482
+ if (!params)
483
+ throw new Error(`${m.name}: a request's counts read the params`);
484
+ const view = { ...st, maps, defaults }, env0 = { ...params, ...numbersOf(input) };
485
+ for (const [c, d] of counts) {
486
+ maps[rename(c)] = new CountCells(x => {
487
+ const e1 = { ...env0, [d.j]: x }, n = evalE(d.below, e1, view, m);
488
+ let sum = 0;
489
+ for (let k = 0; k < n; k++)
490
+ sum = exact(sum + evalE(d.body, { ...e1, [d.key]: k }, view, m));
491
+ return sum;
492
+ });
493
+ defaults[rename(c)] = 0;
494
+ }
495
+ }
466
496
  return { ...st, maps, defaults };
467
497
  }
468
498
  // A request's numbers (its inputs), without the maps it carries.
@@ -482,7 +512,7 @@ export function interpret(m) {
482
512
  env[i] = naturalIn(input[i], `input ${i}`);
483
513
  return env;
484
514
  };
485
- const viewed = (st, input) => carriedView(m, st, input);
515
+ const viewed = (st, input, params) => carriedView(m, st, input, undefined, params);
486
516
  // The records a request's queries read: with pruning, those not yet spent at its order.
487
517
  const live = (env, st) => {
488
518
  const records = st.history;
@@ -530,7 +560,7 @@ export function interpret(m) {
530
560
  return m.leasts ? { ...qs, ...leastsIn(m, { ...env, ...qs }, viewed(st, input)) } : qs;
531
561
  },
532
562
  step: (params, given, input) => {
533
- const env = args(params, input), st = viewed(given, input);
563
+ const env = args(params, input), st = viewed(given, input, params);
534
564
  let records = [];
535
565
  if (h) {
536
566
  ordered(env, st);
@@ -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)
@@ -23,7 +23,7 @@ export const allowed = (m, run, params, st, input) => {
23
23
  const order = m.history?.prune?.order;
24
24
  if (order !== undefined && st.last !== undefined && input[order] < st.last)
25
25
  return false;
26
- return !m.assume || evalC(m.assume, requestEnv(m, run, params, st, input), carriedView(m, st, input), m);
26
+ return !m.assume || evalC(m.assume, requestEnv(m, run, params, st, input), carriedView(m, st, input, undefined, params), m);
27
27
  };
28
28
  // The keys a law about every key is read at: 0 to bound + 1, and every key a map holds.
29
29
  export const keysOf = (bound, ...states) => {
@@ -313,6 +313,31 @@ export declare function checkCounted(g: CountedGoal, cert: {
313
313
  tree: Tree;
314
314
  }): boolean;
315
315
  export declare function countedGoal(g: CountedGoal, insts: CountInst[]): Goal | undefined;
316
+ export type CountDecl = {
317
+ map: string;
318
+ j: string;
319
+ key: string;
320
+ below: E;
321
+ body: E;
322
+ };
323
+ export type MapRead = [string, string, E];
324
+ export type CountCert = {
325
+ reads: MapRead[];
326
+ insts: CountInst[];
327
+ tree: Tree;
328
+ };
329
+ export declare const postName: (map: string) => string;
330
+ export declare const stateCounts: (m: Machine) => string[];
331
+ export declare function checkMC(hyps: C[], ds: CountDecl[], k: CountCert): boolean;
332
+ export declare function mcGoal(hyps: C[], ds: CountDecl[], k: Pick<CountCert, 'reads' | 'insts'>): Goal | undefined;
333
+ export declare function countedObligations(m: Machine, laws: Law[], instances?: Record<string, Instances>, only?: number): {
334
+ goal: Goal;
335
+ decls: CountDecl[];
336
+ }[];
337
+ export declare function checkCountedLaws(m: Machine, laws: Law[], proof: {
338
+ instances: Record<string, Instances>;
339
+ certs: Record<string, CountCert>;
340
+ }): boolean;
316
341
  export type GhostMap = {
317
342
  start: number;
318
343
  write: MapUpdate;