gdp-wired 0.42.0 → 0.43.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.
@@ -672,8 +672,8 @@ export function compileJs(m) {
672
672
  case '<': return `(${ex(c.a)} < ${ex(c.b)})`;
673
673
  case '<=': return `(${ex(c.a)} <= ${ex(c.b)})`;
674
674
  case '=': return `(${ex(c.a)} === ${ex(c.b)})`;
675
- case 'and': return `(${c.xs.map(cx).join(' && ')})`;
676
- case 'or': return `(${c.xs.map(cx).join(' || ')})`;
675
+ case 'and': return c.xs.length ? `(${c.xs.map(cx).join(' && ')})` : 'true';
676
+ case 'or': return c.xs.length ? `(${c.xs.map(cx).join(' || ')})` : 'false';
677
677
  case 'not': return `(!${cx(c.x)})`;
678
678
  case 'flag': return `flag${flags.indexOf(c.name)}`;
679
679
  case 'all': {
@@ -82,6 +82,7 @@ class FakeStore:
82
82
  def build(spec, stores):
83
83
  if 'in' in spec:
84
84
  v = spec['in']
85
+ if spec.get('bytes') and isinstance(v, str): return v.encode('latin-1')
85
86
  return float(v) if spec.get('float') and isinstance(v, int) and not isinstance(v, bool) else v
86
87
  if spec.get('none'): return None
87
88
  if spec.get('inert'): return {} if spec.get('dict') else Inert()
@@ -174,13 +175,14 @@ def state_of(obj, stores):
174
175
  v = walk(obj, l['path'])
175
176
  if k == 'none': s[l['name']] = v is None
176
177
  elif k == 'num': s[l['name']] = '0' if v is None else enc_num(v)
177
- elif k in ('str', 'choice'): s[l['name']] = '' if v is None else v
178
+ elif k in ('str', 'choice'): s[l['name']] = '' if v is None else v.decode('latin-1') if isinstance(v, (bytes, bytearray)) else v
178
179
  elif k == 'bool': s[l['name']] = False if v is None else v
179
180
  elif k == 'map':
180
181
  cells = {}
181
182
  # (a list: its items by their places, 0 first)
182
- for key, x in (enumerate(v or []) if l.get('ordered') else (v or {}).items()):
183
- if l.get('fields'): cells[str(key)] = {f['name']: (lambda y: y if f.get('choice') else enc_num(y))(x[f['name']] if isinstance(x, dict) else getattr(x, f['name'])) for f in l['fields']}
183
+ for key, x in (enumerate(v or []) if l.get('ordered') else ((k, None) for k in v or ()) if l.get('set') else (v or {}).items()):
184
+ if l.get('set'): cells[str(key)] = {}
185
+ elif l.get('fields'): cells[str(key)] = {f['name']: (lambda y: y if f.get('choice') else enc_num(y))(x[f['name']] if isinstance(x, dict) else getattr(x, f['name'])) for f in l['fields']}
184
186
  else: cells[str(key)] = {'value': enc_num(x)}
185
187
  s[l['name']] = cells
186
188
  # A store's key no template names: the code keeps state the rule has no place for.
@@ -190,6 +192,10 @@ def state_of(obj, stores):
190
192
  if not any(tpl_match(t, key) is not None for t in tpls): raise ValueError(f"the store {name} holds {key!r}, a key no template of the rule names")
191
193
  return s
192
194
 
195
+ def is_bytes(l):
196
+ t = l.get('t') or {}
197
+ return bool((t.get('of') if t.get('k') == 'opt' else t).get('bytes'))
198
+
193
199
  def num_in(x, flt):
194
200
  return float(int(x)) if flt else int(x)
195
201
 
@@ -208,15 +214,16 @@ def set_state(obj, stores, state):
208
214
  else: st.data[at] = c['value'] if l.get('choice') else num_in(c['value'], l.get('float'))
209
215
  continue
210
216
  if k == 'num': put(obj, l['path'], num_in(v, l.get('float')))
211
- elif k in ('str', 'choice', 'bool'): put(obj, l['path'], v)
217
+ elif k in ('str', 'choice', 'bool'): put(obj, l['path'], v.encode('latin-1') if k == 'str' and is_bytes(l) and isinstance(v, str) else v)
212
218
  elif k == 'map':
213
219
  d = {}
214
220
  for key, c in (v or {}).items():
215
221
  kk = int(key) if l.get('key') == 'num' else key
216
- if l.get('fields'):
222
+ if l.get('set'): d[kk] = True
223
+ elif l.get('fields'):
217
224
  d[kk] = make_rec(resolve(l['cls']), {f['name']: (num_in(c[f['name']], f.get('float')) if isinstance(c[f['name']], str) and not f.get('choice') else c[f['name']]) for f in l['fields']})
218
225
  else: d[kk] = num_in(c['value'], l.get('float')) if isinstance(c['value'], str) else c['value']
219
- put(obj, l['path'], [d[kk] for kk in sorted(d)] if l.get('ordered') else d)
226
+ put(obj, l['path'], [d[kk] for kk in sorted(d)] if l.get('ordered') else set(d) if l.get('set') else d)
220
227
  for l in S['leaves']:
221
228
  if l['kind'] == 'none' and state.get(l['name']) is True: put(obj, l['path'], None)
222
229
 
@@ -10,6 +10,9 @@ import ast, builtins, json, os, sys
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
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
+ # The heads of a subscripted type an alias may stand for (`Mode = Literal[...]`).
14
+ TYPE_HEADS = {'Literal', 'Optional', 'Union', 'Final', 'Annotated', 'dict', 'Dict', 'Mapping', 'MutableMapping', 'defaultdict', 'OrderedDict', 'list', 'List', 'Sequence',
15
+ 'set', 'Set', 'frozenset', 'FrozenSet', 'AbstractSet', 'MutableSet'}
13
16
  TRANSPARENT = {'staticmethod', 'classmethod', 'property', 'dataclass', 'dataclasses.dataclass', 'override', 'typing.override', 'abstractmethod'}
14
17
 
15
18
  def where(file, n):
@@ -85,6 +88,7 @@ class Module:
85
88
  targets = n.targets if isinstance(n, ast.Assign) else [n.target]
86
89
  for t in targets:
87
90
  if isinstance(t, ast.Name) and n.value is not None: self.consts[t.id] = n.value
91
+ elif type(n).__name__ == 'TypeAlias' and isinstance(n.name, ast.Name): self.consts[n.name.id] = n.value # `type X = ...` (3.12)
88
92
  elif isinstance(n, ast.If):
89
93
  # `if TYPE_CHECKING:` imports and aliases: what the names are for the types (its else, `X = Any`, yields to it).
90
94
  for m in n.orelse + n.body: self.scan(m)
@@ -234,16 +238,21 @@ class Reader:
234
238
  if head in ('dict', 'Dict', 'Mapping', 'MutableMapping', 'defaultdict', 'OrderedDict') and len(args) == 2:
235
239
  return {'k': 'map', 'key': self.ty(args[0], mod), 'val': self.ty(args[1], mod), 'py': head}
236
240
  if head in ('list', 'List', 'Sequence'): return {'k': 'list', 'of': self.ty(args[0], mod)}
241
+ # (a set: a map of its keys alone, each held or not)
242
+ if head in ('set', 'Set', 'frozenset', 'FrozenSet', 'AbstractSet', 'MutableSet') and len(args) == 1: return {'k': 'map', 'key': self.ty(args[0], mod), 'val': {'k': 'none'}, 'set': True, 'py': head}
237
243
  return {'k': 'opaque', 'why': f"{text(a)}"}
238
244
  n = dotted(a)
239
245
  if n in ('int',): return {'k': 'int'}
240
246
  if n in ('float',): return {'k': 'float'}
241
247
  if n in ('bool',): return {'k': 'bool'}
242
248
  if n in ('str',): return {'k': 'str'}
249
+ if n in ('bytes', 'bytearray'): return {'k': 'str', 'bytes': True} # (a string of bytes: set and compared, never equal to a str)
243
250
  if n in ('None',): return {'k': 'none'}
244
251
  if n in ('Final', 'Any', 'typing.Any', 'object'): return {'k': 'any'}
245
252
  if n in ('dict', 'Dict'): return {'k': 'opaque', 'why': f"{n} with no key and value types"}
246
253
  if n in ('threading.Lock', 'asyncio.Lock', 'Lock'): return {'k': 'lock'}
254
+ al = self.alias_of(mod, n) if n and '.' not in n else None
255
+ if al: return self.ty(al[1], al[0])
247
256
  if n:
248
257
  hit = self.find_class(mod, n.split('.')[-1]) if '.' not in n or n.split('.')[0] in mod.imports else None
249
258
  if hit:
@@ -251,6 +260,37 @@ class Reader:
251
260
  if q: return {'k': 'rec', 'name': q}
252
261
  return {'k': 'opaque', 'why': f"{n}, a type outside the files read"}
253
262
  return {'k': 'opaque', 'why': text(a)}
263
+ def const_value(self, mod, v):
264
+ """A constant's value, through constants bound to other constants' names (LONG = IDLE)."""
265
+ for _ in range(6):
266
+ if isinstance(v, ast.Name) and v.id in mod.consts and v.id not in mod.classes and v.id not in mod.funcs: v = mod.consts[v.id]
267
+ else: break
268
+ return v
269
+ def module_const(self, mod, x):
270
+ """`m.NAME` where m is a module of the repository (imported whole, or `from pkg import m`) and NAME one of its
271
+ constants bound to a literal (a number, a string, a bool, None): that literal, else None."""
272
+ if not isinstance(x.value, ast.Name): return None
273
+ imp = mod.imports[x.value.id]
274
+ q = imp[1] if imp[0] == 'module' else f"{imp[1]}.{imp[2]}"
275
+ path = self.repo.path_of(q)
276
+ if not path or path == mod.path: return None
277
+ sub = Module(self.repo, path)
278
+ v = self.const_value(sub, sub.consts.get(x.attr))
279
+ lit = isinstance(v, ast.Constant) or (isinstance(v, ast.UnaryOp) and isinstance(v.op, ast.USub) and isinstance(v.operand, ast.Constant))
280
+ return self.expr(v, mod) if lit and not isinstance(getattr(v, 'value', getattr(getattr(v, 'operand', None), 'value', None)), bytes) else None
281
+ def alias_of(self, mod, name, depth=0):
282
+ """A type alias a module names, through its imports: `Mode = Literal["a", "b"]`, `Key = int | str`, `X: TypeAlias = ...`,
283
+ `type X = ...`: (module, the type it stands for), or None (a class, or a constant that is no type)."""
284
+ if depth > 6 or mod is None or name in mod.classes: return None
285
+ v = mod.consts.get(name)
286
+ if v is not None:
287
+ typing = isinstance(v, ast.Subscript) and (dotted(v.value) or '').split('.')[-1] in TYPE_HEADS
288
+ return (mod, v) if typing or (isinstance(v, ast.BinOp) and isinstance(v.op, ast.BitOr)) else None
289
+ imp = mod.imports.get(name)
290
+ if imp and imp[0] == 'name':
291
+ p = self.repo.path_of(imp[1])
292
+ if p and p != mod.path: return self.alias_of(Module(self.repo, p), imp[2], depth + 1)
293
+ return None
254
294
  def union(self, ts, a):
255
295
  none = any(t['k'] == 'none' for t in ts)
256
296
  rest = [t for t in ts if t['k'] != 'none']
@@ -433,6 +473,10 @@ class Reader:
433
473
  return {'e': 'ext', 'q': f"{imp[1]}.{imp[2]}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'p': p, **({'ret': ret} if ret else {})}
434
474
  if n in mod.consts:
435
475
  v = mod.consts[n]
476
+ # (a constant bound to another constant's name, LONG = IDLE: that one's value, a few deep)
477
+ for _ in range(6):
478
+ if isinstance(v, ast.Name) and v.id in mod.consts and v.id != n and v.id not in mod.classes and v.id not in mod.funcs: v = mod.consts[v.id]
479
+ else: break
436
480
  if isinstance(v, ast.Constant) or (isinstance(v, ast.UnaryOp) and isinstance(v.operand, ast.Constant)): return self.expr(v, mod)
437
481
  cm = self.const_map(v, mod, p)
438
482
  if cm: return cm
@@ -464,6 +508,10 @@ class Reader:
464
508
  if isinstance(x, ast.Attribute):
465
509
  d = dotted(x)
466
510
  base = d.split('.')[0] if d else None
511
+ # (a literal constant of another module of the repository, `boat.BRING_UP`: its value, as the module's own
512
+ # constants are read; what the module is set to at import, the check importing it as it ships)
513
+ lit = self.module_const(mod, x) if d and base in mod.imports and not (self.local_stack and base in self.local_stack[-1]) else None
514
+ if lit is not None: return {**lit, 'p': p}
467
515
  if d and base in mod.imports and mod.imports[base][0] == 'module' and not (self.local_stack and base in self.local_stack[-1]):
468
516
  q = mod.imports[base][1] + d[len(base):]
469
517
  if q in KNOWN: return {'e': 'lib', 'q': q, 'p': p}
@@ -543,7 +591,9 @@ def main():
543
591
  mod = r.mod
544
592
  if mod.tree is None:
545
593
  print(json.dumps({'error': f"{req['file']} doesn't parse"})); return
546
- out = {'lang': 'python', 'file': os.path.basename(r.file), 'path': r.file, 'module': mod.name, 'root': os.path.abspath(req['root']), 'entries': []}
594
+ out = {'lang': 'python', 'file': os.path.basename(r.file), 'path': r.file, 'module': mod.name, 'root': os.path.abspath(req['root']), 'entries': [],
595
+ # (the module's constants bound to literals, as the code reads them: a law may name them too)
596
+ 'consts': {k: v.value for k, v in ((k, r.const_value(mod, v)) for k, v in mod.consts.items()) if isinstance(v, ast.Constant) and isinstance(v.value, (int, float, str, bool)) and not (isinstance(v.value, float) and not v.value.is_integer())}}
547
597
  for n in req['names'] or list(mod.classes):
548
598
  if n in mod.classes: out['entries'].append({'k': 'class', 'rec': r.rec_of(mod, mod.classes[n])})
549
599
  elif n in mod.funcs:
@@ -0,0 +1,44 @@
1
+ import { type Machine } from './machine.js';
2
+ import { type Kind, type Rule } from './dsl.js';
3
+ export type Model = {
4
+ name: string;
5
+ assumes: string;
6
+ checked: string;
7
+ };
8
+ export declare const assuming: (m: Machine | Rule, ...ms: Model[]) => Machine;
9
+ export declare const modelsOf: (m: Machine | Rule) => Model[];
10
+ export declare function lift(m: Machine, id: string, given?: string[]): Machine;
11
+ export type Part = Machine | Rule | {
12
+ rule: Machine | Rule;
13
+ id?: string;
14
+ shared?: string[];
15
+ };
16
+ export declare function system(name: string, parts: Record<string, Part>, opts?: {
17
+ act?: string;
18
+ kinds?: Record<string, Kind<unknown>>;
19
+ }): Rule;
20
+ export declare function asRule(m: Machine, kinds?: Record<string, Kind<unknown>>): Rule;
21
+ export type Level = 'atomic' | 'read committed' | 'snapshot';
22
+ export declare const ISOLATION: Record<Level, Model>;
23
+ export declare function isolation(m: Machine, level: Level): Machine;
24
+ export type Delivery = 'exactly-once' | 'at-least-once';
25
+ export declare const DELIVERY: Record<Delivery, Model>;
26
+ export declare function delivery(m: Machine, pool: string, fields: string[], mode: Delivery, opts?: {
27
+ msg?: string;
28
+ id?: string;
29
+ }): Machine;
30
+ export declare const client: (pool: string, fields: string[], msg?: string) => Machine;
31
+ export declare const RETRIES: Model;
32
+ export declare const STORE_FAILS: Model;
33
+ export declare const WRITES_FAIL: Model;
34
+ export declare const EXPIRY: Model;
35
+ export declare const expiry: (cells: Record<string, number>, key?: string) => Machine;
36
+ export declare const TIME: Model;
37
+ export declare const time: (now?: string, by?: string) => Machine;
38
+ export declare const SKEW: (skew: number | string) => Model;
39
+ export declare function clocked(m: Machine, at: string, skew: number | string, now?: string): Machine;
40
+ export declare const TTL: Model;
41
+ export declare function expires(cells: Record<string, number>, at: string, opts?: {
42
+ key?: string;
43
+ now?: string;
44
+ }): Machine;