gdp-wired 0.44.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 +445 -38
- package/dist/core/calendar.d.ts +29 -0
- package/dist/core/calendar.js +82 -0
- package/dist/core/check.js +3 -2
- package/dist/core/cli.d.ts +4 -0
- package/dist/core/cli.js +335 -39
- package/dist/core/compose.js +3 -1
- package/dist/core/counts.d.ts +5 -2
- package/dist/core/counts.js +335 -88
- 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 +8 -2
- package/dist/core/data.js +1113 -172
- 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 +39 -3
- package/dist/core/dsl.js +250 -31
- package/dist/core/effect-prims.js +2 -2
- package/dist/core/effect.d.ts +1 -4
- package/dist/core/effect.js +1 -15
- package/dist/core/ex/reader.exs +17 -1
- package/dist/core/exists.d.ts +16 -1
- package/dist/core/exists.js +447 -50
- package/dist/core/extract-c.d.ts +2 -0
- package/dist/core/extract-c.js +185 -31
- package/dist/core/extract-check.d.ts +7 -0
- package/dist/core/extract-check.js +115 -3
- package/dist/core/extract-ex.js +3 -3
- package/dist/core/extract-go-check.d.ts +1 -1
- package/dist/core/extract-go-check.js +21 -13
- package/dist/core/extract-go.d.ts +1 -0
- package/dist/core/extract-go.js +58 -9
- 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 +65 -14
- package/dist/core/extract-orm.d.ts +12 -0
- package/dist/core/extract-orm.js +244 -0
- package/dist/core/extract-print.js +23 -1
- package/dist/core/extract-py.d.ts +1 -0
- package/dist/core/extract-py.js +4 -4
- package/dist/core/extract-rb.js +3 -3
- package/dist/core/extract-read.d.ts +25 -0
- package/dist/core/extract-read.js +60 -5
- package/dist/core/extract-rs.js +22 -20
- package/dist/core/extract-shapes.js +22 -0
- package/dist/core/extract-sol.d.ts +10 -1
- package/dist/core/extract-sol.js +89 -30
- package/dist/core/extract-step.d.ts +201 -4
- package/dist/core/extract-step.js +1514 -111
- package/dist/core/extract-swift.js +24 -13
- package/dist/core/extract.d.ts +9 -0
- package/dist/core/extract.js +88 -7
- package/dist/core/fiber-run.d.ts +5 -0
- package/dist/core/fiber-run.js +18 -0
- package/dist/core/fresh.d.ts +2 -2
- package/dist/core/fresh.js +7 -3
- package/dist/core/go/reader.go +7 -1
- package/dist/core/infer.d.ts +4 -1
- package/dist/core/infer.js +1020 -246
- package/dist/core/jvm/JavaReader.java +33 -8
- package/dist/core/jvm/Jvm.java +20 -1
- package/dist/core/jvm/KtReader.java +59 -6
- package/dist/core/laws.d.ts +10 -3
- package/dist/core/laws.js +193 -14
- package/dist/core/machine.d.ts +16 -3
- package/dist/core/machine.js +212 -28
- 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 +260 -21
- package/dist/core/py/reader.py +278 -39
- package/dist/core/rb/reader.rb +52 -5
- 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 +18 -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 +63 -7
- package/dist/core/sol-concrete.d.ts +23 -0
- package/dist/core/sol-concrete.js +195 -0
- package/dist/core/solver.js +8 -5
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
- package/dist/core/system.d.ts +62 -1
- package/dist/core/system.js +263 -4
- package/dist/core/transfer.js +39 -9
- package/dist/core/translate.js +39 -10
- package/dist/core/watch.js +51 -6
- package/dist/interchange/check.js +10 -10
- package/dist/interchange/format.d.ts +4 -0
- package/dist/interchange/format.js +24 -6
- package/dist/kernel/cdcl.d.ts +5 -0
- package/dist/kernel/cdcl.js +88 -10
- package/dist/kernel/epr.js +141 -29
- package/dist/kernel/kernel.d.ts +31 -1
- package/dist/kernel/kernel.js +391 -101
- package/dist/kernel/model-sequence.d.ts +3 -0
- package/dist/kernel/model-sequence.js +34 -0
- package/dist/kernel/prove.d.ts +30 -1
- package/dist/kernel/prove.js +481 -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.d.ts +9 -3
- package/dist/lean-kernel/emit.js +200 -66
- package/dist/lean-kernel/lean-terms.js +5 -0
- package/dist/lean-kernel/library.js +10 -10
- package/package.json +7 -2
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, json, os, sys
|
|
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)
|
|
@@ -40,6 +45,25 @@ def injected(d):
|
|
|
40
45
|
f = d.func if isinstance(d, ast.Call) else d.value if isinstance(d, ast.Subscript) else None
|
|
41
46
|
return (dotted(f) or '').split('.')[-1] in ('Depends', 'Provide', 'Inject') if f is not None else False
|
|
42
47
|
|
|
48
|
+
def missing(q):
|
|
49
|
+
"""Why the attribute path q (a module's, `logging.getLo`) fails where it runs, or None: the module object's own method
|
|
50
|
+
(`m.__init__`), or a name a module of Python's own library doesn't have (that module imported to look: the code
|
|
51
|
+
imports it too)."""
|
|
52
|
+
parts = q.split('.')
|
|
53
|
+
for i, n in enumerate(parts[1:], 1):
|
|
54
|
+
if n.startswith('__') and callable(getattr(types.ModuleType, n, None)): return f"{'.'.join(parts[:i + 1])}: the module object's own method (its machinery, outside the subset)"
|
|
55
|
+
if parts[0] not in getattr(sys, 'stdlib_module_names', ()) or parts[0] in ('this', 'antigravity', '__main__'): return None
|
|
56
|
+
try:
|
|
57
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): o = importlib.import_module(parts[0])
|
|
58
|
+
for i, n in enumerate(parts[1:], 1):
|
|
59
|
+
if hasattr(o, n): o = getattr(o, n); continue
|
|
60
|
+
if not isinstance(o, types.ModuleType): return None
|
|
61
|
+
try:
|
|
62
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): o = importlib.import_module('.'.join(parts[:i + 1]))
|
|
63
|
+
except ImportError: return f"{'.'.join(parts[:i + 1])}: {'.'.join(parts[:i])} has no {n} (an AttributeError where it runs)"
|
|
64
|
+
except Exception: return None
|
|
65
|
+
return None
|
|
66
|
+
|
|
43
67
|
class Repo:
|
|
44
68
|
"""The repository's modules, parsed once each, for the classes an annotation names."""
|
|
45
69
|
def __init__(self, root):
|
|
@@ -76,6 +100,22 @@ class Module:
|
|
|
76
100
|
self.imports, self.classes, self.funcs, self.consts = {}, {}, {}, {}
|
|
77
101
|
for n in (self.tree.body if self.tree else []):
|
|
78
102
|
self.scan(n)
|
|
103
|
+
# (the module's variables a function rebinds, `global x`: no constant, every call shares them; and the names the
|
|
104
|
+
# module binds at its top level and in its classes' bodies, or may through `from m import *`: past them and a
|
|
105
|
+
# function's own, a name is a NameError where it runs)
|
|
106
|
+
walk = list(ast.walk(self.tree)) if self.tree else []
|
|
107
|
+
self.rebound = {g for x in walk if isinstance(x, ast.Global) for g in x.names}
|
|
108
|
+
self.star = any(isinstance(x, ast.ImportFrom) and any(a.name == '*' for a in x.names) for x in walk)
|
|
109
|
+
self.bound, todo = set(self.rebound), list(self.tree.body if self.tree else [])
|
|
110
|
+
while todo:
|
|
111
|
+
x = todo.pop()
|
|
112
|
+
if isinstance(x, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): self.bound.add(x.name)
|
|
113
|
+
if isinstance(x, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): continue
|
|
114
|
+
if isinstance(x, ast.Name) and not isinstance(x.ctx, ast.Load): self.bound.add(x.id)
|
|
115
|
+
if isinstance(x, (ast.Import, ast.ImportFrom)): self.bound |= {(a.asname or a.name).split('.')[0] for a in x.names}
|
|
116
|
+
if isinstance(x, (ast.ExceptHandler, ast.MatchAs, ast.MatchStar)) and x.name: self.bound.add(x.name)
|
|
117
|
+
if isinstance(x, ast.MatchMapping) and x.rest: self.bound.add(x.rest)
|
|
118
|
+
todo.extend(x.body if isinstance(x, ast.ClassDef) else ast.iter_child_nodes(x))
|
|
79
119
|
def scan(self, n):
|
|
80
120
|
if isinstance(n, ast.Import):
|
|
81
121
|
for a in n.names: self.imports[(a.asname or a.name).split('.')[0]] = ('module', a.name if a.asname else a.name.split('.')[0])
|
|
@@ -102,6 +142,9 @@ class Reader:
|
|
|
102
142
|
self.local_stack = []
|
|
103
143
|
self.caught = [] # (the names the handlers being read bind their exceptions to)
|
|
104
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 = {}
|
|
105
148
|
|
|
106
149
|
# --- types -------------------------------------------------------------------------------------------------------
|
|
107
150
|
def find_class(self, mod, name, depth=0):
|
|
@@ -144,6 +187,126 @@ class Reader:
|
|
|
144
187
|
imp = m.imports.get(name)
|
|
145
188
|
if imp and imp[0] == 'name': return self.ret_of(imp[1], imp[2], depth + 1)
|
|
146
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')}
|
|
147
310
|
def rec_of(self, mod, cdef, base=False):
|
|
148
311
|
"""A class as a record type: its fields (annotations, its bases' first), its methods (to resolve calls). A class
|
|
149
312
|
of the file, or a base of one (another module's too: its methods are the class's own), has its methods read."""
|
|
@@ -154,12 +317,20 @@ class Reader:
|
|
|
154
317
|
self.defs[q] = (mod, cdef)
|
|
155
318
|
self.recs[q] = None # (being read)
|
|
156
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
|
|
157
325
|
for b in cdef.bases:
|
|
158
326
|
bn = dotted(b.value if isinstance(b, ast.Subscript) else b)
|
|
159
|
-
if
|
|
160
|
-
if bn in ('
|
|
161
|
-
if bn in ('
|
|
162
|
-
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
|
|
163
334
|
hit = self.find_class(mod, bn.split('.')[-1]) if bn else None
|
|
164
335
|
if hit:
|
|
165
336
|
bq = self.rec_of(*hit, base=base or mod.path == self.file)
|
|
@@ -171,7 +342,9 @@ class Reader:
|
|
|
171
342
|
if not any(g['name'] == f['name'] for g in fields): fields.append(f)
|
|
172
343
|
for m, fid in br['methods'].items(): methods[m] = fid
|
|
173
344
|
rets.update(br.get('rets', {}))
|
|
174
|
-
elif bn:
|
|
345
|
+
elif bn:
|
|
346
|
+
kinds.add('outside-base:' + bn)
|
|
347
|
+
static = False
|
|
175
348
|
dataclass = any((dotted(d.func if isinstance(d, ast.Call) else d) or '').split('.')[-1] == 'dataclass' for d in cdef.decorator_list)
|
|
176
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)
|
|
177
350
|
# (a dataclass whose == is its fields' unless eq=False says it is identity)
|
|
@@ -179,7 +352,7 @@ class Reader:
|
|
|
179
352
|
total = not any(k.arg == 'total' and isinstance(k.value, ast.Constant) and k.value.value is False for k in cdef.keywords)
|
|
180
353
|
# The fields its __init__ sets: annotated there, or set from an annotated argument (a class of another module whose
|
|
181
354
|
# fields aren't declared on the class).
|
|
182
|
-
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
|
|
183
356
|
if init is not None:
|
|
184
357
|
anns = {x.arg: x.annotation for x in init.args.args + init.args.kwonlyargs if x.annotation is not None}
|
|
185
358
|
for n in ast.walk(init):
|
|
@@ -193,28 +366,84 @@ class Reader:
|
|
|
193
366
|
# `x or DEFAULT`: the argument's type, never None
|
|
194
367
|
name, t = n.targets[0].attr, self.ty(anns[v.values[0].id], mod)
|
|
195
368
|
if t['k'] == 'opt': t = t['of']
|
|
196
|
-
if t is not None
|
|
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]]
|
|
197
372
|
for n in cdef.body:
|
|
198
|
-
|
|
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):
|
|
199
378
|
ann = n.annotation
|
|
200
379
|
if dotted(ann.value if isinstance(ann, ast.Subscript) else ann) in ('ClassVar', 'typing.ClassVar'): continue
|
|
201
380
|
f = {'name': n.target.id, 't': self.ty(ann, mod)}
|
|
202
381
|
if n.value is not None: f['dflt'] = self.expr(n.value, mod)
|
|
203
382
|
fields = [g for g in fields if g['name'] != f['name']] + [f]
|
|
383
|
+
own_fields[f['name']] = f
|
|
204
384
|
elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
205
|
-
if n.returns is not None:
|
|
206
|
-
|
|
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)
|
|
207
390
|
if mod.path == self.file or base:
|
|
208
|
-
fid = f"{
|
|
391
|
+
fid = f"{q}.{n.name}"
|
|
209
392
|
# (a base's method read where its module is: its positions in its own file, super() its own bases')
|
|
210
|
-
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
|
|
211
394
|
try: self.funcs[fid] = self.func(n, mod, cdef.name, fid)
|
|
212
|
-
finally: self.file, self.supers = file, sup
|
|
213
|
-
methods[n.name] = fid
|
|
214
|
-
else: methods[n.name] = None # another module's method: not read
|
|
215
|
-
|
|
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,
|
|
216
431
|
'kinds': sorted(kinds | ({'dataclass'} if dataclass else set()) | ({'frozen'} if frozen else set()) | (set() if total else {'partial'})),
|
|
217
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}
|
|
218
447
|
self.recs[q] = r
|
|
219
448
|
return q
|
|
220
449
|
def ty(self, a, mod):
|
|
@@ -242,6 +471,7 @@ class Reader:
|
|
|
242
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}
|
|
243
472
|
return {'k': 'opaque', 'why': f"{text(a)}"}
|
|
244
473
|
n = dotted(a)
|
|
474
|
+
if self.qualified(mod, a) == 'sqlalchemy.orm.Session': return {'k': 'opaque', 'why': '$orm-session'}
|
|
245
475
|
if n in ('int',): return {'k': 'int'}
|
|
246
476
|
if n in ('float',): return {'k': 'float'}
|
|
247
477
|
if n in ('bool',): return {'k': 'bool'}
|
|
@@ -327,14 +557,14 @@ class Reader:
|
|
|
327
557
|
if a.vararg: params.append({'name': a.vararg.arg, 't': {'k': 'opaque', 'why': '*args'}, 'star': 1})
|
|
328
558
|
if a.kwarg: params.append({'name': a.kwarg.arg, 't': {'k': 'opaque', 'why': '**kwargs'}, 'star': 2})
|
|
329
559
|
body = self.block(n.body, mod)
|
|
330
|
-
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],
|
|
331
561
|
'params': params, 'ret': self.ty(n.returns, mod), 'body': body, 'async': isinstance(n, ast.AsyncFunctionDef), 'decorators': decs, 'static': static}
|
|
332
562
|
finally:
|
|
333
563
|
self.local_stack.pop()
|
|
334
564
|
self.local_imps.pop()
|
|
335
565
|
def decorator(self, d):
|
|
336
566
|
f = d.func if isinstance(d, ast.Call) else d
|
|
337
|
-
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)}
|
|
338
568
|
def locals_of(self, fn):
|
|
339
569
|
out = {x.arg for x in fn.args.posonlyargs + fn.args.args + fn.args.kwonlyargs}
|
|
340
570
|
if fn.args.vararg: out.add(fn.args.vararg.arg)
|
|
@@ -353,7 +583,7 @@ class Reader:
|
|
|
353
583
|
out.append(r)
|
|
354
584
|
return out
|
|
355
585
|
def stmt(self, s, mod):
|
|
356
|
-
p = where(self.file, s)
|
|
586
|
+
p = where(self.file, s, self.repo.root)
|
|
357
587
|
E = lambda x: self.expr(x, mod)
|
|
358
588
|
if isinstance(s, ast.Expr):
|
|
359
589
|
if isinstance(s.value, ast.Constant) and (isinstance(s.value.value, str) or s.value.value is Ellipsis): return [] # a docstring, or `...`
|
|
@@ -362,7 +592,8 @@ class Reader:
|
|
|
362
592
|
return [{'s': 'expr', 'p': p, 'x': E(s.value)}]
|
|
363
593
|
if isinstance(s, ast.Pass): return []
|
|
364
594
|
if isinstance(s, (ast.Assign, ast.AnnAssign)):
|
|
365
|
-
|
|
595
|
+
# (a declaration, `x: int`; of a field or an item, `o.f: int`, its object evaluated, and the item's index)
|
|
596
|
+
if s.value is None: return [] if isinstance(s.target, ast.Name) else [{'s': 'expr', 'p': p, 'x': E(y)} for y in ([s.target.value] + ([s.target.slice] if isinstance(s.target, ast.Subscript) else []))]
|
|
366
597
|
targets = s.targets if isinstance(s, ast.Assign) else [s.target]
|
|
367
598
|
x = E(s.value)
|
|
368
599
|
ann = self.ty(s.annotation, mod) if isinstance(s, ast.AnnAssign) else None
|
|
@@ -403,7 +634,9 @@ class Reader:
|
|
|
403
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)}]
|
|
404
635
|
if isinstance(s, ast.Continue): return [{'s': 'continue', 'p': p}]
|
|
405
636
|
if isinstance(s, ast.Break): return [{'s': 'break', 'p': p}]
|
|
406
|
-
|
|
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)"}]
|
|
407
640
|
if type(s).__name__ == 'TryStar': return [{'s': 'no', 'p': p, 'why': 'try/except* (exception groups)'}]
|
|
408
641
|
if isinstance(s, ast.Try):
|
|
409
642
|
hs = []
|
|
@@ -413,7 +646,7 @@ class Reader:
|
|
|
413
646
|
self.caught.append(h.name)
|
|
414
647
|
try: body = self.block(h.body, mod)
|
|
415
648
|
finally: self.caught.pop()
|
|
416
|
-
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])]}),
|
|
417
650
|
**({'open': True} if cs and cs[0][1] else {}), **({'as': h.name} if h.name else {}), 'body': body})
|
|
418
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)}]
|
|
419
652
|
if isinstance(s, (ast.Global, ast.Nonlocal)): return [{'s': 'no', 'p': p, 'why': f"{type(s).__name__.lower()} (a variable every call shares)"}]
|
|
@@ -445,7 +678,7 @@ class Reader:
|
|
|
445
678
|
out += [n for n in bs if n not in out]; op = op or bo
|
|
446
679
|
return out, op
|
|
447
680
|
def target(self, t, mod):
|
|
448
|
-
p = where(self.file, t)
|
|
681
|
+
p = where(self.file, t, self.repo.root)
|
|
449
682
|
if isinstance(t, ast.Name): return {'e': 'var', 'n': t.id, 'p': p}
|
|
450
683
|
if isinstance(t, ast.Attribute): return {'e': 'get', 'x': self.expr(t.value, mod), 'f': t.attr, 'p': p, 'text': text(t)}
|
|
451
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)}
|
|
@@ -458,6 +691,7 @@ class Reader:
|
|
|
458
691
|
def name(self, n, mod, p):
|
|
459
692
|
"""What a name is where it is read: a local, a constant, a function or class of the module, an import, a builtin."""
|
|
460
693
|
if self.local_stack and n in self.local_stack[-1]: return {'e': 'var', 'n': n, 'p': p}
|
|
694
|
+
if n in mod.rebound: return {'e': 'no', 'why': f"{n}: a module variable a function rebinds (global {n}), shared by every call", 'p': p}
|
|
461
695
|
if n in mod.funcs: return {'e': 'fn', 'id': n, 'p': p}
|
|
462
696
|
if n in mod.classes:
|
|
463
697
|
q = self.rec_of(mod, mod.classes[n])
|
|
@@ -486,13 +720,15 @@ class Reader:
|
|
|
486
720
|
return {'e': 'ext', 'q': f"{mod.name}.{n}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'global': True, 'p': p}
|
|
487
721
|
if n in ('True', 'False', 'None'): return self.expr(ast.Constant({'True': True, 'False': False, 'None': None}[n]), mod)
|
|
488
722
|
if n in BUILTINS: return {'e': 'builtin', 'n': n, 'p': p}
|
|
489
|
-
|
|
723
|
+
if n not in mod.bound and not mod.star and not hasattr(builtins, n) and not (n.startswith('__') and n.endswith('__')):
|
|
724
|
+
return {'e': 'no', 'why': f"{n}: a name the module doesn't define, import or bind (a NameError where it runs)", 'raises': True, 'p': p}
|
|
725
|
+
return {'e': 'ext', 'q': n, 'text': n, 'p': p}
|
|
490
726
|
def expr(self, x, mod):
|
|
491
727
|
r = self.expr1(x, mod)
|
|
492
728
|
if r.get('e') == 'no' and 'names' not in r: r['names'] = mentioned(x)
|
|
493
729
|
return r
|
|
494
730
|
def expr1(self, x, mod):
|
|
495
|
-
p = where(self.file, x)
|
|
731
|
+
p = where(self.file, x, self.repo.root)
|
|
496
732
|
E = lambda y: self.expr(y, mod)
|
|
497
733
|
if isinstance(x, ast.Constant):
|
|
498
734
|
v = x.value
|
|
@@ -506,8 +742,18 @@ class Reader:
|
|
|
506
742
|
return {'e': 'no', 'why': f"{text(x)}: a constant outside the subset", 'p': p}
|
|
507
743
|
if isinstance(x, ast.Name): return self.name(x.id, mod, p)
|
|
508
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)}
|
|
509
753
|
d = dotted(x)
|
|
510
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}
|
|
511
757
|
# (a literal constant of another module of the repository, `boat.BRING_UP`: its value, as the module's own
|
|
512
758
|
# constants are read; what the module is set to at import, the check importing it as it ships)
|
|
513
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
|
|
@@ -515,6 +761,8 @@ class Reader:
|
|
|
515
761
|
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]):
|
|
516
762
|
q = mod.imports[base][1] + d[len(base):]
|
|
517
763
|
if q in KNOWN: return {'e': 'lib', 'q': q, 'p': p}
|
|
764
|
+
why = missing(q) if not self.repo.path_of(q.split('.')[0]) else None
|
|
765
|
+
if why: return {'e': 'no', 'why': why, 'raises': True, 'p': p}
|
|
518
766
|
ret = self.ret_of(q.rpartition('.')[0], q.rpartition('.')[2])
|
|
519
767
|
return {'e': 'ext', 'q': q, 'text': d, 'patch': {'mod': mod.name, 'path': d.split('.')}, 'p': p, **({'ret': ret} if ret else {})}
|
|
520
768
|
return {'e': 'get', 'x': E(x.value), 'f': x.attr, 'p': p, 'text': text(x)}
|
|
@@ -538,15 +786,6 @@ class Reader:
|
|
|
538
786
|
if isinstance(x, ast.IfExp): return {'e': 'ite', 'c': E(x.test), 'a': E(x.body), 'b': E(x.orelse), 'p': p}
|
|
539
787
|
if isinstance(x, ast.Await): return {'e': 'await', 'x': E(x.value), 'p': p}
|
|
540
788
|
if isinstance(x, ast.Call):
|
|
541
|
-
# super().m(...): the first base (in the order its bases are listed, theirs after) whose m is read, on self;
|
|
542
|
-
# super().__init__() where no base has one: object's, nothing
|
|
543
|
-
fx = x.func
|
|
544
|
-
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:
|
|
545
|
-
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)
|
|
546
|
-
if mid is False and fx.attr == '__init__' and not x.args and not x.keywords: return {'e': 'none', 'p': p}
|
|
547
|
-
if not mid: return {'e': 'no', 'why': f"{text(x)}: a base's method not read", 'p': p}
|
|
548
|
-
return {'e': 'call', 'f': {'e': 'get', 'x': {'e': 'var', 'n': 'self', 'p': p}, 'f': fx.attr, 'sup': mid, 'p': p, 'text': text(fx)},
|
|
549
|
-
'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)}
|
|
550
789
|
f = E(x.func)
|
|
551
790
|
if f.get('e') == 'ext' and f.get('q') in KNOWN: f = {'e': 'lib', 'q': f['q'], 'p': f['p']}
|
|
552
791
|
# (a class of the repository made here: its methods read, its __init__ the code that makes it)
|
|
@@ -593,7 +832,7 @@ def main():
|
|
|
593
832
|
print(json.dumps({'error': f"{req['file']} doesn't parse"})); return
|
|
594
833
|
out = {'lang': 'python', 'file': os.path.basename(r.file), 'path': r.file, 'module': mod.name, 'root': os.path.abspath(req['root']), 'entries': [],
|
|
595
834
|
# (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())}}
|
|
835
|
+
'consts': {k: v.value for k, v in ((k, r.const_value(mod, v)) for k, v in mod.consts.items() if k not in mod.rebound) 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())}}
|
|
597
836
|
for n in req['names'] or list(mod.classes):
|
|
598
837
|
if n in mod.classes: out['entries'].append({'k': 'class', 'rec': r.rec_of(mod, mod.classes[n])})
|
|
599
838
|
elif n in mod.funcs:
|
package/dist/core/rb/reader.rb
CHANGED
|
@@ -18,8 +18,10 @@ class Reader
|
|
|
18
18
|
def initialize(req)
|
|
19
19
|
@root, @file, @clocks = File.expand_path(req['root']), File.expand_path(req['file']), req['clocks'] || []
|
|
20
20
|
@base = File.basename(@file)
|
|
21
|
-
@consts = {}
|
|
22
|
-
|
|
21
|
+
@consts, @defined, @mods = {}, [], {}
|
|
22
|
+
# (open: a constant may come from what the code requires, a gem's, or a Gemfile's bundle, or be made as it runs)
|
|
23
|
+
@open = %w[Gemfile gems.rb].any? { |g| File.exist?(File.join(@root, g)) } || !Dir.glob(File.join(@root, '*.gemspec')).empty?
|
|
24
|
+
([@file] | Dir.glob(File.join(@root, '**', '*.rb'))).each { |f| index_consts(f) rescue nil }
|
|
23
25
|
@recs, @funcs, @loads = {}, {}, []
|
|
24
26
|
@caught = []
|
|
25
27
|
end
|
|
@@ -28,8 +30,25 @@ class Reader
|
|
|
28
30
|
def index_consts(f)
|
|
29
31
|
walk = lambda do |n, nest|
|
|
30
32
|
case n
|
|
31
|
-
when Prism::ModuleNode, Prism::ClassNode
|
|
33
|
+
when Prism::ModuleNode, Prism::ClassNode
|
|
34
|
+
q = (nest + [n.constant_path.slice]).join('::')
|
|
35
|
+
@defined << q
|
|
36
|
+
# (its singleton methods and the names each one's body calls on it; open where its body may add others)
|
|
37
|
+
md = (@mods[q] ||= {defs: {}, open: false, cls: n.is_a?(Prism::ClassNode)})
|
|
38
|
+
md[:open] = true if n.is_a?(Prism::ClassNode) && n.superclass
|
|
39
|
+
(n.body&.body || []).each do |m|
|
|
40
|
+
if m.is_a?(Prism::DefNode) && m.receiver.is_a?(Prism::SelfNode)
|
|
41
|
+
calls = []
|
|
42
|
+
each_node(m) { |c| calls << c.name.to_s if c.is_a?(Prism::CallNode) && !c.receiver }
|
|
43
|
+
md[:defs][m.name.to_s] = calls
|
|
44
|
+
elsif m.is_a?(Prism::SingletonClassNode) || (m.is_a?(Prism::CallNode) && !%i[attr_reader attr_writer attr_accessor private public protected].include?(m.name))
|
|
45
|
+
md[:open] = true
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
n.body&.body&.each { |m| walk.(m, nest + [n.constant_path.slice]) }
|
|
49
|
+
when Prism::ConstantPathWriteNode then @defined << (nest + [n.target.slice]).join('::')
|
|
32
50
|
when Prism::ConstantWriteNode
|
|
51
|
+
@defined << (nest + [n.name.to_s]).join('::')
|
|
33
52
|
v = n.value
|
|
34
53
|
lit = case v
|
|
35
54
|
when Prism::SymbolNode then {'e' => 'str', 'v' => v.unescaped, 'sym' => true}
|
|
@@ -40,7 +59,29 @@ class Reader
|
|
|
40
59
|
@consts[(nest + [n.name.to_s]).join('::')] = lit.merge('file' => f) if lit
|
|
41
60
|
end
|
|
42
61
|
end
|
|
43
|
-
Prism.parse_file(f).value
|
|
62
|
+
tree = Prism.parse_file(f).value
|
|
63
|
+
tree.statements.body.each { |n| walk.(n, []) }
|
|
64
|
+
each_node(tree) { |n| @open = true if !@open && n.is_a?(Prism::CallNode) && %i[require load autoload const_set const_missing eval instance_eval class_eval module_eval].include?(n.name) }
|
|
65
|
+
end
|
|
66
|
+
# Why Mod.m fails where it runs, a module or class under the root whose singleton methods the reader sees all of: no
|
|
67
|
+
# such method, or its body calls a name nothing defines; else nil.
|
|
68
|
+
def no_method(r, n, nest)
|
|
69
|
+
return nil if @open
|
|
70
|
+
full = r.slice.sub(/\A::/, '')
|
|
71
|
+
q = nest.length.downto(0).map { |i| (nest[0, i] + [full]).join('::') }.find { |k| @mods.key?(k) }
|
|
72
|
+
md = q && @mods[q]
|
|
73
|
+
return nil if !md || md[:open]
|
|
74
|
+
known = ->(m) { md[:defs].key?(m) || (md[:cls] ? Class.new : Module.new).respond_to?(m, true) }
|
|
75
|
+
return "#{full} defines no #{n} (a NoMethodError where it runs)" unless known.(n.to_s)
|
|
76
|
+
gone = md[:defs][n.to_s].reject { |m| known.(m) }
|
|
77
|
+
gone.empty? ? nil : "#{full}.#{n} calls #{gone.first}, which nothing defines (a NameError where it runs)"
|
|
78
|
+
end
|
|
79
|
+
# Whether a constant is defined: under the root (a class, a module, a constant), by Ruby itself, or maybe by what the
|
|
80
|
+
# code requires.
|
|
81
|
+
def defined_const?(n, nest)
|
|
82
|
+
full = n.slice.sub(/\A::/, '')
|
|
83
|
+
@open || nest.length.downto(0).any? { |i| @defined.include?((nest[0, i] + [full]).join('::')) } || @defined.any? { |k| k.end_with?("::#{full}") } ||
|
|
84
|
+
(Object.const_defined?(full) rescue true)
|
|
44
85
|
end
|
|
45
86
|
# A constant's literal, and the file defining it kept (the check loads it before the file read).
|
|
46
87
|
def const(n, nest)
|
|
@@ -395,7 +436,13 @@ class Reader
|
|
|
395
436
|
else
|
|
396
437
|
return no(x, "#{text(x)}: a method of an array") if r.is_a?(Prism::ArrayNode)
|
|
397
438
|
# (another class's code: at the boundary where it is inferred, with the names its arguments mention)
|
|
398
|
-
return no(x, "#{text(x)}: #{r.slice},
|
|
439
|
+
return no(x, "#{text(x)}: #{r.slice}, a constant nothing under the root defines (a NameError where it runs)").merge('raises' => true) if (r.is_a?(Prism::ConstantReadNode) || r.is_a?(Prism::ConstantPathNode)) && !defined_const?(r, @nest)
|
|
440
|
+
if r.is_a?(Prism::ConstantReadNode) || r.is_a?(Prism::ConstantPathNode)
|
|
441
|
+
why = no_method(r, n, @nest)
|
|
442
|
+
return no(x, "#{text(x)}: #{why}").merge('raises' => true) if why
|
|
443
|
+
# (its arguments evaluated, as the code does: what fails there fails the step)
|
|
444
|
+
return no(x, "#{text(x)}: #{r.slice}, another class's code").merge('ext' => "#{r.slice}.#{n}", 'names' => mentioned(args), 'args' => args.map { |a| expr(a) }, 'patch' => {'mod' => r.slice, 'path' => [n.to_s]})
|
|
445
|
+
end
|
|
399
446
|
call({'e' => 'get', 'x' => rv, 'f' => n.to_s, 'p' => p, 'text' => text(x)}, args.map { |a| expr(a) }, x)
|
|
400
447
|
end
|
|
401
448
|
end
|
|
@@ -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/`.
|