gdp-wired 0.45.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -7
- package/dist/core/bitsets.d.ts +2 -0
- package/dist/core/bitsets.js +23 -0
- package/dist/core/bmc.js +6 -2
- package/dist/core/c/reader.d.ts +9 -1
- package/dist/core/c/reader.js +423 -31
- package/dist/core/calendar.d.ts +29 -0
- package/dist/core/calendar.js +82 -0
- package/dist/core/cli.d.ts +3 -0
- package/dist/core/cli.js +204 -38
- package/dist/core/compose.js +3 -1
- package/dist/core/counts.d.ts +4 -1
- package/dist/core/counts.js +314 -85
- package/dist/core/cycles.js +8 -1
- package/dist/core/cyclic.d.ts +1 -0
- package/dist/core/cyclic.js +13 -7
- package/dist/core/data-synth.d.ts +3 -0
- package/dist/core/data-synth.js +252 -0
- package/dist/core/data.d.ts +2 -1
- package/dist/core/data.js +223 -24
- package/dist/core/discover.js +3 -1
- package/dist/core/draft.d.ts +19 -0
- package/dist/core/draft.js +53 -0
- package/dist/core/dsl.d.ts +37 -3
- package/dist/core/dsl.js +167 -26
- package/dist/core/effect.d.ts +1 -4
- package/dist/core/effect.js +1 -15
- package/dist/core/exists.d.ts +1 -0
- package/dist/core/exists.js +191 -16
- package/dist/core/extract-c.d.ts +2 -0
- package/dist/core/extract-c.js +169 -22
- package/dist/core/extract-check.d.ts +1 -0
- package/dist/core/extract-check.js +66 -0
- package/dist/core/extract-go-check.d.ts +1 -1
- package/dist/core/extract-go-check.js +2 -1
- package/dist/core/extract-go.d.ts +1 -0
- package/dist/core/extract-go.js +38 -4
- package/dist/core/extract-ir.d.ts +1 -0
- package/dist/core/extract-ir.js +15 -0
- package/dist/core/extract-jvm.d.ts +1 -1
- package/dist/core/extract-jvm.js +2 -0
- package/dist/core/extract-orm.d.ts +12 -0
- package/dist/core/extract-orm.js +244 -0
- package/dist/core/extract-print.js +20 -1
- package/dist/core/extract-py.d.ts +1 -0
- package/dist/core/extract-py.js +1 -1
- package/dist/core/extract-read.d.ts +17 -0
- package/dist/core/extract-read.js +5 -5
- package/dist/core/extract-rs.js +5 -1
- package/dist/core/extract-shapes.js +2 -0
- package/dist/core/extract-sol.d.ts +10 -1
- package/dist/core/extract-sol.js +70 -22
- package/dist/core/extract-step.d.ts +151 -1
- package/dist/core/extract-step.js +1232 -60
- package/dist/core/extract-swift.js +6 -2
- package/dist/core/extract.d.ts +8 -0
- package/dist/core/extract.js +61 -5
- package/dist/core/fiber-run.d.ts +5 -0
- package/dist/core/fiber-run.js +18 -0
- package/dist/core/infer.d.ts +4 -1
- package/dist/core/infer.js +918 -217
- package/dist/core/jvm/JavaReader.java +23 -6
- package/dist/core/jvm/Jvm.java +3 -0
- package/dist/core/jvm/KtReader.java +6 -5
- package/dist/core/laws.d.ts +10 -3
- package/dist/core/laws.js +193 -14
- package/dist/core/machine.d.ts +15 -1
- package/dist/core/machine.js +187 -15
- package/dist/core/nonterm.js +14 -1
- package/dist/core/orm/harness.js +61 -0
- package/dist/core/orm-fixtures/schema.prisma +5 -0
- package/dist/core/py/harness.py +183 -10
- package/dist/core/py/reader.py +234 -40
- package/dist/core/reader-fixtures/README.md +28 -0
- package/dist/core/reader-fixtures/c-693042.cpp +8 -0
- package/dist/core/reader-fixtures/go-685506.go +14 -0
- package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
- package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
- package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
- package/dist/core/reader-fixtures/swift-735726.swift +15 -0
- package/dist/core/reader-fixtures/swift-735990.swift +15 -0
- package/dist/core/reader-fixtures/swift-739158.swift +4 -0
- package/dist/core/reader-fixtures/swift-744834.swift +15 -0
- package/dist/core/reader-fixtures/swift-746946.swift +31 -0
- package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
- package/dist/core/relation.d.ts +1 -1
- package/dist/core/relation.js +29 -2
- package/dist/core/relational.js +4 -2
- package/dist/core/rs/src/main.rs +8 -2
- package/dist/core/sample-cache.d.ts +8 -0
- package/dist/core/sample-cache.js +46 -0
- package/dist/core/security.d.ts +38 -0
- package/dist/core/security.js +88 -0
- package/dist/core/sol/harness.py +57 -4
- package/dist/core/sol-concrete.d.ts +23 -0
- package/dist/core/sol-concrete.js +195 -0
- package/dist/core/solver.js +3 -1
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
- package/dist/core/system.js +1 -1
- package/dist/core/transfer.js +22 -9
- package/dist/core/translate.js +39 -10
- package/dist/core/watch.js +50 -5
- package/dist/interchange/format.js +11 -1
- package/dist/kernel/cdcl.d.ts +5 -0
- package/dist/kernel/cdcl.js +56 -9
- package/dist/kernel/epr.js +108 -26
- package/dist/kernel/kernel.d.ts +29 -1
- package/dist/kernel/kernel.js +325 -62
- package/dist/kernel/model-sequence.d.ts +3 -0
- package/dist/kernel/model-sequence.js +34 -0
- package/dist/kernel/prove.d.ts +10 -3
- package/dist/kernel/prove.js +332 -71
- package/dist/kernel/reader.d.ts +3 -0
- package/dist/kernel/reader.js +101 -14
- package/dist/kernel/share.d.ts +1 -0
- package/dist/kernel/share.js +27 -0
- package/dist/lean-kernel/emit.js +30 -37
- package/dist/lean-kernel/lean-terms.js +5 -0
- package/dist/lean-kernel/library.js +10 -10
- package/package.json +6 -1
package/dist/core/py/reader.py
CHANGED
|
@@ -5,18 +5,23 @@
|
|
|
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, builtins, contextlib, importlib, io, json, os, sys, types
|
|
8
|
+
import ast, builtins, contextlib, functools, importlib, io, json, os, sys, types
|
|
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', 'datetime.datetime.now', 'datetime.timedelta', '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', 'dateutil.relativedelta.relativedelta', 'math.floor', 'math.ceil', 'math.isfinite', 'math.isnan', 'math.isinf', 'threading.Lock', 'threading.RLock', 'asyncio.Lock'}
|
|
13
13
|
# The heads of a subscripted type an alias may stand for (`Mode = Literal[...]`).
|
|
14
14
|
TYPE_HEADS = {'Literal', 'Optional', 'Union', 'Final', 'Annotated', 'dict', 'Dict', 'Mapping', 'MutableMapping', 'defaultdict', 'OrderedDict', 'list', 'List', 'Sequence',
|
|
15
15
|
'set', 'Set', 'frozenset', 'FrozenSet', 'AbstractSet', 'MutableSet'}
|
|
16
16
|
TRANSPARENT = {'staticmethod', 'classmethod', 'property', 'dataclass', 'dataclasses.dataclass', 'override', 'typing.override', 'abstractmethod'}
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
@functools.lru_cache(maxsize=256)
|
|
19
|
+
def source_name(file, root):
|
|
20
|
+
# Stable within a repository, distinct across equal basenames, and shared with the runtime check's source IDs.
|
|
21
|
+
return os.path.relpath(os.path.realpath(file), os.path.realpath(root)).replace(os.sep, '/')
|
|
22
|
+
|
|
23
|
+
def where(file, n, root):
|
|
24
|
+
return f"{source_name(file, root)}:{getattr(n, 'lineno', 0)}:{getattr(n, 'col_offset', 0) + 1}"
|
|
20
25
|
|
|
21
26
|
def text(n):
|
|
22
27
|
try: s = ast.unparse(n)
|
|
@@ -137,6 +142,9 @@ class Reader:
|
|
|
137
142
|
self.local_stack = []
|
|
138
143
|
self.caught = [] # (the names the handlers being read bind their exceptions to)
|
|
139
144
|
self.based, self.supers, self.defs, self.local_imps = set(), [], {}, [] # (the bases read as bases; the bases of the class whose method is read)
|
|
145
|
+
self.class_mros, self.class_attrs, self.class_bound = {}, {}, {}
|
|
146
|
+
self.class_fields, self.class_methods, self.class_rets = {}, {}, {}
|
|
147
|
+
self.class_collections = {}
|
|
140
148
|
|
|
141
149
|
# --- types -------------------------------------------------------------------------------------------------------
|
|
142
150
|
def find_class(self, mod, name, depth=0):
|
|
@@ -179,6 +187,126 @@ class Reader:
|
|
|
179
187
|
imp = m.imports.get(name)
|
|
180
188
|
if imp and imp[0] == 'name': return self.ret_of(imp[1], imp[2], depth + 1)
|
|
181
189
|
return None
|
|
190
|
+
def class_constants(self, cdef):
|
|
191
|
+
"""Own scalar literals and every name that shadows a base's literal. Mutable values are not constants."""
|
|
192
|
+
values, bound, collections, final_methods = {}, set(), set(), set()
|
|
193
|
+
static = not cdef.keywords and not cdef.decorator_list
|
|
194
|
+
for n in cdef.body:
|
|
195
|
+
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
196
|
+
names = {n.name}
|
|
197
|
+
elif isinstance(n, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
|
|
198
|
+
targets = n.targets if isinstance(n, ast.Assign) else [n.target]
|
|
199
|
+
names = {x.id for t in targets for x in ast.walk(t) if isinstance(x, ast.Name) and isinstance(x.ctx, ast.Store)} if not isinstance(n, ast.AnnAssign) or n.value is not None else set()
|
|
200
|
+
elif isinstance(n, ast.Pass) or isinstance(n, ast.Expr) and isinstance(n.value, ast.Constant):
|
|
201
|
+
continue
|
|
202
|
+
else:
|
|
203
|
+
# Control flow, imports and dynamic class-body code may shadow any earlier literal.
|
|
204
|
+
values.clear()
|
|
205
|
+
collections.clear()
|
|
206
|
+
static = False
|
|
207
|
+
continue
|
|
208
|
+
bound.update(names)
|
|
209
|
+
for name in names:
|
|
210
|
+
values.pop(name, None)
|
|
211
|
+
collections.discard(name)
|
|
212
|
+
final_methods.discard(name)
|
|
213
|
+
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)): final_methods.add(n.name)
|
|
214
|
+
target = n.targets[0] if isinstance(n, ast.Assign) and len(n.targets) == 1 else n.target if isinstance(n, ast.AnnAssign) else None
|
|
215
|
+
value = n.value if isinstance(n, (ast.Assign, ast.AnnAssign)) else None
|
|
216
|
+
if isinstance(target, ast.Name) and isinstance(value, ast.Constant) and isinstance(value.value, (int, float, str, bool, type(None))) and not isinstance(value.value, bytes):
|
|
217
|
+
values[target.id] = value.value
|
|
218
|
+
if isinstance(target, ast.Name) and isinstance(value, (ast.List, ast.Tuple, ast.Dict, ast.Set)):
|
|
219
|
+
collections.add(target.id)
|
|
220
|
+
return values, bound, static, collections, final_methods
|
|
221
|
+
|
|
222
|
+
def class_mro(self, q, bases):
|
|
223
|
+
"""Python's C3 order, or no inherited constants if a base/order is not known."""
|
|
224
|
+
if len(set(bases)) != len(bases) or any(self.class_mros.get(b) is None for b in bases): return None
|
|
225
|
+
seqs = [list(self.class_mros[b]) for b in bases] + [list(bases)]
|
|
226
|
+
order = [q]
|
|
227
|
+
while any(seqs):
|
|
228
|
+
seqs = [s for s in seqs if s]
|
|
229
|
+
head = next((s[0] for s in seqs if not any(s[0] in t[1:] for t in seqs)), None)
|
|
230
|
+
if head is None: return None
|
|
231
|
+
order.append(head)
|
|
232
|
+
for s in seqs:
|
|
233
|
+
if s and s[0] == head: s.pop(0)
|
|
234
|
+
return order
|
|
235
|
+
|
|
236
|
+
def qualified(self, mod, node):
|
|
237
|
+
n = dotted(node)
|
|
238
|
+
if not n: return ''
|
|
239
|
+
h, *tail = n.split('.')
|
|
240
|
+
imp = mod.imports.get(h)
|
|
241
|
+
if not imp: return n
|
|
242
|
+
return '.'.join(([imp[1], imp[2]] if imp[0] == 'name' else [imp[1]]) + tail)
|
|
243
|
+
def orm_kind(self, mod, cdef, seen=None):
|
|
244
|
+
seen = set() if seen is None else seen
|
|
245
|
+
tag = (mod.name, cdef.name)
|
|
246
|
+
if tag in seen: return None
|
|
247
|
+
seen.add(tag)
|
|
248
|
+
for b in cdef.bases:
|
|
249
|
+
q = self.qualified(mod, b)
|
|
250
|
+
if q == 'django.db.models.Model': return 'django'
|
|
251
|
+
if q in ('sqlalchemy.orm.DeclarativeBase', 'sqlalchemy.orm.decl_api.DeclarativeBase'): return 'sqlalchemy'
|
|
252
|
+
name = dotted(b)
|
|
253
|
+
v = mod.consts.get(name)
|
|
254
|
+
if isinstance(v, ast.Call) and self.qualified(mod, v.func) in ('sqlalchemy.orm.declarative_base', 'sqlalchemy.ext.declarative.declarative_base'): return 'sqlalchemy'
|
|
255
|
+
hit = self.find_class(mod, name) if name else None
|
|
256
|
+
if hit:
|
|
257
|
+
k = self.orm_kind(*hit, seen)
|
|
258
|
+
if k: return k
|
|
259
|
+
return None
|
|
260
|
+
def orm_base_safe(self, mod, base, framework, seen=None):
|
|
261
|
+
"""Admit only framework bases and empty declarative scaffolding, never a mixin/MRO we omit."""
|
|
262
|
+
q = self.qualified(mod, base)
|
|
263
|
+
if framework == 'django': return q == 'django.db.models.Model'
|
|
264
|
+
if q in ('sqlalchemy.orm.DeclarativeBase', 'sqlalchemy.orm.decl_api.DeclarativeBase'): return True
|
|
265
|
+
name = dotted(base)
|
|
266
|
+
v = mod.consts.get(name)
|
|
267
|
+
if isinstance(v, ast.Call) and self.qualified(mod, v.func) in ('sqlalchemy.orm.declarative_base', 'sqlalchemy.ext.declarative.declarative_base'):
|
|
268
|
+
return not v.args and not v.keywords
|
|
269
|
+
hit = self.find_class(mod, name) if name else None
|
|
270
|
+
if not hit: return False
|
|
271
|
+
bm, cls = hit
|
|
272
|
+
seen = set() if seen is None else seen
|
|
273
|
+
key = (bm.name, cls.name)
|
|
274
|
+
if key in seen or cls.decorator_list or cls.keywords: return False
|
|
275
|
+
seen.add(key)
|
|
276
|
+
for n in cls.body:
|
|
277
|
+
if isinstance(n, ast.Pass) or (isinstance(n, ast.Expr) and isinstance(n.value, ast.Constant) and isinstance(n.value.value, str)): continue
|
|
278
|
+
if isinstance(n, ast.Assign) and len(n.targets) == 1 and isinstance(n.targets[0], ast.Name) and n.targets[0].id == '__abstract__' and isinstance(n.value, ast.Constant) and n.value.value is True: continue
|
|
279
|
+
return False
|
|
280
|
+
return bool(cls.bases) and all(self.orm_base_safe(bm, b, framework, seen) for b in cls.bases)
|
|
281
|
+
def orm_field(self, node, mod, framework):
|
|
282
|
+
target = node.targets[0] if isinstance(node, ast.Assign) and len(node.targets) == 1 else node.target if isinstance(node, ast.AnnAssign) else None
|
|
283
|
+
if not isinstance(target, ast.Name) or not isinstance(node.value, ast.Call): return None
|
|
284
|
+
call = node.value; q = self.qualified(mod, call.func)
|
|
285
|
+
kw = {k.arg: k.value for k in call.keywords}
|
|
286
|
+
true = lambda n: isinstance(kw.get(n), ast.Constant) and kw[n].value is True
|
|
287
|
+
if framework == 'django':
|
|
288
|
+
if not q.startswith('django.db.models.'): return None
|
|
289
|
+
kind = q.rsplit('.', 1)[-1]
|
|
290
|
+
types = {'AutoField': 'int', 'BigAutoField': 'int', 'SmallAutoField': 'int', 'IntegerField': 'int', 'BigIntegerField': 'int', 'SmallIntegerField': 'int', 'PositiveIntegerField': 'int', 'PositiveSmallIntegerField': 'int', 'PositiveBigIntegerField': 'int', 'BooleanField': 'bool', 'CharField': 'str', 'TextField': 'str'}
|
|
291
|
+
t = {'k': types[kind]} if kind in types else {'k': 'opaque', 'why': 'ORM field ' + q + ' is outside the subset'}
|
|
292
|
+
if kind == 'DateTimeField': t = {'k': 'int', 'unit': 'datetime-utc'}
|
|
293
|
+
nullable = true('null')
|
|
294
|
+
elif q in ('sqlalchemy.Column', 'sqlalchemy.orm.mapped_column'):
|
|
295
|
+
ty = next((a for a in call.args if not isinstance(a, ast.Constant)), None)
|
|
296
|
+
tq = self.qualified(mod, ty.func if isinstance(ty, ast.Call) else ty)
|
|
297
|
+
types = {'Integer': 'int', 'BigInteger': 'int', 'SmallInteger': 'int', 'Boolean': 'bool', 'String': 'str', 'Text': 'str'}
|
|
298
|
+
kind = tq.rsplit('.', 1)[-1]
|
|
299
|
+
t = {'k': types[kind]} if tq.startswith('sqlalchemy.') and kind in types else None
|
|
300
|
+
ann = node.annotation if isinstance(node, ast.AnnAssign) else None
|
|
301
|
+
if t is None and q == 'sqlalchemy.orm.mapped_column' and isinstance(ann, ast.Subscript) and self.qualified(mod, ann.value) == 'sqlalchemy.orm.Mapped': t = self.ty(ann.slice, mod)
|
|
302
|
+
if tq == 'sqlalchemy.DateTime':
|
|
303
|
+
aware = isinstance(ty, ast.Call) and any(k.arg == 'timezone' and isinstance(k.value, ast.Constant) and k.value.value is True for k in ty.keywords)
|
|
304
|
+
t = {'k': 'int', 'unit': 'datetime-utc' if aware else 'datetime-naive'}
|
|
305
|
+
t = t or {'k': 'opaque', 'why': 'ORM column ' + (tq or q) + ' is outside the subset'}
|
|
306
|
+
nullable = true('nullable') or ('nullable' not in kw and q == 'sqlalchemy.Column' and not true('primary_key'))
|
|
307
|
+
else: return None
|
|
308
|
+
if nullable and t['k'] != 'opt': t = {'k': 'opt', 'of': t}
|
|
309
|
+
return {'name': target.id, 't': t, 'primary': true('primary_key')}
|
|
182
310
|
def rec_of(self, mod, cdef, base=False):
|
|
183
311
|
"""A class as a record type: its fields (annotations, its bases' first), its methods (to resolve calls). A class
|
|
184
312
|
of the file, or a base of one (another module's too: its methods are the class's own), has its methods read."""
|
|
@@ -189,12 +317,20 @@ class Reader:
|
|
|
189
317
|
self.defs[q] = (mod, cdef)
|
|
190
318
|
self.recs[q] = None # (being read)
|
|
191
319
|
fields, methods, bases, kinds, rets = [], {}, [], set(), {}
|
|
320
|
+
own_fields, own_methods, own_rets = {}, {}, {}
|
|
321
|
+
cattrs, bound, static, collections, final_methods = self.class_constants(cdef)
|
|
322
|
+
collections = {name: q for name in collections}
|
|
323
|
+
orm = self.orm_kind(mod, cdef)
|
|
324
|
+
if orm: static = False
|
|
192
325
|
for b in cdef.bases:
|
|
193
326
|
bn = dotted(b.value if isinstance(b, ast.Subscript) else b)
|
|
194
|
-
if
|
|
195
|
-
if bn in ('
|
|
196
|
-
if bn in ('
|
|
197
|
-
if bn in ('
|
|
327
|
+
if orm: continue # ORM inheritance is schema, never an ordinary constructor.
|
|
328
|
+
if bn in ('TypedDict', 'typing.TypedDict', 'typing_extensions.TypedDict'): kinds.add('typeddict'); static = False; continue
|
|
329
|
+
if bn in ('BaseModel', 'pydantic.BaseModel'): kinds.add('pydantic'); static = False; continue
|
|
330
|
+
if bn in ('Protocol', 'typing.Protocol', 'ABC', 'abc.ABC'): kinds.add('protocol'); static = False; continue
|
|
331
|
+
if bn in ('Generic', 'object', 'Exception'):
|
|
332
|
+
if bn != 'object': static = False
|
|
333
|
+
continue
|
|
198
334
|
hit = self.find_class(mod, bn.split('.')[-1]) if bn else None
|
|
199
335
|
if hit:
|
|
200
336
|
bq = self.rec_of(*hit, base=base or mod.path == self.file)
|
|
@@ -206,7 +342,9 @@ class Reader:
|
|
|
206
342
|
if not any(g['name'] == f['name'] for g in fields): fields.append(f)
|
|
207
343
|
for m, fid in br['methods'].items(): methods[m] = fid
|
|
208
344
|
rets.update(br.get('rets', {}))
|
|
209
|
-
elif bn:
|
|
345
|
+
elif bn:
|
|
346
|
+
kinds.add('outside-base:' + bn)
|
|
347
|
+
static = False
|
|
210
348
|
dataclass = any((dotted(d.func if isinstance(d, ast.Call) else d) or '').split('.')[-1] == 'dataclass' for d in cdef.decorator_list)
|
|
211
349
|
frozen = any(isinstance(d, ast.Call) and any(k.arg == 'frozen' and isinstance(k.value, ast.Constant) and k.value.value for k in d.keywords) for d in cdef.decorator_list)
|
|
212
350
|
# (a dataclass whose == is its fields' unless eq=False says it is identity)
|
|
@@ -214,7 +352,7 @@ class Reader:
|
|
|
214
352
|
total = not any(k.arg == 'total' and isinstance(k.value, ast.Constant) and k.value.value is False for k in cdef.keywords)
|
|
215
353
|
# The fields its __init__ sets: annotated there, or set from an annotated argument (a class of another module whose
|
|
216
354
|
# fields aren't declared on the class).
|
|
217
|
-
init = next((n for n in cdef.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == '__init__'), None)
|
|
355
|
+
init = next((n for n in reversed(cdef.body) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == '__init__'), None) if '__init__' in final_methods else None
|
|
218
356
|
if init is not None:
|
|
219
357
|
anns = {x.arg: x.annotation for x in init.args.args + init.args.kwonlyargs if x.annotation is not None}
|
|
220
358
|
for n in ast.walk(init):
|
|
@@ -228,32 +366,84 @@ class Reader:
|
|
|
228
366
|
# `x or DEFAULT`: the argument's type, never None
|
|
229
367
|
name, t = n.targets[0].attr, self.ty(anns[v.values[0].id], mod)
|
|
230
368
|
if t['k'] == 'opt': t = t['of']
|
|
231
|
-
if t is not None
|
|
232
|
-
|
|
369
|
+
if t is not None:
|
|
370
|
+
own_fields[name] = {'name': name, 't': t, 'init': True}
|
|
371
|
+
fields = [g for g in fields if g['name'] != name] + [own_fields[name]]
|
|
233
372
|
for n in cdef.body:
|
|
234
|
-
|
|
235
|
-
if
|
|
236
|
-
|
|
237
|
-
|
|
373
|
+
of = self.orm_field(n, mod, orm) if orm else None
|
|
374
|
+
if of:
|
|
375
|
+
fields = [g for g in fields if g['name'] != of['name']] + [of]
|
|
376
|
+
own_fields[of['name']] = of
|
|
377
|
+
if not of and isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name):
|
|
238
378
|
ann = n.annotation
|
|
239
379
|
if dotted(ann.value if isinstance(ann, ast.Subscript) else ann) in ('ClassVar', 'typing.ClassVar'): continue
|
|
240
380
|
f = {'name': n.target.id, 't': self.ty(ann, mod)}
|
|
241
381
|
if n.value is not None: f['dflt'] = self.expr(n.value, mod)
|
|
242
382
|
fields = [g for g in fields if g['name'] != f['name']] + [f]
|
|
383
|
+
own_fields[f['name']] = f
|
|
243
384
|
elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
244
|
-
if n.returns is not None:
|
|
245
|
-
|
|
385
|
+
if n.returns is not None:
|
|
386
|
+
rets[n.name] = own_rets[n.name] = self.ty(n.returns, mod)
|
|
387
|
+
else:
|
|
388
|
+
rets.pop(n.name, None)
|
|
389
|
+
own_rets.pop(n.name, None)
|
|
246
390
|
if mod.path == self.file or base:
|
|
247
|
-
fid = f"{
|
|
391
|
+
fid = f"{q}.{n.name}"
|
|
248
392
|
# (a base's method read where its module is: its positions in its own file, super() its own bases')
|
|
249
|
-
file, self.file, sup, self.supers = self.file, mod.path, self.supers, bases
|
|
393
|
+
file, self.file, sup, self.supers, dfn, self.defining = self.file, mod.path, self.supers, bases, getattr(self, 'defining', None), q
|
|
250
394
|
try: self.funcs[fid] = self.func(n, mod, cdef.name, fid)
|
|
251
|
-
finally: self.file, self.supers = file, sup
|
|
252
|
-
methods[n.name] = fid
|
|
253
|
-
else: methods[n.name] = None # another module's method: not read
|
|
254
|
-
|
|
395
|
+
finally: self.file, self.supers, self.defining = file, sup, dfn
|
|
396
|
+
methods[n.name] = own_methods[n.name] = fid
|
|
397
|
+
else: methods[n.name] = own_methods[n.name] = None # another module's method: not read
|
|
398
|
+
# Only the last runtime binding is callable. An annotation without a value
|
|
399
|
+
# does not bind; an assignment after a method removes its stale metadata.
|
|
400
|
+
for name in bound - final_methods:
|
|
401
|
+
methods.pop(name, None)
|
|
402
|
+
own_methods.pop(name, None)
|
|
403
|
+
rets.pop(name, None)
|
|
404
|
+
own_rets.pop(name, None)
|
|
405
|
+
self.class_attrs[q], self.class_bound[q] = cattrs, bound
|
|
406
|
+
self.class_collections[q] = collections
|
|
407
|
+
self.class_fields[q], self.class_methods[q], self.class_rets[q] = own_fields, own_methods, own_rets
|
|
408
|
+
order = self.class_mro(q, bases) if static else None
|
|
409
|
+
self.class_mros[q] = order
|
|
410
|
+
if order is not None:
|
|
411
|
+
cattrs, methods, rets, selected_fields, collections = {}, {}, {}, {}, {}
|
|
412
|
+
for owner in reversed(order):
|
|
413
|
+
# Only declarations belong to an owner. A flattened base record can
|
|
414
|
+
# select an ancestor too early in a diamond, or the wrong direct base.
|
|
415
|
+
for name in self.class_bound[owner]:
|
|
416
|
+
cattrs.pop(name, None)
|
|
417
|
+
collections.pop(name, None)
|
|
418
|
+
methods.pop(name, None)
|
|
419
|
+
rets.pop(name, None)
|
|
420
|
+
cattrs.update(self.class_attrs[owner])
|
|
421
|
+
collections.update(self.class_collections[owner])
|
|
422
|
+
methods.update(self.class_methods[owner])
|
|
423
|
+
rets.update(self.class_rets[owner])
|
|
424
|
+
selected_fields.update(self.class_fields[owner])
|
|
425
|
+
fields = list(selected_fields.values())
|
|
426
|
+
# A scalar selected by attribute lookup also shadows an inherited method/property of that name.
|
|
427
|
+
for name in cattrs:
|
|
428
|
+
methods.pop(name, None)
|
|
429
|
+
rets.pop(name, None)
|
|
430
|
+
r = {'name': q, 'short': cdef.name, 'fields': fields, 'methods': methods, 'bases': bases, 'mro': order, 'declared': sorted(bound), 'p': where(mod.path, cdef, self.repo.root), 'cattrs': cattrs, 'classCollections': collections,
|
|
255
431
|
'kinds': sorted(kinds | ({'dataclass'} if dataclass else set()) | ({'frozen'} if frozen else set()) | (set() if total else {'partial'})),
|
|
256
432
|
'own': mod.path == self.file, 'module': mod.name, **({'rets': rets} if rets else {})}
|
|
433
|
+
if orm:
|
|
434
|
+
keys = [f['name'] for f in fields if f.pop('primary', False)]
|
|
435
|
+
if not keys and orm == 'django':
|
|
436
|
+
keys = ['id']; fields.insert(0, {'name': 'id', 't': {'k': 'int'}})
|
|
437
|
+
why = '' if len(keys) == 1 else 'ORM requires one explicit primary key'
|
|
438
|
+
if any(not self.orm_base_safe(mod, b, orm) for b in cdef.bases): why = 'inherited ORM schema or behavior is outside the table boundary'
|
|
439
|
+
if cdef.decorator_list or cdef.keywords: why = 'decorated ORM classes or custom metaclasses are outside the table boundary'
|
|
440
|
+
# Plain display bodies are not erased: explicit calls still read their bodies.
|
|
441
|
+
# Implicit conversions of these records are refused by the step reader.
|
|
442
|
+
def display(n):
|
|
443
|
+
return isinstance(n, ast.FunctionDef) and n.name in ('__str__', '__repr__') and not n.decorator_list and len(n.args.posonlyargs + n.args.args) == 1 and not (n.args.defaults or n.args.kwonlyargs or n.args.vararg or n.args.kwarg)
|
|
444
|
+
if any(isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and (n.decorator_list or (n.name.startswith('__') and not display(n))) for n in cdef.body): why = 'decorated ORM methods or custom magic methods are outside the table boundary'
|
|
445
|
+
if any(isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'objects' for t in n.targets) for n in cdef.body): why = 'custom ORM managers are outside the table boundary'
|
|
446
|
+
r['orm'] = {'framework': orm, 'key': keys[0] if len(keys) == 1 else '', 'why': why}
|
|
257
447
|
self.recs[q] = r
|
|
258
448
|
return q
|
|
259
449
|
def ty(self, a, mod):
|
|
@@ -281,6 +471,7 @@ class Reader:
|
|
|
281
471
|
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}
|
|
282
472
|
return {'k': 'opaque', 'why': f"{text(a)}"}
|
|
283
473
|
n = dotted(a)
|
|
474
|
+
if self.qualified(mod, a) == 'sqlalchemy.orm.Session': return {'k': 'opaque', 'why': '$orm-session'}
|
|
284
475
|
if n in ('int',): return {'k': 'int'}
|
|
285
476
|
if n in ('float',): return {'k': 'float'}
|
|
286
477
|
if n in ('bool',): return {'k': 'bool'}
|
|
@@ -366,14 +557,14 @@ class Reader:
|
|
|
366
557
|
if a.vararg: params.append({'name': a.vararg.arg, 't': {'k': 'opaque', 'why': '*args'}, 'star': 1})
|
|
367
558
|
if a.kwarg: params.append({'name': a.kwarg.arg, 't': {'k': 'opaque', 'why': '**kwargs'}, 'star': 2})
|
|
368
559
|
body = self.block(n.body, mod)
|
|
369
|
-
return {'id': fid, 'name': n.name, **({'cls': cls} if cls else {}), 'p': where(self.file, n), 'span': [
|
|
560
|
+
return {'id': fid, 'name': n.name, **({'cls': cls} if cls else {}), 'p': where(self.file, n, self.repo.root), 'span': [source_name(self.file, self.repo.root), n.lineno, n.end_lineno],
|
|
370
561
|
'params': params, 'ret': self.ty(n.returns, mod), 'body': body, 'async': isinstance(n, ast.AsyncFunctionDef), 'decorators': decs, 'static': static}
|
|
371
562
|
finally:
|
|
372
563
|
self.local_stack.pop()
|
|
373
564
|
self.local_imps.pop()
|
|
374
565
|
def decorator(self, d):
|
|
375
566
|
f = d.func if isinstance(d, ast.Call) else d
|
|
376
|
-
return {'name': dotted(f) or text(f), 'text': text(d), 'p': where(self.file, d)}
|
|
567
|
+
return {'name': dotted(f) or text(f), 'text': text(d), 'p': where(self.file, d, self.repo.root)}
|
|
377
568
|
def locals_of(self, fn):
|
|
378
569
|
out = {x.arg for x in fn.args.posonlyargs + fn.args.args + fn.args.kwonlyargs}
|
|
379
570
|
if fn.args.vararg: out.add(fn.args.vararg.arg)
|
|
@@ -392,7 +583,7 @@ class Reader:
|
|
|
392
583
|
out.append(r)
|
|
393
584
|
return out
|
|
394
585
|
def stmt(self, s, mod):
|
|
395
|
-
p = where(self.file, s)
|
|
586
|
+
p = where(self.file, s, self.repo.root)
|
|
396
587
|
E = lambda x: self.expr(x, mod)
|
|
397
588
|
if isinstance(s, ast.Expr):
|
|
398
589
|
if isinstance(s.value, ast.Constant) and (isinstance(s.value.value, str) or s.value.value is Ellipsis): return [] # a docstring, or `...`
|
|
@@ -443,7 +634,9 @@ class Reader:
|
|
|
443
634
|
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)}]
|
|
444
635
|
if isinstance(s, ast.Continue): return [{'s': 'continue', 'p': p}]
|
|
445
636
|
if isinstance(s, ast.Break): return [{'s': 'break', 'p': p}]
|
|
446
|
-
|
|
637
|
+
# (a while loop: read where its passes take the first items of the state's ordered collections, as a fold)
|
|
638
|
+
if isinstance(s, ast.While): return [{'s': 'while', 'p': p, 'c': E(s.test), 'body': self.block(s.body, mod), 'els': self.block(s.orelse, mod)}]
|
|
639
|
+
if isinstance(s, ast.AsyncFor): return [{'s': 'no', 'p': p, 'why': "a loop (async for)"}]
|
|
447
640
|
if type(s).__name__ == 'TryStar': return [{'s': 'no', 'p': p, 'why': 'try/except* (exception groups)'}]
|
|
448
641
|
if isinstance(s, ast.Try):
|
|
449
642
|
hs = []
|
|
@@ -453,7 +646,7 @@ class Reader:
|
|
|
453
646
|
self.caught.append(h.name)
|
|
454
647
|
try: body = self.block(h.body, mod)
|
|
455
648
|
finally: self.caught.pop()
|
|
456
|
-
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])]}),
|
|
649
|
+
hs.append({'p': where(self.file, h, self.repo.root), '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])]}),
|
|
457
650
|
**({'open': True} if cs and cs[0][1] else {}), **({'as': h.name} if h.name else {}), 'body': body})
|
|
458
651
|
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)}]
|
|
459
652
|
if isinstance(s, (ast.Global, ast.Nonlocal)): return [{'s': 'no', 'p': p, 'why': f"{type(s).__name__.lower()} (a variable every call shares)"}]
|
|
@@ -485,7 +678,7 @@ class Reader:
|
|
|
485
678
|
out += [n for n in bs if n not in out]; op = op or bo
|
|
486
679
|
return out, op
|
|
487
680
|
def target(self, t, mod):
|
|
488
|
-
p = where(self.file, t)
|
|
681
|
+
p = where(self.file, t, self.repo.root)
|
|
489
682
|
if isinstance(t, ast.Name): return {'e': 'var', 'n': t.id, 'p': p}
|
|
490
683
|
if isinstance(t, ast.Attribute): return {'e': 'get', 'x': self.expr(t.value, mod), 'f': t.attr, 'p': p, 'text': text(t)}
|
|
491
684
|
if isinstance(t, ast.Subscript): return {'e': 'idx', 'x': self.expr(t.value, mod), 'i': self.expr(t.slice, mod), 'p': p, 'text': text(t)}
|
|
@@ -535,7 +728,7 @@ class Reader:
|
|
|
535
728
|
if r.get('e') == 'no' and 'names' not in r: r['names'] = mentioned(x)
|
|
536
729
|
return r
|
|
537
730
|
def expr1(self, x, mod):
|
|
538
|
-
p = where(self.file, x)
|
|
731
|
+
p = where(self.file, x, self.repo.root)
|
|
539
732
|
E = lambda y: self.expr(y, mod)
|
|
540
733
|
if isinstance(x, ast.Constant):
|
|
541
734
|
v = x.value
|
|
@@ -549,8 +742,18 @@ class Reader:
|
|
|
549
742
|
return {'e': 'no', 'why': f"{text(x)}: a constant outside the subset", 'p': p}
|
|
550
743
|
if isinstance(x, ast.Name): return self.name(x.id, mod, p)
|
|
551
744
|
if isinstance(x, ast.Attribute):
|
|
745
|
+
if isinstance(x.value, ast.Call) and isinstance(x.value.func, ast.Name) and x.value.func.id == 'super':
|
|
746
|
+
args, owner = x.value.args, getattr(self, 'defining', None)
|
|
747
|
+
valid = not args or (len(args) == 2 and all(isinstance(a, ast.Name) for a in args) and owner and args[0].id == owner.rsplit('.', 1)[-1] and args[1].id == 'self')
|
|
748
|
+
if not owner or not valid or x.value.keywords:
|
|
749
|
+
return {'e': 'no', 'why': f"{text(x)}: super outside its defining instance method", 'p': p}
|
|
750
|
+
# Resolve after this owner in the receiver's MRO, not in the owner's
|
|
751
|
+
# direct bases: cooperative super may dispatch to a sibling mixin.
|
|
752
|
+
return {'e': 'get', 'x': {'e': 'var', 'n': 'self', 'p': p}, 'f': x.attr, 'superFrom': owner, 'p': p, 'text': text(x)}
|
|
552
753
|
d = dotted(x)
|
|
553
754
|
base = d.split('.')[0] if d else None
|
|
755
|
+
q = self.qualified(mod, x)
|
|
756
|
+
if q in KNOWN and not (self.local_stack and base in self.local_stack[-1]): return {'e': 'lib', 'q': q, 'p': p}
|
|
554
757
|
# (a literal constant of another module of the repository, `boat.BRING_UP`: its value, as the module's own
|
|
555
758
|
# constants are read; what the module is set to at import, the check importing it as it ships)
|
|
556
759
|
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
|
|
@@ -583,15 +786,6 @@ class Reader:
|
|
|
583
786
|
if isinstance(x, ast.IfExp): return {'e': 'ite', 'c': E(x.test), 'a': E(x.body), 'b': E(x.orelse), 'p': p}
|
|
584
787
|
if isinstance(x, ast.Await): return {'e': 'await', 'x': E(x.value), 'p': p}
|
|
585
788
|
if isinstance(x, ast.Call):
|
|
586
|
-
# super().m(...): the first base (in the order its bases are listed, theirs after) whose m is read, on self;
|
|
587
|
-
# super().__init__() where no base has one: object's, nothing
|
|
588
|
-
fx = x.func
|
|
589
|
-
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:
|
|
590
|
-
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)
|
|
591
|
-
if mid is False and fx.attr == '__init__' and not x.args and not x.keywords: return {'e': 'none', 'p': p}
|
|
592
|
-
if not mid: return {'e': 'no', 'why': f"{text(x)}: a base's method not read", 'p': p}
|
|
593
|
-
return {'e': 'call', 'f': {'e': 'get', 'x': {'e': 'var', 'n': 'self', 'p': p}, 'f': fx.attr, 'sup': mid, 'p': p, 'text': text(fx)},
|
|
594
|
-
'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)}
|
|
595
789
|
f = E(x.func)
|
|
596
790
|
if f.get('e') == 'ext' and f.get('q') in KNOWN: f = {'e': 'lib', 'q': f['q'], 'p': f['p']}
|
|
597
791
|
# (a class of the repository made here: its methods read, its __init__ the code that makes it)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Reader-fuzz regressions
|
|
2
|
+
|
|
3
|
+
These are the exact mutated sources captured by `READER_FUZZ_SHOW=1`, with
|
|
4
|
+
`READER_FUZZ_N=2`, on base 9b62ecf. Each filename names the language and seed.
|
|
5
|
+
The TypeScript source has a `.txt` suffix so the repository typecheck does not
|
|
6
|
+
try to compile intentionally invalid syntax. Tests copy JVM/Go sources into
|
|
7
|
+
isolated temporary projects so sibling fixtures cannot affect resolution.
|
|
8
|
+
|
|
9
|
+
- Swift 735726, 739158, 744834: native reader recovery exceeded 300 seconds.
|
|
10
|
+
- Swift 735990, 746946: the native reader returned, but `swift build` timed out
|
|
11
|
+
twice. Reproduced with a diagnostic 30-second build limit; the archived
|
|
12
|
+
treadmill used the default 900 seconds per attempt.
|
|
13
|
+
- JVM 737430: Kotlin PSI recovery exceeded 300 seconds.
|
|
14
|
+
- JVM 724362: a missing `if` branch reached `where(null)`.
|
|
15
|
+
- JVM 765282: a nameless function reached `Set.of(...).contains(null)`.
|
|
16
|
+
- TypeScript 673062: an empty extends clause reached `h.types[0].expression`.
|
|
17
|
+
- Go 685506: a return value in a zero-result function reached `results[0].t`.
|
|
18
|
+
- C++ 693042: a narrowing initializer introduced division, which kernel start
|
|
19
|
+
expressions do not permit (they read only parameters, not functions).
|
|
20
|
+
|
|
21
|
+
Native reader depth guards are deliberately conservative text resource limits:
|
|
22
|
+
32 nested delimiter characters, **including strings and comments**. Refusing
|
|
23
|
+
that resource limit does not assert that a source is syntactically invalid.
|
|
24
|
+
Swift also limits each build-check attempt to 60 seconds (or the smaller
|
|
25
|
+
`GDP_COMPILE_S` setting). Compiler failure remains a failed check, not evidence
|
|
26
|
+
that the source differs from the extracted rule. No kernel admission changed.
|
|
27
|
+
|
|
28
|
+
Original replay logs: `runs/repro-2/` and `runs/compiler-repro/`.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
package demo
|
|
2
|
+
|
|
3
|
+
data class Budget(val limit: Int, val spent: Int = 0) {
|
|
4
|
+
init { limit.takeIf { it >= 0 }.let { requireNotNull(it) { "limit" } } }
|
|
5
|
+
fun spend(n: Int): Budget = if (n < 0 || spent + n > limit) else copy(spent = spent + n)
|
|
6
|
+
fun reset(): Budget = copy(spent = 0)
|
|
7
|
+
fun left(): Int = limit - spent
|
|
8
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
package demo
|
|
2
|
+
|
|
3
|
+
data class Budget(val limit: Int, val spent: Int = 0) {
|
|
4
|
+
init { limit.takeIf { it >= 1 }.let { requireNotNull(it) { "limit" } } }
|
|
5
|
+
fun spend(n: Int): Budget = if (n <(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( 0 || spent + n > limit) this else copy(spent = spent + n)
|
|
6
|
+
fun left(): Int = limit - spent
|
|
7
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// An actor: each method one step (it has no suspension point), a guard, an Int's trap.
|
|
2
|
+
actor Tally {
|
|
3
|
+
private var n = 0
|
|
4
|
+
let cap: Int
|
|
5
|
+
|
|
6
|
+
init(cap: Int) { self.cap = cap }
|
|
7
|
+
|
|
8
|
+
func add(_ k: Int) -> Bool {
|
|
9
|
+
guard k > 0, n + k <= cap else {[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ return false }
|
|
10
|
+
n += k
|
|
11
|
+
return true
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
func reset() { n = 0 }
|
|
15
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// An actor: each method one step (it has no suspension point), a guard, an Int's trap.
|
|
2
|
+
actor Tally {
|
|
3
|
+
private var n = 0
|
|
4
|
+
let cap: Int
|
|
5
|
+
|
|
6
|
+
init(cap: Int) { self.cap = cap }
|
|
7
|
+
|
|
8
|
+
func add(_ k: Int) -> Bool {
|
|
9
|
+
guard k > 0, n + k <=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[[[se { return false }
|
|
10
|
+
n += k
|
|
11
|
+
return true
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
func reset() { n = 0 }
|
|
15
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// PREDICTION: refused; LAW: r.law('n stays zero', ({n}) => n.eq(0))
|
|
2
|
+
protocol Store {
|
|
3
|
+
func get(_ key: String) -> Int?
|
|
4
|
+
func set(_ key: String, value: Int)
|
|
5
|
+
}
|
|
6
|
+
final class Meter {
|
|
7
|
+
let a: Store
|
|
8
|
+
let b: Store[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
|
|
9
|
+
var n = 0
|
|
10
|
+
init(a: Store, b: Store) { self.a = a; self.b = b }
|
|
11
|
+
func tick() {
|
|
12
|
+
a.set("k", value: 1)
|
|
13
|
+
n = b.get("k") ?? 0
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// The boundary inferred: two injected protocols (a counter called by a key, held as a store; a flag source whose
|
|
2
|
+
// limit() is answered by the request over its declared Int), the entry inferred, a dictionary keyed by a String in the
|
|
3
|
+
// state.
|
|
4
|
+
protocol Counter {
|
|
5
|
+
func get(_ key: String) -> Int?
|
|
6
|
+
func set(_ key: String, value: Int)
|
|
7
|
+
}
|
|
8
|
+
protocol Flags {
|
|
9
|
+
func limit() -> Int
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
final class Limiter {
|
|
13
|
+
private let counter: Counter
|
|
14
|
+
private let flags: Flags
|
|
15
|
+
private var denied: [String: Int] = [:]
|
|
16
|
+
|
|
17
|
+
init(counter: Counter, flags: Flags) {
|
|
18
|
+
self.counter = counter
|
|
19
|
+
self.flags = flags
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
func allow(_ user: String) -> Bool {
|
|
23
|
+
let used = counter.get("hits:\(user)") ?? 0
|
|
24
|
+
guard used < flags.limit() e[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[lse {
|
|
25
|
+
denied[user, default: 0] += 1
|
|
26
|
+
return false
|
|
27
|
+
}
|
|
28
|
+
counter.set("hits:\(user)", value: used + 1)
|
|
29
|
+
return true
|
|
30
|
+
}
|
|
31
|
+
}
|
package/dist/core/relation.d.ts
CHANGED