gdp-wired 0.38.0 → 0.40.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.
@@ -239,6 +239,11 @@ function builderOf(m, sorts) {
239
239
  for (const v of [...m.state, ...m.inputs, ...m.params])
240
240
  if (v.sort.k === 'choice' && !P.choiceVars.has(v.sort.values.join('\u0000')))
241
241
  P.choiceVars.set(v.sort.values.join('\u0000'), v.name);
242
+ // (a choice only a map's records hold: named through a cell of the map, its value unread, `m.at(0).f.of('x')`)
243
+ for (const d of m.maps)
244
+ for (const f of d.fields)
245
+ if (f.sort.k === 'choice' && !P.choiceVars.has(f.sort.values.join('\u0000')))
246
+ P.choiceVars.set(f.sort.values.join('\u0000'), `${d.name}.at(${d.key === 'str' ? "intern('')" : '0'}).${f.name}`);
242
247
  const ctx = () => ({ m, sorts, atoms: [] });
243
248
  const lines = [`rule(${JSON.stringify(m.name)})`];
244
249
  const kinds = (vs) => vs.map(v => `${v.name}: ${kindOf(v, sorts)}`).join(', ');
@@ -368,8 +373,8 @@ const isBool = (x, m) => {
368
373
  function withChoices(env, text, P, extra = []) {
369
374
  const names = new Set(env.slice(1, -1).split(', ').filter(Boolean));
370
375
  for (const w of P.choiceVars.values())
371
- if (new RegExp(`\\b${w}\\.of\\(`).test(text))
372
- names.add(w);
376
+ if (/^\w+$/.test(w) ? new RegExp(`\\b${w}\\.of\\(`).test(text) : text.includes(`${w}.of(`))
377
+ names.add(w.replace(/\.at\(.*$/, ''));
373
378
  for (const n of P.hoisted.values())
374
379
  names.delete(n);
375
380
  for (const n of extra)
@@ -16,6 +16,10 @@ export type InferOptions = {
16
16
  remainders?: boolean;
17
17
  join?: number;
18
18
  cubes?: number;
19
+ rows?: {
20
+ params: Record<string, number>;
21
+ st: State;
22
+ }[];
19
23
  };
20
24
  export type Found = {
21
25
  law: Law;
@@ -2930,9 +2930,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2930
2930
  return { small, others, bfs, cut, params: pvs.size, ms: Math.round(vnow() - t3) };
2931
2931
  };
2932
2932
  {
2933
- const r0 = instance(() => 0, undefined, rand);
2933
+ const r0 = instance(() => 0, undefined, rand), own = [...r0.small, ...r0.others], most = new Map();
2934
2934
  samples.unshift(...r0.small);
2935
- smallAll = [...r0.small, ...r0.others];
2935
+ for (const q of own)
2936
+ for (const [mp, cs] of Object.entries(q.st.maps))
2937
+ for (const c of cs.values())
2938
+ most.set(mp, Math.max(most.get(mp) ?? 0, c));
2939
+ // (the rows given, where their cells take values the small instance's do (a yes/no's 1 at least): more states, not
2940
+ // more values, so the literals the cubes are made of are the instance's own)
2941
+ smallAll = [...(opts.rows ?? []).filter(q => Object.entries(q.st.maps).every(([mp, cs]) => [...cs.values()].every(c => c <= Math.max(1, most.get(mp) ?? 1)))), ...own];
2936
2942
  }
2937
2943
  const out = [];
2938
2944
  for (const counts of width.reduce((acc, w) => acc.flatMap(c => Array.from({ length: w + 1 }, (_, k) => [...c, k])), [[]])) {
@@ -4,7 +4,8 @@
4
4
  # one that keeps what is set, the clock read as the request's time. Line events count the branch arms reached.
5
5
  #
6
6
  # python3 core/py/harness.py <in-fifo> <out-fifo>
7
- import asyncio, dataclasses, importlib, inspect, json, os, sys, types
7
+ import asyncio, dataclasses, datetime, importlib, inspect, json, os, sys, types
8
+ import time as time_module
8
9
 
9
10
  NOW = [0]
10
11
  CUR = {}
@@ -49,16 +50,20 @@ class FakeStore:
49
50
  setattr(o, parts[-1], v)
50
51
  asyncs = decl.get('async') or {}
51
52
  def mk(kind, name):
52
- def get(*a, **k): return self.data.get(k.get('key', a[0] if a else None))
53
+ # (the key by position, or as key= or name=, redis-py's; nx and xx as redis-py's: True where it set, else None)
54
+ kk = lambda a, k: k.get('key', k.get('name', a[0] if a else None))
55
+ def get(*a, **k): return self.data.get(kk(a, k))
53
56
  def set_(*a, **k):
54
- key = k.get('key', a[0] if a else None); val = k.get('value', a[1] if len(a) > 1 else None)
57
+ key = kk(a, k); val = k.get('value', a[1] if len(a) > 1 else None)
58
+ if (k.get('nx') and key in self.data) or (k.get('xx') and key not in self.data): return None
55
59
  self.data[key] = val
56
- def delete(*a, **k): self.data.pop(k.get('key', a[0] if a else None), None)
60
+ if k.get('nx') or k.get('xx'): return True
61
+ def delete(*a, **k): self.data.pop(kk(a, k), None)
57
62
  f0, key = {'get': get, 'set': set_, 'delete': delete}[kind], f"{self.name}.{name}"
58
63
  # (where the request says the operation raises, inside a try that catches it)
59
64
  def f(*a, **k):
60
65
  r = (CUR.get(key) or {}).get('raise')
61
- if r is not None: raise raised(r)
66
+ if r is not None and raises_here(key): raise raised(r)
62
67
  return f0(*a, **k)
63
68
  if asyncs.get(name):
64
69
  async def af(*a, **k): return f(*a, **k)
@@ -79,7 +84,7 @@ def build(spec, stores):
79
84
  v = spec['in']
80
85
  return float(v) if spec.get('float') and isinstance(v, int) and not isinstance(v, bool) else v
81
86
  if spec.get('none'): return None
82
- if spec.get('inert'): return Inert()
87
+ if spec.get('inert'): return {} if spec.get('dict') else Inert()
83
88
  if 'store' in spec: return stores.setdefault(spec['store'], FakeStore(S['stores'].get(spec['store'], {}), spec['store']))
84
89
  if 'list' in spec: return [build(x, stores) for x in spec['list']]
85
90
  if 'rec' in spec:
@@ -134,6 +139,15 @@ def tpl_match(tpl, key):
134
139
  if not isinstance(key, str) or not key.startswith(pre) or not key.endswith(post) or len(key) < len(pre) + len(post): return None
135
140
  return key[len(pre): len(key) - len(post)] if '{}' in tpl else ('' if key == tpl else None)
136
141
 
142
+ def owns(l, key):
143
+ """The part of a store's key a leaf's template takes, where no more specific template of the store takes it (the
144
+ templates name distinct keys: "{}:lock" keys aren't "{}" ones)."""
145
+ h = tpl_match(l['tpl'], key)
146
+ if h is None: return None
147
+ for m in S['leaves']:
148
+ if m.get('store') == l['store'] and m is not l and len(m['tpl']) > len(l['tpl']) and tpl_match(m['tpl'], key) is not None: return None
149
+ return h
150
+
137
151
  def state_of(obj, stores):
138
152
  s = {}
139
153
  for l in S['leaves']:
@@ -143,9 +157,18 @@ def state_of(obj, stores):
143
157
  st = stores.get(l['store'])
144
158
  cells = {}
145
159
  for key, v in (st.data.items() if st else []):
146
- h = tpl_match(l['tpl'], key)
160
+ h = owns(l, key)
147
161
  if h is None: continue
148
- cells[h] = {'value': enc_num(v)}
162
+ if l.get('json'):
163
+ # (a JSON record: its fields kept, an optional one beside whether the key holds a value; strings left out)
164
+ d, c = json.loads(v), {}
165
+ for f in l['json']:
166
+ if f.get('out'): continue
167
+ x = d.get(f['name']) if f.get('opt') else d[f['name']]
168
+ if f.get('opt'): c[f['name'] + '_has'] = x is not None
169
+ c[f['name']] = (x if x is not None else (f['vals'][0] if f.get('choice') else 0)) if f.get('choice') else enc_num(0 if x is None else x)
170
+ cells[h] = c
171
+ else: cells[h] = {'value': v if l.get('choice') else enc_num(v)}
149
172
  s[l['name']] = cells
150
173
  continue
151
174
  v = walk(obj, l['path'])
@@ -178,8 +201,11 @@ def set_state(obj, stores, state):
178
201
  if l.get('store'):
179
202
  st = stores[l['store']]
180
203
  pre, _, post = l['tpl'].partition('{}')
181
- for key in [kk for kk in st.data if tpl_match(l['tpl'], kk) is not None]: del st.data[key]
182
- for h, c in (v or {}).items(): st.data[pre + h + post if '{}' in l['tpl'] else l['tpl']] = num_in(c['value'], l.get('float'))
204
+ for key in [kk for kk in st.data if owns(l, kk) is not None]: del st.data[key]
205
+ for h, c in (v or {}).items():
206
+ at = pre + h + post if '{}' in l['tpl'] else l['tpl']
207
+ if l.get('json'): st.data[at] = json.dumps({f['name']: (c[f['name']] if f.get('choice') else num_in(c[f['name']], False)) for f in l['json'] if not f.get('out') and (not f.get('opt') or c.get(f['name'] + '_has'))})
208
+ else: st.data[at] = c['value'] if l.get('choice') else num_in(c['value'], l.get('float'))
183
209
  continue
184
210
  if k == 'num': put(obj, l['path'], num_in(v, l.get('float')))
185
211
  elif k in ('str', 'choice', 'bool'): put(obj, l['path'], v)
@@ -223,6 +249,39 @@ class Clock:
223
249
  def perf_counter(self): return float(NOW[0])
224
250
  def __getattr__(self, n): return getattr(self.real, n)
225
251
 
252
+ class _Now(datetime.datetime):
253
+ """datetime.datetime with now() the request's time (local, naive, as the code's own now())."""
254
+ @classmethod
255
+ def now(cls, tz=None): return datetime.datetime.fromtimestamp(NOW[0], tz)
256
+
257
+ def pin_clocks(root):
258
+ """The clock the repository's modules read (time.time(), datetime.now()) made the request's time."""
259
+ root = os.path.realpath(root)
260
+ dtm = types.SimpleNamespace(**{k: getattr(datetime, k) for k in dir(datetime) if not k.startswith('__')})
261
+ dtm.datetime = _Now
262
+ for m in list(sys.modules.values()):
263
+ f = getattr(m, '__file__', None)
264
+ if not f or not os.path.realpath(f).startswith(root + os.sep): continue
265
+ for n, v in list(vars(m).items()):
266
+ if v is time_module: setattr(m, n, Clock(v))
267
+ elif v is datetime: setattr(m, n, dtm)
268
+ elif v is datetime.datetime: setattr(m, n, _Now)
269
+
270
+ def raises_here(key):
271
+ """Whether a call left out raises here, as the request says: only at the sites the rule read it may raise (a call of
272
+ the same callee elsewhere, outside a try that catches it, runs as it is)."""
273
+ a = next((x for x in S.get('answers') or [] if x['key'] == key), None)
274
+ if not a or not a.get('pass') or not a.get('at'): return True
275
+ f = sys._getframe(1)
276
+ while f is not None and os.path.realpath(f.f_code.co_filename) == os.path.realpath(__file__): f = f.f_back
277
+ if f is None: return True
278
+ here, line = os.path.basename(f.f_code.co_filename), f.f_lineno
279
+ for site in a['at']:
280
+ file, l0 = site['p'].split(':')[0], int(site['p'].split(':')[1])
281
+ l1 = int(site['end'].split(':')[0]) if site.get('end') and site['end'].split(':')[0].isdigit() else l0
282
+ if file == here and l0 <= line <= l1: return True
283
+ return False
284
+
226
285
  def raised(r):
227
286
  """The exception a stub raises where the request says: the class a handler names, made without its arguments."""
228
287
  cls = eval(r[1], vars(importlib.import_module(r[0])))
@@ -234,7 +293,7 @@ def stub(key, is_async, orig=None):
234
293
  # (orig: a call left out, run as it is unless the request says it raises)
235
294
  def value(a_, k_):
236
295
  a = CUR.get(key)
237
- if a is not None and a.get('raise') is not None: raise raised(a['raise'])
296
+ if a is not None and a.get('raise') is not None and raises_here(key): raise raised(a['raise'])
238
297
  if orig is not None: return orig(*a_, **k_)
239
298
  if a is None or a.get('none'): return None
240
299
  return build(a, {})
@@ -258,7 +317,7 @@ def hello(req):
258
317
  sys.path.insert(0, req['root'])
259
318
  S['mod'] = importlib.import_module(req['module'])
260
319
  mod = S['mod']
261
- if isinstance(getattr(mod, 'time', None), types.ModuleType): mod.time = Clock(mod.time)
320
+ pin_clocks(req['root'])
262
321
  S['self_stubs'] = []
263
322
  for a in req['answers']:
264
323
  p = a['patch']
@@ -308,6 +367,10 @@ def call(req):
308
367
  err = None
309
368
  except Exception as e:
310
369
  out, err = None, f"{type(e).__name__}: {e}"[:300]
370
+ # (GDP_HARNESS_LOG: each exception the code raised, with its traceback, appended there)
371
+ if os.environ.get('GDP_HARNESS_LOG'):
372
+ import traceback
373
+ with open(os.environ['GDP_HARNESS_LOG'], 'a') as f: f.write(f"{req['m']} {json.dumps(req.get('answers'))}\n{traceback.format_exc()}\n")
311
374
  finally:
312
375
  sys.settrace(None)
313
376
  if err is not None and snap is not None: set_state(obj, stores, snap)
@@ -9,7 +9,7 @@ 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).
12
- KNOWN = {'time.time', 'time.monotonic', 'time.perf_counter', 'math.floor', 'math.ceil', 'math.isfinite', 'math.isnan', 'math.isinf', 'threading.Lock', 'threading.RLock', 'asyncio.Lock'}
12
+ KNOWN = {'time.time', 'time.monotonic', 'time.perf_counter', 'datetime.datetime.now', 'datetime.timedelta', 'math.floor', 'math.ceil', 'math.isfinite', 'math.isnan', 'math.isinf', 'threading.Lock', 'threading.RLock', 'asyncio.Lock'}
13
13
  TRANSPARENT = {'staticmethod', 'classmethod', 'property', 'dataclass', 'dataclasses.dataclass', 'override', 'typing.override', 'abstractmethod'}
14
14
 
15
15
  def where(file, n):
@@ -97,6 +97,7 @@ class Reader:
97
97
  self.recs, self.funcs = {}, {}
98
98
  self.local_stack = []
99
99
  self.caught = [] # (the names the handlers being read bind their exceptions to)
100
+ self.based, self.supers, self.defs, self.local_imps = set(), [], {}, [] # (the bases read as bases; the bases of the class whose method is read)
100
101
 
101
102
  # --- types -------------------------------------------------------------------------------------------------------
102
103
  def find_class(self, mod, name, depth=0):
@@ -112,6 +113,23 @@ class Reader:
112
113
  if name in mod.consts and isinstance(mod.consts[name], ast.Name): # an alias: X = Y
113
114
  return self.find_class(mod, mod.consts[name].id, depth + 1)
114
115
  return None
116
+ def const_map(self, v, mod, p):
117
+ """A module's constant mapping of string keys to constants (a dict literal, or MappingProxyType of one): the dict
118
+ literal itself, made where it is read (a write to it is a write to no variable, refused)."""
119
+ if isinstance(v, ast.Call) and (dotted(v.func) or '').split('.')[-1] == 'MappingProxyType' and len(v.args) == 1 and not v.keywords: v = v.args[0]
120
+ if not isinstance(v, ast.Dict) or not v.keys: return None
121
+ if not all(isinstance(k, ast.Constant) and isinstance(k.value, str) for k in v.keys): return None
122
+ if not all(isinstance(x, ast.Constant) and isinstance(x.value, (str, int, bool)) for x in v.values): return None
123
+ return {'e': 'dict', 'keys': [self.expr(k, mod) for k in v.keys], 'vals': [self.expr(x, mod) for x in v.values], 'const': True, 'p': p}
124
+ def find_const(self, mod, name, p, depth=0):
125
+ """A constant mapping another module of the repository defines, through its imports (re-exports too)."""
126
+ imp = mod.imports.get(name)
127
+ if depth > 6 or not imp or imp[0] != 'name': return None
128
+ path = self.repo.path_of(imp[1])
129
+ if not path: return None
130
+ sub = Module(self.repo, path) if path != mod.path else mod
131
+ if imp[2] in sub.consts: return self.const_map(sub.consts[imp[2]], sub, p)
132
+ return self.find_const(sub, imp[2], p, depth + 1)
115
133
  def ret_of(self, modname, name, depth=0):
116
134
  """The declared result type of a function a module of the repository defines (through its re-exports), or None."""
117
135
  p = self.repo.path_of(modname) if modname else None
@@ -122,10 +140,14 @@ class Reader:
122
140
  imp = m.imports.get(name)
123
141
  if imp and imp[0] == 'name': return self.ret_of(imp[1], imp[2], depth + 1)
124
142
  return None
125
- def rec_of(self, mod, cdef):
126
- """A class as a record type: its fields (annotations, its bases' first), its methods (to resolve calls)."""
143
+ def rec_of(self, mod, cdef, base=False):
144
+ """A class as a record type: its fields (annotations, its bases' first), its methods (to resolve calls). A class
145
+ of the file, or a base of one (another module's too: its methods are the class's own), has its methods read."""
127
146
  q = f"{mod.name}.{cdef.name}"
128
- if q in self.recs: return q
147
+ if q in self.recs and not (base and self.recs[q] and None in self.recs[q]['methods'].values() and q not in self.based):
148
+ return q
149
+ if base: self.based.add(q)
150
+ self.defs[q] = (mod, cdef)
129
151
  self.recs[q] = None # (being read)
130
152
  fields, methods, bases, kinds, rets = [], {}, [], set(), {}
131
153
  for b in cdef.bases:
@@ -136,7 +158,7 @@ class Reader:
136
158
  if bn in ('Generic', 'object', 'Exception'): continue
137
159
  hit = self.find_class(mod, bn.split('.')[-1]) if bn else None
138
160
  if hit:
139
- bq = self.rec_of(*hit)
161
+ bq = self.rec_of(*hit, base=base or mod.path == self.file)
140
162
  if bq and self.recs.get(bq):
141
163
  br = self.recs[bq]
142
164
  bases.append(bq)
@@ -178,9 +200,12 @@ class Reader:
178
200
  elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
179
201
  if n.returns is not None: rets[n.name] = self.ty(n.returns, mod)
180
202
  else: rets.pop(n.name, None)
181
- if mod.path == self.file:
203
+ if mod.path == self.file or base:
182
204
  fid = f"{cdef.name}.{n.name}"
183
- self.funcs[fid] = self.func(n, mod, cdef.name, fid)
205
+ # (a base's method read where its module is: its positions in its own file, super() its own bases')
206
+ file, self.file, sup, self.supers = self.file, mod.path, self.supers, bases
207
+ try: self.funcs[fid] = self.func(n, mod, cdef.name, fid)
208
+ finally: self.file, self.supers = file, sup
184
209
  methods[n.name] = fid
185
210
  else: methods[n.name] = None # another module's method: not read
186
211
  r = {'name': q, 'short': cdef.name, 'fields': fields, 'methods': methods, 'bases': bases, 'p': where(mod.path, cdef),
@@ -240,6 +265,13 @@ class Reader:
240
265
  # --- functions ---------------------------------------------------------------------------------------------------
241
266
  def func(self, n, mod, cls, fid):
242
267
  self.local_stack.append(set(self.locals_of(n)))
268
+ # (the names the function imports in its body: an exception class raised there resolves through them)
269
+ imps = {}
270
+ for x in ast.walk(n):
271
+ if isinstance(x, ast.ImportFrom):
272
+ m = resolve_from(mod.name, mod.is_pkg, x)
273
+ for a in x.names: imps[a.asname or a.name] = ('name', m, a.name)
274
+ self.local_imps.append(imps)
243
275
  try:
244
276
  a = n.args
245
277
  params = []
@@ -259,6 +291,7 @@ class Reader:
259
291
  'params': params, 'ret': self.ty(n.returns, mod), 'body': body, 'async': isinstance(n, ast.AsyncFunctionDef), 'decorators': decs, 'static': static}
260
292
  finally:
261
293
  self.local_stack.pop()
294
+ self.local_imps.pop()
262
295
  def decorator(self, d):
263
296
  f = d.func if isinstance(d, ast.Call) else d
264
297
  return {'name': dotted(f) or text(f), 'text': text(d), 'p': where(self.file, d)}
@@ -283,7 +316,9 @@ class Reader:
283
316
  p = where(self.file, s)
284
317
  E = lambda x: self.expr(x, mod)
285
318
  if isinstance(s, ast.Expr):
286
- if isinstance(s.value, ast.Constant) and isinstance(s.value.value, str): return [] # a docstring
319
+ if isinstance(s.value, ast.Constant) and (isinstance(s.value.value, str) or s.value.value is Ellipsis): return [] # a docstring, or `...`
320
+ # (a bare yield: where a context manager made by @contextmanager runs the body of the with)
321
+ if isinstance(s.value, ast.Yield) and s.value.value is None: return [{'s': 'yield', 'p': p}]
287
322
  return [{'s': 'expr', 'p': p, 'x': E(s.value)}]
288
323
  if isinstance(s, ast.Pass): return []
289
324
  if isinstance(s, (ast.Assign, ast.AnnAssign)):
@@ -350,11 +385,12 @@ class Reader:
350
385
  d = dotted(x)
351
386
  if d is None or depth > 8: return [text(x)], True
352
387
  head, *rest = d.split('.')
353
- if not rest and head not in mod.imports and head not in mod.classes:
388
+ local = self.local_imps[-1].get(head) if self.local_imps and depth == 0 and head not in mod.imports else None
389
+ if not rest and head not in mod.imports and head not in mod.classes and not local:
354
390
  b = getattr(builtins, head, None)
355
391
  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
392
  hit = self.find_class(mod, head) if not rest else None
357
- imp = mod.imports.get(head)
393
+ imp = mod.imports.get(head) or local
358
394
  if hit is None and imp:
359
395
  q = f"{imp[1]}.{imp[2]}" if imp[0] == 'name' else imp[1]
360
396
  q = '.'.join([q, *rest])
@@ -391,11 +427,18 @@ class Reader:
391
427
  if imp[0] == 'module': return {'e': 'ext', 'q': imp[1], 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'p': p}
392
428
  hit = self.find_class(mod, n)
393
429
  if hit: return {'e': 'cls', 'rec': self.rec_of(*hit), 'q': f"{imp[1]}.{imp[2]}", 'patch': {'mod': mod.name, 'path': [n]}, 'p': p}
430
+ cm = self.find_const(mod, n, p)
431
+ if cm: return cm
394
432
  ret = self.ret_of(imp[1], imp[2])
395
433
  return {'e': 'ext', 'q': f"{imp[1]}.{imp[2]}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'p': p, **({'ret': ret} if ret else {})}
396
434
  if n in mod.consts:
397
435
  v = mod.consts[n]
398
436
  if isinstance(v, ast.Constant) or (isinstance(v, ast.UnaryOp) and isinstance(v.operand, ast.Constant)): return self.expr(v, mod)
437
+ cm = self.const_map(v, mod, p)
438
+ if cm: return cm
439
+ # (a logger, logging.getLogger(...): its calls never raise, logging handles its handlers' errors itself)
440
+ if isinstance(v, ast.Call) and (dotted(v.func) or '') in ('logging.getLogger', 'getLogger'):
441
+ return {'e': 'ext', 'q': f"{mod.name}.{n}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'global': True, 'nothrow': True, 'p': p}
399
442
  return {'e': 'ext', 'q': f"{mod.name}.{n}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'global': True, 'p': p}
400
443
  if n in ('True', 'False', 'None'): return self.expr(ast.Constant({'True': True, 'False': False, 'None': None}[n]), mod)
401
444
  if n in BUILTINS: return {'e': 'builtin', 'n': n, 'p': p}
@@ -447,8 +490,21 @@ class Reader:
447
490
  if isinstance(x, ast.IfExp): return {'e': 'ite', 'c': E(x.test), 'a': E(x.body), 'b': E(x.orelse), 'p': p}
448
491
  if isinstance(x, ast.Await): return {'e': 'await', 'x': E(x.value), 'p': p}
449
492
  if isinstance(x, ast.Call):
493
+ # super().m(...): the first base (in the order its bases are listed, theirs after) whose m is read, on self;
494
+ # super().__init__() where no base has one: object's, nothing
495
+ fx = x.func
496
+ if isinstance(fx, ast.Attribute) and isinstance(fx.value, ast.Call) and isinstance(fx.value.func, ast.Name) and fx.value.func.id == 'super' and not fx.value.args:
497
+ mid = next((self.recs[b]['methods'][fx.attr] for b in self.supers if self.recs.get(b) and fx.attr in self.recs[b]['methods']), False)
498
+ if mid is False and fx.attr == '__init__' and not x.args and not x.keywords: return {'e': 'none', 'p': p}
499
+ if not mid: return {'e': 'no', 'why': f"{text(x)}: a base's method not read", 'p': p}
500
+ return {'e': 'call', 'f': {'e': 'get', 'x': {'e': 'var', 'n': 'self', 'p': p}, 'f': fx.attr, 'sup': mid, 'p': p, 'text': text(fx)},
501
+ 'args': [E(a) for a in x.args], 'kw': [[k.arg, E(k.value)] if k.arg else ['**', {'e': 'no', 'why': f"**{text(k.value)}", 'p': p}] for k in x.keywords], 'p': p, 'text': text(x)}
450
502
  f = E(x.func)
451
503
  if f.get('e') == 'ext' and f.get('q') in KNOWN: f = {'e': 'lib', 'q': f['q'], 'p': f['p']}
504
+ # (a class of the repository made here: its methods read, its __init__ the code that makes it)
505
+ if f.get('e') == 'cls' and f['rec'] in self.defs and self.recs.get(f['rec']) and not self.recs[f['rec']]['own']:
506
+ r0 = self.recs[f['rec']]
507
+ if not any(k.startswith('outside-base') or k in ('pydantic', 'typeddict', 'protocol') for k in r0['kinds']): self.rec_of(*self.defs[f['rec']], base=True)
452
508
  # any, all or sum of one generator: a loop over its collection (a fold), its value the accumulator's
453
509
  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
510
  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:
@@ -500,7 +556,7 @@ def main():
500
556
  if n not in r.funcs: r.funcs[n] = r.func(f, mod, None, n)
501
557
  out['recs'] = {k: v for k, v in r.recs.items() if v}
502
558
  # 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')}
559
+ 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', 'UnboundLocalError', 'RuntimeError', 'OverflowError')}
504
560
  out['exc'] = {'mro': ['builtins.Exception', 'builtins.BaseException'], 'raise': ['builtins', 'Exception']}
505
561
  out['lists'] = True
506
562
  out['funcs'] = r.funcs
@@ -1311,7 +1311,7 @@ export function modelInstances(m, laws, inst, goal, w, most = 64) {
1311
1311
  if (!keyed.length && !qs.length)
1312
1312
  return undefined;
1313
1313
  // (the maps a request carries read as maps too: a quantified flag over one, wo's ∀k. Q has k → Votes[src, k])
1314
- const fns = Object.keys(pm.fns ?? {}), mm = { ...pm, fns: undefined, maps: { ...(pm.maps ?? {}), ...Object.fromEntries([...fns, ...(pm.inputMaps ?? [])].map(f => [f, 0])) } };
1314
+ const fns = Object.keys(pm.fns ?? {}), mm = { ...pm, fns: undefined, maps: { ...(pm.maps ?? {}), ...Object.fromEntries([...fns, ...(pm.inputMaps ?? []), ...Object.keys(pm.counts ?? {})].map(f => [f, 0])) } };
1315
1315
  const maps = Object.fromEntries(Object.keys(mm.maps).map(mp => [mp, new Map()]));
1316
1316
  for (const [cell, value] of Object.entries(w)) {
1317
1317
  const br = cell.indexOf('[');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.38.0",
3
+ "version": "0.40.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",