gdp-wired 0.31.1 → 0.32.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 +82 -6
- package/dist/core/c/reader.d.ts +86 -0
- package/dist/core/c/reader.js +860 -0
- package/dist/core/cli.d.ts +66 -0
- package/dist/core/cli.js +582 -0
- package/dist/core/dsl.d.ts +4 -2
- package/dist/core/dsl.js +22 -12
- package/dist/core/effect.d.ts +6 -4
- package/dist/core/effect.js +48 -10
- package/dist/core/ex/harness.exs +177 -0
- package/dist/core/ex/json.exs +46 -0
- package/dist/core/ex/reader.exs +462 -0
- package/dist/core/exists.d.ts +3 -0
- package/dist/core/exists.js +3 -1
- package/dist/core/extract-c.d.ts +35 -0
- package/dist/core/extract-c.js +424 -0
- package/dist/core/extract-check.js +27 -6
- package/dist/core/extract-ex.d.ts +16 -0
- package/dist/core/extract-ex.js +33 -0
- package/dist/core/extract-go-check.d.ts +28 -0
- package/dist/core/extract-go-check.js +639 -0
- package/dist/core/extract-go.d.ts +231 -0
- package/dist/core/extract-go.js +1166 -0
- package/dist/core/extract-jvm.d.ts +23 -0
- package/dist/core/extract-jvm.js +220 -0
- package/dist/core/extract-print.js +17 -7
- package/dist/core/extract-py.d.ts +15 -0
- package/dist/core/extract-py.js +31 -0
- package/dist/core/extract-rb.d.ts +17 -0
- package/dist/core/extract-rb.js +31 -0
- package/dist/core/extract-read.d.ts +20 -0
- package/dist/core/extract-read.js +46 -6
- package/dist/core/extract-rs.d.ts +12 -0
- package/dist/core/extract-rs.js +306 -0
- package/dist/core/extract-shapes.d.ts +2 -0
- package/dist/core/extract-shapes.js +6 -5
- package/dist/core/extract-step.d.ts +806 -0
- package/dist/core/extract-step.js +4141 -0
- package/dist/core/extract-swift.d.ts +27 -0
- package/dist/core/extract-swift.js +484 -0
- package/dist/core/extract-xstate.d.ts +10 -3
- package/dist/core/extract-xstate.js +50 -4
- package/dist/core/extract.d.ts +22 -3
- package/dist/core/extract.js +107 -18
- package/dist/core/go/go.mod +3 -0
- package/dist/core/go/reader.go +901 -0
- package/dist/core/infer.js +1770 -52
- package/dist/core/jvm/Harness.java +361 -0
- package/dist/core/jvm/JavaReader.java +825 -0
- package/dist/core/jvm/Jvm.java +332 -0
- package/dist/core/jvm/KtReader.java +960 -0
- package/dist/core/jvm/Rt.java +10 -0
- package/dist/core/laws.d.ts +66 -0
- package/dist/core/laws.js +522 -0
- package/dist/core/py/harness.py +328 -0
- package/dist/core/py/reader.py +447 -0
- package/dist/core/rb/harness.rb +233 -0
- package/dist/core/rb/reader.rb +375 -0
- package/dist/core/rs/Cargo.lock +108 -0
- package/dist/core/rs/Cargo.toml +14 -0
- package/dist/core/rs/src/main.rs +681 -0
- package/dist/core/swift/Harness.swift +124 -0
- package/dist/core/swift/Main.swift +34 -0
- package/dist/core/swift/Package.swift +13 -0
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
- package/dist/kernel/epr.d.ts +35 -0
- package/dist/kernel/epr.js +1676 -0
- package/dist/kernel/prove.d.ts +44 -0
- package/dist/kernel/prove.js +657 -50
- package/dist/lean-kernel/emit.d.ts +1 -0
- package/dist/lean-kernel/emit.js +21 -4
- package/package.json +53 -2
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
# The extractor's Python reader (core/extract-py.ts): a module read through Python's own parser (ast) and lowered
|
|
2
|
+
# into the shared step IR (core/extract-step.ts's SModule, as JSON on stdout), which one TypeScript executor runs into
|
|
3
|
+
# the rule. Nothing here decides what is in the subset beyond the syntax: a construct the IR has no node for becomes
|
|
4
|
+
# {"e": "no"} or {"s": "no"} with the reason, refused by the executor only where a step reaches it. The record types
|
|
5
|
+
# arguments carry are read from the repository's own modules (their class annotations, never run).
|
|
6
|
+
#
|
|
7
|
+
# python3 -I core/py/reader.py '{"root": <repo>, "file": <file>, "names": [<classes or functions>]}'
|
|
8
|
+
import ast, json, os, sys
|
|
9
|
+
|
|
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
|
+
# Library functions the executor knows (their meaning, not their code).
|
|
12
|
+
KNOWN = {'time.time', 'time.monotonic', 'time.perf_counter', 'math.floor', 'math.ceil', 'math.isfinite', 'math.isnan', 'math.isinf', 'threading.Lock', 'threading.RLock', 'asyncio.Lock'}
|
|
13
|
+
TRANSPARENT = {'staticmethod', 'classmethod', 'property', 'dataclass', 'dataclasses.dataclass', 'override', 'typing.override', 'abstractmethod'}
|
|
14
|
+
|
|
15
|
+
def where(file, n):
|
|
16
|
+
return f"{os.path.basename(file)}:{getattr(n, 'lineno', 0)}:{getattr(n, 'col_offset', 0) + 1}"
|
|
17
|
+
|
|
18
|
+
def text(n):
|
|
19
|
+
try: s = ast.unparse(n)
|
|
20
|
+
except Exception: s = type(n).__name__
|
|
21
|
+
s = ' '.join(s.split())
|
|
22
|
+
return s if len(s) <= 60 else s[:57] + '...'
|
|
23
|
+
|
|
24
|
+
def dotted(n):
|
|
25
|
+
if isinstance(n, ast.Name): return n.id
|
|
26
|
+
if isinstance(n, ast.Attribute):
|
|
27
|
+
b = dotted(n.value)
|
|
28
|
+
return f"{b}.{n.attr}" if b else None
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
def mentioned(n):
|
|
32
|
+
"""The names a node the subset doesn't read mentions (the variables it may read or write)."""
|
|
33
|
+
return sorted({x.id for x in ast.walk(n) if isinstance(x, ast.Name)})
|
|
34
|
+
|
|
35
|
+
def injected(d):
|
|
36
|
+
"""A parameter's default that marks it an injected dependency: FastAPI's Depends(...), dependency-injector's Provide[...]."""
|
|
37
|
+
f = d.func if isinstance(d, ast.Call) else d.value if isinstance(d, ast.Subscript) else None
|
|
38
|
+
return (dotted(f) or '').split('.')[-1] in ('Depends', 'Provide', 'Inject') if f is not None else False
|
|
39
|
+
|
|
40
|
+
class Repo:
|
|
41
|
+
"""The repository's modules, parsed once each, for the classes an annotation names."""
|
|
42
|
+
def __init__(self, root):
|
|
43
|
+
self.root, self.trees = root, {}
|
|
44
|
+
def path_of(self, mod):
|
|
45
|
+
base = os.path.join(self.root, *mod.split('.'))
|
|
46
|
+
for p in (base + '.py', os.path.join(base, '__init__.py')):
|
|
47
|
+
if os.path.isfile(p): return p
|
|
48
|
+
return None
|
|
49
|
+
def tree(self, path):
|
|
50
|
+
if path not in self.trees:
|
|
51
|
+
try:
|
|
52
|
+
with open(path, encoding='utf-8') as f: self.trees[path] = ast.parse(f.read(), path)
|
|
53
|
+
except Exception: self.trees[path] = None
|
|
54
|
+
return self.trees[path]
|
|
55
|
+
def module_name(self, path):
|
|
56
|
+
rel = os.path.relpath(path, self.root)[:-3].replace(os.sep, '.')
|
|
57
|
+
return rel[:-9] if rel.endswith('.__init__') else rel
|
|
58
|
+
|
|
59
|
+
def resolve_from(mod_name, is_pkg, node):
|
|
60
|
+
"""The absolute module an `from X import ...` names, relative ones too."""
|
|
61
|
+
if not node.level: return node.module
|
|
62
|
+
parts = mod_name.split('.')
|
|
63
|
+
base = parts if is_pkg else parts[:-1]
|
|
64
|
+
base = base[: len(base) - (node.level - 1)] if node.level > 1 else base
|
|
65
|
+
return '.'.join(base + ([node.module] if node.module else []))
|
|
66
|
+
|
|
67
|
+
class Module:
|
|
68
|
+
"""One module's names: its imports, classes, functions and constants."""
|
|
69
|
+
def __init__(self, repo, path):
|
|
70
|
+
self.repo, self.path, self.tree = repo, path, repo.tree(path)
|
|
71
|
+
self.name = repo.module_name(path)
|
|
72
|
+
self.is_pkg = path.endswith('__init__.py')
|
|
73
|
+
self.imports, self.classes, self.funcs, self.consts = {}, {}, {}, {}
|
|
74
|
+
for n in (self.tree.body if self.tree else []):
|
|
75
|
+
self.scan(n)
|
|
76
|
+
def scan(self, n):
|
|
77
|
+
if isinstance(n, ast.Import):
|
|
78
|
+
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])
|
|
79
|
+
elif isinstance(n, ast.ImportFrom):
|
|
80
|
+
m = resolve_from(self.name, self.is_pkg, n)
|
|
81
|
+
for a in n.names: self.imports[a.asname or a.name] = ('name', m, a.name)
|
|
82
|
+
elif isinstance(n, ast.ClassDef): self.classes[n.name] = n
|
|
83
|
+
elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)): self.funcs[n.name] = n
|
|
84
|
+
elif isinstance(n, (ast.Assign, ast.AnnAssign)):
|
|
85
|
+
targets = n.targets if isinstance(n, ast.Assign) else [n.target]
|
|
86
|
+
for t in targets:
|
|
87
|
+
if isinstance(t, ast.Name) and n.value is not None: self.consts[t.id] = n.value
|
|
88
|
+
elif isinstance(n, ast.If):
|
|
89
|
+
# `if TYPE_CHECKING:` imports and aliases: what the names are for the types (its else, `X = Any`, yields to it).
|
|
90
|
+
for m in n.orelse + n.body: self.scan(m)
|
|
91
|
+
|
|
92
|
+
class Reader:
|
|
93
|
+
def __init__(self, root, file):
|
|
94
|
+
self.repo = Repo(root)
|
|
95
|
+
self.mod = Module(self.repo, os.path.abspath(file))
|
|
96
|
+
self.file = os.path.abspath(file)
|
|
97
|
+
self.recs, self.funcs = {}, {}
|
|
98
|
+
self.local_stack = []
|
|
99
|
+
|
|
100
|
+
# --- types -------------------------------------------------------------------------------------------------------
|
|
101
|
+
def find_class(self, mod, name, depth=0):
|
|
102
|
+
"""A class a module names, through its imports (re-exports too): (module, ClassDef) or None."""
|
|
103
|
+
if depth > 6 or mod is None: return None
|
|
104
|
+
if name in mod.classes: return (mod, mod.classes[name])
|
|
105
|
+
imp = mod.imports.get(name)
|
|
106
|
+
if imp and imp[0] == 'name':
|
|
107
|
+
p = self.repo.path_of(imp[1])
|
|
108
|
+
if p:
|
|
109
|
+
sub = Module(self.repo, p) if p != mod.path else mod
|
|
110
|
+
return self.find_class(sub, imp[2], depth + 1)
|
|
111
|
+
if name in mod.consts and isinstance(mod.consts[name], ast.Name): # an alias: X = Y
|
|
112
|
+
return self.find_class(mod, mod.consts[name].id, depth + 1)
|
|
113
|
+
return None
|
|
114
|
+
def ret_of(self, modname, name, depth=0):
|
|
115
|
+
"""The declared result type of a function a module of the repository defines (through its re-exports), or None."""
|
|
116
|
+
p = self.repo.path_of(modname) if modname else None
|
|
117
|
+
if depth > 6 or not p: return None
|
|
118
|
+
m = Module(self.repo, p) if p != self.mod.path else self.mod
|
|
119
|
+
f = m.funcs.get(name)
|
|
120
|
+
if f is not None: return self.ty(f.returns, m) if f.returns is not None else None
|
|
121
|
+
imp = m.imports.get(name)
|
|
122
|
+
if imp and imp[0] == 'name': return self.ret_of(imp[1], imp[2], depth + 1)
|
|
123
|
+
return None
|
|
124
|
+
def rec_of(self, mod, cdef):
|
|
125
|
+
"""A class as a record type: its fields (annotations, its bases' first), its methods (to resolve calls)."""
|
|
126
|
+
q = f"{mod.name}.{cdef.name}"
|
|
127
|
+
if q in self.recs: return q
|
|
128
|
+
self.recs[q] = None # (being read)
|
|
129
|
+
fields, methods, bases, kinds, rets = [], {}, [], set(), {}
|
|
130
|
+
for b in cdef.bases:
|
|
131
|
+
bn = dotted(b.value if isinstance(b, ast.Subscript) else b)
|
|
132
|
+
if bn in ('TypedDict', 'typing.TypedDict', 'typing_extensions.TypedDict'): kinds.add('typeddict'); continue
|
|
133
|
+
if bn in ('BaseModel', 'pydantic.BaseModel'): kinds.add('pydantic'); continue
|
|
134
|
+
if bn in ('Protocol', 'typing.Protocol', 'ABC', 'abc.ABC'): kinds.add('protocol'); continue
|
|
135
|
+
if bn in ('Generic', 'object', 'Exception'): continue
|
|
136
|
+
hit = self.find_class(mod, bn.split('.')[-1]) if bn else None
|
|
137
|
+
if hit:
|
|
138
|
+
bq = self.rec_of(*hit)
|
|
139
|
+
if bq and self.recs.get(bq):
|
|
140
|
+
br = self.recs[bq]
|
|
141
|
+
bases.append(bq)
|
|
142
|
+
kinds |= set(br.get('kinds', []))
|
|
143
|
+
for f in br['fields']:
|
|
144
|
+
if not any(g['name'] == f['name'] for g in fields): fields.append(f)
|
|
145
|
+
for m, fid in br['methods'].items(): methods[m] = fid
|
|
146
|
+
rets.update(br.get('rets', {}))
|
|
147
|
+
elif bn: kinds.add('outside-base:' + bn)
|
|
148
|
+
dataclass = any((dotted(d.func if isinstance(d, ast.Call) else d) or '').split('.')[-1] == 'dataclass' for d in cdef.decorator_list)
|
|
149
|
+
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)
|
|
150
|
+
total = not any(k.arg == 'total' and isinstance(k.value, ast.Constant) and k.value.value is False for k in cdef.keywords)
|
|
151
|
+
# The fields its __init__ sets: annotated there, or set from an annotated argument (a class of another module whose
|
|
152
|
+
# fields aren't declared on the class).
|
|
153
|
+
init = next((n for n in cdef.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == '__init__'), None)
|
|
154
|
+
if init is not None:
|
|
155
|
+
anns = {x.arg: x.annotation for x in init.args.args + init.args.kwonlyargs if x.annotation is not None}
|
|
156
|
+
for n in ast.walk(init):
|
|
157
|
+
t = None
|
|
158
|
+
if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Attribute) and isinstance(n.target.value, ast.Name) and n.target.value.id == 'self':
|
|
159
|
+
name, t = n.target.attr, self.ty(n.annotation, mod)
|
|
160
|
+
elif isinstance(n, ast.Assign) and len(n.targets) == 1 and isinstance(n.targets[0], ast.Attribute) and isinstance(n.targets[0].value, ast.Name) and n.targets[0].value.id == 'self':
|
|
161
|
+
v = n.value
|
|
162
|
+
if isinstance(v, ast.Name) and v.id in anns: name, t = n.targets[0].attr, self.ty(anns[v.id], mod)
|
|
163
|
+
elif isinstance(v, ast.BoolOp) and isinstance(v.op, ast.Or) and isinstance(v.values[0], ast.Name) and v.values[0].id in anns and not (isinstance(v.values[-1], ast.Constant) and v.values[-1].value is None):
|
|
164
|
+
# `x or DEFAULT`: the argument's type, never None
|
|
165
|
+
name, t = n.targets[0].attr, self.ty(anns[v.values[0].id], mod)
|
|
166
|
+
if t['k'] == 'opt': t = t['of']
|
|
167
|
+
if t is not None and not any(g['name'] == name for g in fields): fields.append({'name': name, 't': t, 'init': True})
|
|
168
|
+
for n in cdef.body:
|
|
169
|
+
if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name):
|
|
170
|
+
ann = n.annotation
|
|
171
|
+
if dotted(ann.value if isinstance(ann, ast.Subscript) else ann) in ('ClassVar', 'typing.ClassVar'): continue
|
|
172
|
+
f = {'name': n.target.id, 't': self.ty(ann, mod)}
|
|
173
|
+
if n.value is not None: f['dflt'] = self.expr(n.value, mod)
|
|
174
|
+
fields = [g for g in fields if g['name'] != f['name']] + [f]
|
|
175
|
+
elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
176
|
+
if n.returns is not None: rets[n.name] = self.ty(n.returns, mod)
|
|
177
|
+
else: rets.pop(n.name, None)
|
|
178
|
+
if mod.path == self.file:
|
|
179
|
+
fid = f"{cdef.name}.{n.name}"
|
|
180
|
+
self.funcs[fid] = self.func(n, mod, cdef.name, fid)
|
|
181
|
+
methods[n.name] = fid
|
|
182
|
+
else: methods[n.name] = None # another module's method: not read
|
|
183
|
+
r = {'name': q, 'short': cdef.name, 'fields': fields, 'methods': methods, 'bases': bases, 'p': where(mod.path, cdef),
|
|
184
|
+
'kinds': sorted(kinds | ({'dataclass'} if dataclass else set()) | ({'frozen'} if frozen else set()) | (set() if total else {'partial'})),
|
|
185
|
+
'own': mod.path == self.file, 'module': mod.name, **({'rets': rets} if rets else {})}
|
|
186
|
+
self.recs[q] = r
|
|
187
|
+
return q
|
|
188
|
+
def ty(self, a, mod):
|
|
189
|
+
if a is None: return {'k': 'any'}
|
|
190
|
+
if isinstance(a, ast.Constant):
|
|
191
|
+
if a.value is None: return {'k': 'none'}
|
|
192
|
+
if isinstance(a.value, str):
|
|
193
|
+
try: return self.ty(ast.parse(a.value, mode='eval').body, mod)
|
|
194
|
+
except SyntaxError: return {'k': 'opaque', 'why': a.value}
|
|
195
|
+
if isinstance(a, ast.BinOp) and isinstance(a.op, ast.BitOr):
|
|
196
|
+
return self.union([self.ty(a.left, mod), self.ty(a.right, mod)], a)
|
|
197
|
+
if isinstance(a, ast.Subscript):
|
|
198
|
+
head = (dotted(a.value) or '').split('.')[-1]
|
|
199
|
+
args = a.slice.elts if isinstance(a.slice, ast.Tuple) else [a.slice]
|
|
200
|
+
if head in ('Optional',): return self.union([self.ty(args[0], mod), {'k': 'none'}], a)
|
|
201
|
+
if head == 'Union': return self.union([self.ty(x, mod) for x in args], a)
|
|
202
|
+
if head in ('Final', 'Annotated', 'ReadOnly', 'Required', 'NotRequired'): return self.ty(args[0], mod)
|
|
203
|
+
if head == 'Literal':
|
|
204
|
+
if all(isinstance(x, ast.Constant) and isinstance(x.value, str) for x in args): return {'k': 'choice', 'values': [x.value for x in args]}
|
|
205
|
+
return {'k': 'opaque', 'why': f"{text(a)}: a Literal of other than strings"}
|
|
206
|
+
if head in ('dict', 'Dict', 'Mapping', 'MutableMapping', 'defaultdict', 'OrderedDict') and len(args) == 2:
|
|
207
|
+
return {'k': 'map', 'key': self.ty(args[0], mod), 'val': self.ty(args[1], mod), 'py': head}
|
|
208
|
+
if head in ('list', 'List', 'Sequence'): return {'k': 'list', 'of': self.ty(args[0], mod)}
|
|
209
|
+
return {'k': 'opaque', 'why': f"{text(a)}"}
|
|
210
|
+
n = dotted(a)
|
|
211
|
+
if n in ('int',): return {'k': 'int'}
|
|
212
|
+
if n in ('float',): return {'k': 'float'}
|
|
213
|
+
if n in ('bool',): return {'k': 'bool'}
|
|
214
|
+
if n in ('str',): return {'k': 'str'}
|
|
215
|
+
if n in ('None',): return {'k': 'none'}
|
|
216
|
+
if n in ('Final', 'Any', 'typing.Any', 'object'): return {'k': 'any'}
|
|
217
|
+
if n in ('dict', 'Dict'): return {'k': 'opaque', 'why': f"{n} with no key and value types"}
|
|
218
|
+
if n in ('threading.Lock', 'asyncio.Lock', 'Lock'): return {'k': 'lock'}
|
|
219
|
+
if n:
|
|
220
|
+
hit = self.find_class(mod, n.split('.')[-1]) if '.' not in n or n.split('.')[0] in mod.imports else None
|
|
221
|
+
if hit:
|
|
222
|
+
q = self.rec_of(*hit)
|
|
223
|
+
if q: return {'k': 'rec', 'name': q}
|
|
224
|
+
return {'k': 'opaque', 'why': f"{n}, a type outside the files read"}
|
|
225
|
+
return {'k': 'opaque', 'why': text(a)}
|
|
226
|
+
def union(self, ts, a):
|
|
227
|
+
none = any(t['k'] == 'none' for t in ts)
|
|
228
|
+
rest = [t for t in ts if t['k'] != 'none']
|
|
229
|
+
flat = []
|
|
230
|
+
for t in rest:
|
|
231
|
+
if t['k'] == 'opt': none = True; t = t['of']
|
|
232
|
+
if t not in flat: flat.append(t)
|
|
233
|
+
if len(flat) == 2 and {t['k'] for t in flat} == {'int', 'float'}: flat = [{'k': 'float'}]
|
|
234
|
+
if len(flat) != 1: return {'k': 'opaque', 'why': f"{text(a)}: a union of several types"}
|
|
235
|
+
return {'k': 'opt', 'of': flat[0]} if none else flat[0]
|
|
236
|
+
|
|
237
|
+
# --- functions ---------------------------------------------------------------------------------------------------
|
|
238
|
+
def func(self, n, mod, cls, fid):
|
|
239
|
+
self.local_stack.append(set(self.locals_of(n)))
|
|
240
|
+
try:
|
|
241
|
+
a = n.args
|
|
242
|
+
params = []
|
|
243
|
+
pos = a.posonlyargs + a.args
|
|
244
|
+
dflts = [None] * (len(pos) - len(a.defaults)) + list(a.defaults)
|
|
245
|
+
for i, (x, d) in enumerate(zip(pos, dflts)):
|
|
246
|
+
params.append({'name': x.arg, 't': self.ty(x.annotation, mod), **({'dflt': self.expr(d, mod)} if d is not None else {}), **({'inject': True} if injected(d) else {})})
|
|
247
|
+
for x, d in zip(a.kwonlyargs, a.kw_defaults):
|
|
248
|
+
params.append({'name': x.arg, 't': self.ty(x.annotation, mod), 'kw': True, **({'dflt': self.expr(d, mod)} if d is not None else {}), **({'inject': True} if injected(d) else {})})
|
|
249
|
+
decs = [self.decorator(d) for d in n.decorator_list]
|
|
250
|
+
static = any(d['name'] in ('staticmethod',) for d in decs)
|
|
251
|
+
if cls and not static and params: params[0]['self'] = True
|
|
252
|
+
if a.vararg: params.append({'name': a.vararg.arg, 't': {'k': 'opaque', 'why': '*args'}, 'star': 1})
|
|
253
|
+
if a.kwarg: params.append({'name': a.kwarg.arg, 't': {'k': 'opaque', 'why': '**kwargs'}, 'star': 2})
|
|
254
|
+
body = self.block(n.body, mod)
|
|
255
|
+
return {'id': fid, 'name': n.name, **({'cls': cls} if cls else {}), 'p': where(self.file, n), 'span': [os.path.basename(self.file), n.lineno, n.end_lineno],
|
|
256
|
+
'params': params, 'ret': self.ty(n.returns, mod), 'body': body, 'async': isinstance(n, ast.AsyncFunctionDef), 'decorators': decs, 'static': static}
|
|
257
|
+
finally:
|
|
258
|
+
self.local_stack.pop()
|
|
259
|
+
def decorator(self, d):
|
|
260
|
+
f = d.func if isinstance(d, ast.Call) else d
|
|
261
|
+
return {'name': dotted(f) or text(f), 'text': text(d), 'p': where(self.file, d)}
|
|
262
|
+
def locals_of(self, fn):
|
|
263
|
+
out = {x.arg for x in fn.args.posonlyargs + fn.args.args + fn.args.kwonlyargs}
|
|
264
|
+
if fn.args.vararg: out.add(fn.args.vararg.arg)
|
|
265
|
+
if fn.args.kwarg: out.add(fn.args.kwarg.arg)
|
|
266
|
+
for n in ast.walk(fn):
|
|
267
|
+
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store): out.add(n.id)
|
|
268
|
+
if isinstance(n, (ast.Import, ast.ImportFrom)):
|
|
269
|
+
for a in n.names: out.add((a.asname or a.name).split('.')[0])
|
|
270
|
+
return out
|
|
271
|
+
# --- statements --------------------------------------------------------------------------------------------------
|
|
272
|
+
def block(self, ss, mod):
|
|
273
|
+
out = []
|
|
274
|
+
for s in ss:
|
|
275
|
+
for r in self.stmt(s, mod):
|
|
276
|
+
if r.get('s') == 'no' and 'names' not in r: r['names'] = mentioned(s)
|
|
277
|
+
out.append(r)
|
|
278
|
+
return out
|
|
279
|
+
def stmt(self, s, mod):
|
|
280
|
+
p = where(self.file, s)
|
|
281
|
+
E = lambda x: self.expr(x, mod)
|
|
282
|
+
if isinstance(s, ast.Expr):
|
|
283
|
+
if isinstance(s.value, ast.Constant) and isinstance(s.value.value, str): return [] # a docstring
|
|
284
|
+
return [{'s': 'expr', 'p': p, 'x': E(s.value)}]
|
|
285
|
+
if isinstance(s, ast.Pass): return []
|
|
286
|
+
if isinstance(s, (ast.Assign, ast.AnnAssign)):
|
|
287
|
+
if s.value is None: return [] # a declaration: `x: int`
|
|
288
|
+
targets = s.targets if isinstance(s, ast.Assign) else [s.target]
|
|
289
|
+
x = E(s.value)
|
|
290
|
+
ann = self.ty(s.annotation, mod) if isinstance(s, ast.AnnAssign) else None
|
|
291
|
+
out = []
|
|
292
|
+
for t in targets: out.append({'s': 'set', 'p': p, 'to': self.target(t, mod), 'x': x, **({'t': ann} if ann and ann['k'] != 'any' else {})})
|
|
293
|
+
return out
|
|
294
|
+
if isinstance(s, ast.AugAssign):
|
|
295
|
+
op = self.binop(s.op)
|
|
296
|
+
t = self.target(s.target, mod)
|
|
297
|
+
return [{'s': 'set', 'p': p, 'to': t, 'x': {'e': 'bin', 'op': op, 'x': self.expr(s.target, mod), 'y': E(s.value), 'p': p, 'text': text(s)} if op else {'e': 'no', 'why': f"{text(s)}: {type(s.op).__name__} (outside the subset)", 'p': p}}]
|
|
298
|
+
if isinstance(s, ast.If):
|
|
299
|
+
return [{'s': 'if', 'p': p, 'c': E(s.test), 'then': self.block(s.body, mod), 'else': self.block(s.orelse, mod)}]
|
|
300
|
+
if isinstance(s, ast.Return): return [{'s': 'ret', 'p': p, **({'x': E(s.value)} if s.value is not None else {})}]
|
|
301
|
+
if isinstance(s, ast.Raise):
|
|
302
|
+
return [{'s': 'fail', 'p': p, 'why': f"raise {text(s.exc) if s.exc else ''}".strip(), **({'x': E(s.exc)} if s.exc else {})}]
|
|
303
|
+
if isinstance(s, ast.Assert):
|
|
304
|
+
return [{'s': 'if', 'p': p, 'c': E(s.test), 'then': [], 'else': [{'s': 'fail', 'p': p, 'why': f"assert {text(s.test)}"}]}]
|
|
305
|
+
if isinstance(s, (ast.With, ast.AsyncWith)):
|
|
306
|
+
items = [{'x': E(i.context_expr), **({'as': self.target(i.optional_vars, mod)} if i.optional_vars is not None else {})} for i in s.items]
|
|
307
|
+
return [{'s': 'with', 'p': p, 'items': items, 'body': self.block(s.body, mod), 'async': isinstance(s, ast.AsyncWith)}]
|
|
308
|
+
if isinstance(s, ast.Delete):
|
|
309
|
+
return [{'s': 'del', 'p': p, 'x': self.target(t, mod)} for t in s.targets]
|
|
310
|
+
if isinstance(s, (ast.Import, ast.ImportFrom)):
|
|
311
|
+
names = {}
|
|
312
|
+
for a in s.names:
|
|
313
|
+
if isinstance(s, ast.Import): names[(a.asname or a.name).split('.')[0]] = {'mod': a.name if a.asname else a.name.split('.')[0]}
|
|
314
|
+
else:
|
|
315
|
+
m = resolve_from(self.mod.name, self.mod.is_pkg, s)
|
|
316
|
+
ret = self.ret_of(m, a.name)
|
|
317
|
+
names[a.asname or a.name] = {'mod': m, 'name': a.name, **({'ret': ret} if ret else {})}
|
|
318
|
+
return [{'s': 'import', 'p': p, 'names': names}]
|
|
319
|
+
if isinstance(s, (ast.For, ast.AsyncFor, ast.While)): return [{'s': 'no', 'p': p, 'why': f"a loop ({type(s).__name__.lower().replace('async', 'async ')})"}]
|
|
320
|
+
if isinstance(s, ast.Try) or type(s).__name__ == 'TryStar': return [{'s': 'no', 'p': p, 'why': 'try/except (an exception caught: the subset reads one only as the step\'s failure)'}]
|
|
321
|
+
if isinstance(s, (ast.Global, ast.Nonlocal)): return [{'s': 'no', 'p': p, 'why': f"{type(s).__name__.lower()} (a variable every call shares)"}]
|
|
322
|
+
if isinstance(s, ast.Match): return [{'s': 'no', 'p': p, 'why': 'match'}]
|
|
323
|
+
if isinstance(s, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): return [{'s': 'no', 'p': p, 'why': f"a {'class' if isinstance(s, ast.ClassDef) else 'function'} defined in a function (a closure)"}]
|
|
324
|
+
return [{'s': 'no', 'p': p, 'why': f"{type(s).__name__} (a statement outside the subset)"}]
|
|
325
|
+
def target(self, t, mod):
|
|
326
|
+
p = where(self.file, t)
|
|
327
|
+
if isinstance(t, ast.Name): return {'e': 'var', 'n': t.id, 'p': p}
|
|
328
|
+
if isinstance(t, ast.Attribute): return {'e': 'get', 'x': self.expr(t.value, mod), 'f': t.attr, 'p': p, 'text': text(t)}
|
|
329
|
+
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)}
|
|
330
|
+
if isinstance(t, (ast.Tuple, ast.List)): return {'e': 'tuple', 'xs': [self.target(x, mod) for x in t.elts], 'p': p}
|
|
331
|
+
return {'e': 'no', 'why': f"{text(t)}: an assignment to other than a name, a field or an item", 'p': p}
|
|
332
|
+
|
|
333
|
+
# --- expressions -------------------------------------------------------------------------------------------------
|
|
334
|
+
def binop(self, op):
|
|
335
|
+
return {ast.Add: '+', ast.Sub: '-', ast.Mult: '*', ast.FloorDiv: '//', ast.Mod: '%', ast.Div: '/'}.get(type(op))
|
|
336
|
+
def name(self, n, mod, p):
|
|
337
|
+
"""What a name is where it is read: a local, a constant, a function or class of the module, an import, a builtin."""
|
|
338
|
+
if self.local_stack and n in self.local_stack[-1]: return {'e': 'var', 'n': n, 'p': p}
|
|
339
|
+
if n in mod.funcs: return {'e': 'fn', 'id': n, 'p': p}
|
|
340
|
+
if n in mod.classes:
|
|
341
|
+
q = self.rec_of(mod, mod.classes[n])
|
|
342
|
+
return {'e': 'cls', 'rec': q, 'p': p}
|
|
343
|
+
if n in mod.imports:
|
|
344
|
+
imp = mod.imports[n]
|
|
345
|
+
if imp[0] == 'module': return {'e': 'ext', 'q': imp[1], 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'p': p}
|
|
346
|
+
hit = self.find_class(mod, n)
|
|
347
|
+
if hit: return {'e': 'cls', 'rec': self.rec_of(*hit), 'q': f"{imp[1]}.{imp[2]}", 'patch': {'mod': mod.name, 'path': [n]}, 'p': p}
|
|
348
|
+
ret = self.ret_of(imp[1], imp[2])
|
|
349
|
+
return {'e': 'ext', 'q': f"{imp[1]}.{imp[2]}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'p': p, **({'ret': ret} if ret else {})}
|
|
350
|
+
if n in mod.consts:
|
|
351
|
+
v = mod.consts[n]
|
|
352
|
+
if isinstance(v, ast.Constant) or (isinstance(v, ast.UnaryOp) and isinstance(v.operand, ast.Constant)): return self.expr(v, mod)
|
|
353
|
+
return {'e': 'ext', 'q': f"{mod.name}.{n}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'global': True, 'p': p}
|
|
354
|
+
if n in ('True', 'False', 'None'): return self.expr(ast.Constant({'True': True, 'False': False, 'None': None}[n]), mod)
|
|
355
|
+
if n in BUILTINS: return {'e': 'builtin', 'n': n, 'p': p}
|
|
356
|
+
return {'e': 'ext', 'q': n, 'text': n, 'p': p, 'unbound': True}
|
|
357
|
+
def expr(self, x, mod):
|
|
358
|
+
r = self.expr1(x, mod)
|
|
359
|
+
if r.get('e') == 'no' and 'names' not in r: r['names'] = mentioned(x)
|
|
360
|
+
return r
|
|
361
|
+
def expr1(self, x, mod):
|
|
362
|
+
p = where(self.file, x)
|
|
363
|
+
E = lambda y: self.expr(y, mod)
|
|
364
|
+
if isinstance(x, ast.Constant):
|
|
365
|
+
v = x.value
|
|
366
|
+
if isinstance(v, bool): return {'e': 'bool', 'v': v, 'p': p}
|
|
367
|
+
if isinstance(v, int): return {'e': 'int', 'v': str(v), 'p': p}
|
|
368
|
+
if isinstance(v, float):
|
|
369
|
+
if v.is_integer() and abs(v) < 2 ** 53: return {'e': 'int', 'v': str(int(v)), 'float': True, 'p': p}
|
|
370
|
+
return {'e': 'no', 'why': f"{text(x)}: a float that isn't whole (a binary fraction)", 'p': p}
|
|
371
|
+
if isinstance(v, str): return {'e': 'str', 'v': v, 'p': p}
|
|
372
|
+
if v is None: return {'e': 'none', 'p': p}
|
|
373
|
+
return {'e': 'no', 'why': f"{text(x)}: a constant outside the subset", 'p': p}
|
|
374
|
+
if isinstance(x, ast.Name): return self.name(x.id, mod, p)
|
|
375
|
+
if isinstance(x, ast.Attribute):
|
|
376
|
+
d = dotted(x)
|
|
377
|
+
base = d.split('.')[0] if d else None
|
|
378
|
+
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]):
|
|
379
|
+
q = mod.imports[base][1] + d[len(base):]
|
|
380
|
+
if q in KNOWN: return {'e': 'lib', 'q': q, 'p': p}
|
|
381
|
+
ret = self.ret_of(q.rpartition('.')[0], q.rpartition('.')[2])
|
|
382
|
+
return {'e': 'ext', 'q': q, 'text': d, 'patch': {'mod': mod.name, 'path': d.split('.')}, 'p': p, **({'ret': ret} if ret else {})}
|
|
383
|
+
return {'e': 'get', 'x': E(x.value), 'f': x.attr, 'p': p, 'text': text(x)}
|
|
384
|
+
if isinstance(x, ast.BinOp):
|
|
385
|
+
op = self.binop(x.op)
|
|
386
|
+
if not op: return {'e': 'no', 'why': f"{text(x)}: {type(x.op).__name__} (outside the subset)", 'p': p}
|
|
387
|
+
return {'e': 'bin', 'op': op, 'x': E(x.left), 'y': E(x.right), 'p': p, 'text': text(x)}
|
|
388
|
+
if isinstance(x, ast.UnaryOp):
|
|
389
|
+
if isinstance(x.op, ast.USub): return {'e': 'neg', 'x': E(x.operand), 'p': p}
|
|
390
|
+
if isinstance(x.op, ast.UAdd): return E(x.operand)
|
|
391
|
+
if isinstance(x.op, ast.Not): return {'e': 'not', 'x': E(x.operand), 'p': p}
|
|
392
|
+
return {'e': 'no', 'why': f"{text(x)}: a bit operation", 'p': p}
|
|
393
|
+
if isinstance(x, ast.BoolOp): return {'e': 'and' if isinstance(x.op, ast.And) else 'or', 'xs': [E(v) for v in x.values], 'p': p}
|
|
394
|
+
if isinstance(x, ast.Compare):
|
|
395
|
+
ops = {ast.Lt: '<', ast.LtE: '<=', ast.Gt: '>', ast.GtE: '>=', ast.Eq: '==', ast.NotEq: '!=', ast.Is: 'is', ast.IsNot: 'is not', ast.In: 'in', ast.NotIn: 'not in'}
|
|
396
|
+
parts, left = [], x.left
|
|
397
|
+
for op, right in zip(x.ops, x.comparators):
|
|
398
|
+
parts.append({'e': 'cmp', 'op': ops[type(op)], 'x': E(left), 'y': E(right), 'p': p, 'text': text(x)})
|
|
399
|
+
left = right
|
|
400
|
+
return parts[0] if len(parts) == 1 else {'e': 'and', 'xs': parts, 'p': p}
|
|
401
|
+
if isinstance(x, ast.IfExp): return {'e': 'ite', 'c': E(x.test), 'a': E(x.body), 'b': E(x.orelse), 'p': p}
|
|
402
|
+
if isinstance(x, ast.Await): return {'e': 'await', 'x': E(x.value), 'p': p}
|
|
403
|
+
if isinstance(x, ast.Call):
|
|
404
|
+
f = E(x.func)
|
|
405
|
+
if f.get('e') == 'ext' and f.get('q') in KNOWN: f = {'e': 'lib', 'q': f['q'], 'p': f['p']}
|
|
406
|
+
args = [E(a) if not isinstance(a, ast.Starred) else {'e': 'no', 'why': f"{text(a)}: *args", 'p': p} for a in x.args]
|
|
407
|
+
kw = [[k.arg, E(k.value)] if k.arg else ['**', {'e': 'no', 'why': f"**{text(k.value)}", 'p': p}] for k in x.keywords]
|
|
408
|
+
return {'e': 'call', 'f': f, 'args': args, 'kw': kw, 'p': p, 'text': text(x)}
|
|
409
|
+
if isinstance(x, ast.Subscript): return {'e': 'idx', 'x': E(x.value), 'i': E(x.slice), 'p': p, 'text': text(x)}
|
|
410
|
+
if isinstance(x, ast.Dict):
|
|
411
|
+
if any(k is None for k in x.keys): return {'e': 'no', 'why': f"{text(x)}: a dict spread", 'p': p}
|
|
412
|
+
return {'e': 'dict', 'keys': [E(k) for k in x.keys], 'vals': [E(v) for v in x.values], 'p': p}
|
|
413
|
+
if isinstance(x, ast.Tuple): return {'e': 'tuple', 'xs': [E(v) for v in x.elts], 'p': p}
|
|
414
|
+
if isinstance(x, ast.JoinedStr):
|
|
415
|
+
parts = []
|
|
416
|
+
for v in x.values:
|
|
417
|
+
if isinstance(v, ast.Constant): parts.append(v.value)
|
|
418
|
+
elif isinstance(v, ast.FormattedValue): parts.append({'x': E(v.value), 'plain': v.conversion == -1 and v.format_spec is None})
|
|
419
|
+
return {'e': 'fstr', 'parts': parts, 'p': p, 'text': text(x)}
|
|
420
|
+
if isinstance(x, ast.List): return {'e': 'list', 'xs': [E(v) for v in x.elts], 'p': p}
|
|
421
|
+
if isinstance(x, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): return {'e': 'no', 'why': f"{text(x)}: a comprehension (a loop)", 'p': p}
|
|
422
|
+
if isinstance(x, ast.Lambda): return {'e': 'no', 'why': f"{text(x)}: a lambda (a closure)", 'p': p}
|
|
423
|
+
return {'e': 'no', 'why': f"{text(x)}: {type(x).__name__} (outside the subset)", 'p': p}
|
|
424
|
+
|
|
425
|
+
def main():
|
|
426
|
+
req = json.loads(sys.argv[1])
|
|
427
|
+
r = Reader(req['root'], req['file'])
|
|
428
|
+
mod = r.mod
|
|
429
|
+
if mod.tree is None:
|
|
430
|
+
print(json.dumps({'error': f"{req['file']} doesn't parse"})); return
|
|
431
|
+
out = {'lang': 'python', 'file': os.path.basename(r.file), 'path': r.file, 'module': mod.name, 'root': os.path.abspath(req['root']), 'entries': []}
|
|
432
|
+
for n in req['names'] or list(mod.classes):
|
|
433
|
+
if n in mod.classes: out['entries'].append({'k': 'class', 'rec': r.rec_of(mod, mod.classes[n])})
|
|
434
|
+
elif n in mod.funcs:
|
|
435
|
+
r.local_stack = []
|
|
436
|
+
r.funcs[n] = r.func(mod.funcs[n], mod, None, n)
|
|
437
|
+
out['entries'].append({'k': 'func', 'id': n})
|
|
438
|
+
else: out['entries'].append({'k': 'missing', 'name': n})
|
|
439
|
+
# The module's other functions, for the calls the entries make (each read once).
|
|
440
|
+
for n, f in mod.funcs.items():
|
|
441
|
+
if n not in r.funcs: r.funcs[n] = r.func(f, mod, None, n)
|
|
442
|
+
out['recs'] = {k: v for k, v in r.recs.items() if v}
|
|
443
|
+
out['funcs'] = r.funcs
|
|
444
|
+
print(json.dumps(out))
|
|
445
|
+
|
|
446
|
+
if __name__ == '__main__':
|
|
447
|
+
main()
|