gdp-wired 0.43.0 → 0.45.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 +8 -3
- package/dist/core/c/reader.js +22 -7
- package/dist/core/check.js +3 -2
- package/dist/core/cli.d.ts +7 -0
- package/dist/core/cli.js +184 -12
- package/dist/core/counts.d.ts +1 -1
- package/dist/core/counts.js +30 -12
- package/dist/core/data.d.ts +6 -1
- package/dist/core/data.js +894 -152
- package/dist/core/dsl.d.ts +2 -0
- package/dist/core/dsl.js +88 -10
- package/dist/core/effect-prims.d.ts +60 -0
- package/dist/core/effect-prims.js +625 -0
- package/dist/core/effect.d.ts +17 -1
- package/dist/core/effect.js +108 -4
- package/dist/core/ex/harness.exs +2 -0
- package/dist/core/ex/reader.exs +17 -1
- package/dist/core/exists.d.ts +15 -1
- package/dist/core/exists.js +263 -41
- package/dist/core/extract-c.d.ts +2 -0
- package/dist/core/extract-c.js +22 -13
- package/dist/core/extract-check.d.ts +7 -0
- package/dist/core/extract-check.js +57 -4
- package/dist/core/extract-ex.js +5 -5
- package/dist/core/extract-go-check.js +22 -17
- package/dist/core/extract-go.d.ts +3 -0
- package/dist/core/extract-go.js +24 -9
- package/dist/core/extract-jvm.js +68 -16
- package/dist/core/extract-print.js +3 -0
- package/dist/core/extract-py.js +5 -5
- package/dist/core/extract-rb.js +5 -5
- package/dist/core/extract-read.d.ts +8 -0
- package/dist/core/extract-read.js +55 -0
- package/dist/core/extract-rs.js +28 -25
- package/dist/core/extract-shapes.js +20 -0
- package/dist/core/extract-sol.js +23 -12
- package/dist/core/extract-step.d.ts +59 -3
- package/dist/core/extract-step.js +334 -64
- package/dist/core/extract-swift.js +22 -15
- package/dist/core/extract.d.ts +1 -0
- package/dist/core/extract.js +27 -2
- 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.js +113 -40
- package/dist/core/jvm/Harness.java +8 -1
- package/dist/core/jvm/JavaReader.java +10 -2
- package/dist/core/jvm/Jvm.java +18 -2
- package/dist/core/jvm/KtReader.java +60 -5
- package/dist/core/machine.d.ts +2 -0
- package/dist/core/machine.js +32 -6
- package/dist/core/py/harness.py +128 -24
- package/dist/core/py/reader.py +50 -5
- package/dist/core/rb/reader.rb +52 -5
- package/dist/core/rs/src/main.rs +10 -0
- package/dist/core/sol/Replay.sol +52 -0
- package/dist/core/sol/harness.py +511 -0
- package/dist/core/solver.js +5 -4
- package/dist/core/system.d.ts +62 -1
- package/dist/core/system.js +274 -6
- package/dist/core/transfer.js +17 -0
- package/dist/core/watch.js +1 -1
- package/dist/interchange/check.d.ts +18 -1
- package/dist/interchange/check.js +19 -12
- package/dist/interchange/cli.d.ts +2 -0
- package/dist/interchange/cli.js +45 -0
- package/dist/interchange/format.d.ts +5 -1
- package/dist/interchange/format.js +25 -9
- package/dist/kernel/cdcl.js +65 -14
- package/dist/kernel/epr.js +35 -5
- package/dist/kernel/kernel.d.ts +2 -0
- package/dist/kernel/kernel.js +67 -40
- package/dist/kernel/prove.d.ts +22 -0
- package/dist/kernel/prove.js +156 -7
- package/dist/kernel/reader.js +3 -2
- package/dist/lean-kernel/emit.d.ts +9 -3
- package/dist/lean-kernel/emit.js +170 -29
- package/dist/lean-kernel/library.js +1 -1
- package/package.json +12 -3
package/dist/core/py/reader.py
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
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, 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).
|
|
@@ -40,6 +40,25 @@ def injected(d):
|
|
|
40
40
|
f = d.func if isinstance(d, ast.Call) else d.value if isinstance(d, ast.Subscript) else None
|
|
41
41
|
return (dotted(f) or '').split('.')[-1] in ('Depends', 'Provide', 'Inject') if f is not None else False
|
|
42
42
|
|
|
43
|
+
def missing(q):
|
|
44
|
+
"""Why the attribute path q (a module's, `logging.getLo`) fails where it runs, or None: the module object's own method
|
|
45
|
+
(`m.__init__`), or a name a module of Python's own library doesn't have (that module imported to look: the code
|
|
46
|
+
imports it too)."""
|
|
47
|
+
parts = q.split('.')
|
|
48
|
+
for i, n in enumerate(parts[1:], 1):
|
|
49
|
+
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)"
|
|
50
|
+
if parts[0] not in getattr(sys, 'stdlib_module_names', ()) or parts[0] in ('this', 'antigravity', '__main__'): return None
|
|
51
|
+
try:
|
|
52
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): o = importlib.import_module(parts[0])
|
|
53
|
+
for i, n in enumerate(parts[1:], 1):
|
|
54
|
+
if hasattr(o, n): o = getattr(o, n); continue
|
|
55
|
+
if not isinstance(o, types.ModuleType): return None
|
|
56
|
+
try:
|
|
57
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): o = importlib.import_module('.'.join(parts[:i + 1]))
|
|
58
|
+
except ImportError: return f"{'.'.join(parts[:i + 1])}: {'.'.join(parts[:i])} has no {n} (an AttributeError where it runs)"
|
|
59
|
+
except Exception: return None
|
|
60
|
+
return None
|
|
61
|
+
|
|
43
62
|
class Repo:
|
|
44
63
|
"""The repository's modules, parsed once each, for the classes an annotation names."""
|
|
45
64
|
def __init__(self, root):
|
|
@@ -76,6 +95,22 @@ class Module:
|
|
|
76
95
|
self.imports, self.classes, self.funcs, self.consts = {}, {}, {}, {}
|
|
77
96
|
for n in (self.tree.body if self.tree else []):
|
|
78
97
|
self.scan(n)
|
|
98
|
+
# (the module's variables a function rebinds, `global x`: no constant, every call shares them; and the names the
|
|
99
|
+
# module binds at its top level and in its classes' bodies, or may through `from m import *`: past them and a
|
|
100
|
+
# function's own, a name is a NameError where it runs)
|
|
101
|
+
walk = list(ast.walk(self.tree)) if self.tree else []
|
|
102
|
+
self.rebound = {g for x in walk if isinstance(x, ast.Global) for g in x.names}
|
|
103
|
+
self.star = any(isinstance(x, ast.ImportFrom) and any(a.name == '*' for a in x.names) for x in walk)
|
|
104
|
+
self.bound, todo = set(self.rebound), list(self.tree.body if self.tree else [])
|
|
105
|
+
while todo:
|
|
106
|
+
x = todo.pop()
|
|
107
|
+
if isinstance(x, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): self.bound.add(x.name)
|
|
108
|
+
if isinstance(x, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): continue
|
|
109
|
+
if isinstance(x, ast.Name) and not isinstance(x.ctx, ast.Load): self.bound.add(x.id)
|
|
110
|
+
if isinstance(x, (ast.Import, ast.ImportFrom)): self.bound |= {(a.asname or a.name).split('.')[0] for a in x.names}
|
|
111
|
+
if isinstance(x, (ast.ExceptHandler, ast.MatchAs, ast.MatchStar)) and x.name: self.bound.add(x.name)
|
|
112
|
+
if isinstance(x, ast.MatchMapping) and x.rest: self.bound.add(x.rest)
|
|
113
|
+
todo.extend(x.body if isinstance(x, ast.ClassDef) else ast.iter_child_nodes(x))
|
|
79
114
|
def scan(self, n):
|
|
80
115
|
if isinstance(n, ast.Import):
|
|
81
116
|
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])
|
|
@@ -194,7 +229,11 @@ class Reader:
|
|
|
194
229
|
name, t = n.targets[0].attr, self.ty(anns[v.values[0].id], mod)
|
|
195
230
|
if t['k'] == 'opt': t = t['of']
|
|
196
231
|
if t is not None and not any(g['name'] == name for g in fields): fields.append({'name': name, 't': t, 'init': True})
|
|
232
|
+
cattrs = {}
|
|
197
233
|
for n in cdef.body:
|
|
234
|
+
# (a class attribute set to a constant, PREFIX = None, LOCK_PERIOD = 5: read through self as that constant)
|
|
235
|
+
if isinstance(n, ast.Assign) and len(n.targets) == 1 and isinstance(n.targets[0], ast.Name) and isinstance(n.value, ast.Constant) and isinstance(n.value.value, (int, float, str, bool, type(None))) and not isinstance(n.value.value, bytes):
|
|
236
|
+
cattrs[n.targets[0].id] = n.value.value
|
|
198
237
|
if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name):
|
|
199
238
|
ann = n.annotation
|
|
200
239
|
if dotted(ann.value if isinstance(ann, ast.Subscript) else ann) in ('ClassVar', 'typing.ClassVar'): continue
|
|
@@ -212,7 +251,7 @@ class Reader:
|
|
|
212
251
|
finally: self.file, self.supers = file, sup
|
|
213
252
|
methods[n.name] = fid
|
|
214
253
|
else: methods[n.name] = None # another module's method: not read
|
|
215
|
-
r = {'name': q, 'short': cdef.name, 'fields': fields, 'methods': methods, 'bases': bases, 'p': where(mod.path, cdef),
|
|
254
|
+
r = {'name': q, 'short': cdef.name, 'fields': fields, 'methods': methods, 'bases': bases, 'p': where(mod.path, cdef), 'cattrs': cattrs,
|
|
216
255
|
'kinds': sorted(kinds | ({'dataclass'} if dataclass else set()) | ({'frozen'} if frozen else set()) | (set() if total else {'partial'})),
|
|
217
256
|
'own': mod.path == self.file, 'module': mod.name, **({'rets': rets} if rets else {})}
|
|
218
257
|
self.recs[q] = r
|
|
@@ -362,7 +401,8 @@ class Reader:
|
|
|
362
401
|
return [{'s': 'expr', 'p': p, 'x': E(s.value)}]
|
|
363
402
|
if isinstance(s, ast.Pass): return []
|
|
364
403
|
if isinstance(s, (ast.Assign, ast.AnnAssign)):
|
|
365
|
-
|
|
404
|
+
# (a declaration, `x: int`; of a field or an item, `o.f: int`, its object evaluated, and the item's index)
|
|
405
|
+
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
406
|
targets = s.targets if isinstance(s, ast.Assign) else [s.target]
|
|
367
407
|
x = E(s.value)
|
|
368
408
|
ann = self.ty(s.annotation, mod) if isinstance(s, ast.AnnAssign) else None
|
|
@@ -458,6 +498,7 @@ class Reader:
|
|
|
458
498
|
def name(self, n, mod, p):
|
|
459
499
|
"""What a name is where it is read: a local, a constant, a function or class of the module, an import, a builtin."""
|
|
460
500
|
if self.local_stack and n in self.local_stack[-1]: return {'e': 'var', 'n': n, 'p': p}
|
|
501
|
+
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
502
|
if n in mod.funcs: return {'e': 'fn', 'id': n, 'p': p}
|
|
462
503
|
if n in mod.classes:
|
|
463
504
|
q = self.rec_of(mod, mod.classes[n])
|
|
@@ -486,7 +527,9 @@ class Reader:
|
|
|
486
527
|
return {'e': 'ext', 'q': f"{mod.name}.{n}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'global': True, 'p': p}
|
|
487
528
|
if n in ('True', 'False', 'None'): return self.expr(ast.Constant({'True': True, 'False': False, 'None': None}[n]), mod)
|
|
488
529
|
if n in BUILTINS: return {'e': 'builtin', 'n': n, 'p': p}
|
|
489
|
-
|
|
530
|
+
if n not in mod.bound and not mod.star and not hasattr(builtins, n) and not (n.startswith('__') and n.endswith('__')):
|
|
531
|
+
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}
|
|
532
|
+
return {'e': 'ext', 'q': n, 'text': n, 'p': p}
|
|
490
533
|
def expr(self, x, mod):
|
|
491
534
|
r = self.expr1(x, mod)
|
|
492
535
|
if r.get('e') == 'no' and 'names' not in r: r['names'] = mentioned(x)
|
|
@@ -515,6 +558,8 @@ class Reader:
|
|
|
515
558
|
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
559
|
q = mod.imports[base][1] + d[len(base):]
|
|
517
560
|
if q in KNOWN: return {'e': 'lib', 'q': q, 'p': p}
|
|
561
|
+
why = missing(q) if not self.repo.path_of(q.split('.')[0]) else None
|
|
562
|
+
if why: return {'e': 'no', 'why': why, 'raises': True, 'p': p}
|
|
518
563
|
ret = self.ret_of(q.rpartition('.')[0], q.rpartition('.')[2])
|
|
519
564
|
return {'e': 'ext', 'q': q, 'text': d, 'patch': {'mod': mod.name, 'path': d.split('.')}, 'p': p, **({'ret': ret} if ret else {})}
|
|
520
565
|
return {'e': 'get', 'x': E(x.value), 'f': x.attr, 'p': p, 'text': text(x)}
|
|
@@ -593,7 +638,7 @@ def main():
|
|
|
593
638
|
print(json.dumps({'error': f"{req['file']} doesn't parse"})); return
|
|
594
639
|
out = {'lang': 'python', 'file': os.path.basename(r.file), 'path': r.file, 'module': mod.name, 'root': os.path.abspath(req['root']), 'entries': [],
|
|
595
640
|
# (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())}}
|
|
641
|
+
'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
642
|
for n in req['names'] or list(mod.classes):
|
|
598
643
|
if n in mod.classes: out['entries'].append({'k': 'class', 'rec': r.rec_of(mod, mod.classes[n])})
|
|
599
644
|
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
|
package/dist/core/rs/src/main.rs
CHANGED
|
@@ -61,6 +61,10 @@ impl Reader {
|
|
|
61
61
|
}
|
|
62
62
|
fn load_file(root: &Path, rel: &Path, module: &str, out: &mut Vec<File>) -> Result<(), String> {
|
|
63
63
|
let src = std::fs::read_to_string(root.join(rel)).map_err(|e| format!("{}: {e}", rel.display()))?;
|
|
64
|
+
// (syn's parser and the lowering recurse on each level of nesting: past MAX_DEPTH brackets the source is refused, said
|
|
65
|
+
// so as core/extract-read.ts's statedRefusal reads it, before any recursion could pass the reader's stack)
|
|
66
|
+
let deep = src.chars().fold((0i64, 0i64), |(d, m), c| match c { '(' | '[' | '{' => (d + 1, m.max(d + 1)), ')' | ']' | '}' => (d - 1, m), _ => (d, m) }).1;
|
|
67
|
+
if deep > MAX_DEPTH { eprintln!("gdp: refused: {}: the source nests {deep} brackets deep (past {MAX_DEPTH})", rel.display()); std::process::exit(3) }
|
|
64
68
|
let f = syn::parse_file(&src).map_err(|e| format!("{}: {e}", rel.display()))?;
|
|
65
69
|
let dir: PathBuf = if rel.file_name().map(|n| n == "lib.rs" || n == "main.rs" || n == "mod.rs").unwrap_or(false) { rel.parent().unwrap().to_path_buf() } else { rel.with_extension("") };
|
|
66
70
|
let mut items = vec![];
|
|
@@ -654,7 +658,13 @@ fn assigns(e: &Expr, n: &str) -> bool {
|
|
|
654
658
|
false
|
|
655
659
|
}
|
|
656
660
|
|
|
661
|
+
const MAX_DEPTH: i64 = 1000;
|
|
662
|
+
// The reader on a thread of 1 GiB of stack (reserved, not used): MAX_DEPTH levels of syn's recursion fit in it.
|
|
657
663
|
fn main() {
|
|
664
|
+
let t = std::thread::Builder::new().stack_size(1 << 30).spawn(run).expect("a thread");
|
|
665
|
+
if t.join().is_err() { std::process::exit(101) }
|
|
666
|
+
}
|
|
667
|
+
fn run() {
|
|
658
668
|
let req: Value = serde_json::from_str(&std::env::args().nth(1).expect("a request")).expect("JSON");
|
|
659
669
|
let root = PathBuf::from(req["root"].as_str().unwrap());
|
|
660
670
|
let files = match Reader::load(&root) { Ok(f) => f, Err(e) => { println!("{}", json!({"error": e})); return } };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
pragma solidity ^0.8.20;
|
|
3
|
+
|
|
4
|
+
// The re-entrant runs of core/extract-sol.ts replayed on the code: every address a run names is an Agent (its code set
|
|
5
|
+
// there), and one Director holds the run's script. A call of the script is made by its Agent; a call into an Agent (the
|
|
6
|
+
// contract sending it a value) runs the script's next calls from inside it, up to a return (the Agent's call returns, or
|
|
7
|
+
// reverts). The Director records whether each call of the script succeeded.
|
|
8
|
+
interface IDirector { function onCall() external returns (bool); }
|
|
9
|
+
|
|
10
|
+
contract Agent {
|
|
11
|
+
address constant DIRECTOR = address(uint160(0xD1EC70));
|
|
12
|
+
function act(address t, uint256 v, bytes calldata d) external returns (bool ok) {
|
|
13
|
+
require(msg.sender == DIRECTOR, "agent: the director only");
|
|
14
|
+
(ok, ) = t.call{value: v}(d);
|
|
15
|
+
}
|
|
16
|
+
receive() external payable { if (!IDirector(DIRECTOR).onCall()) revert("agent: the callee reverts"); }
|
|
17
|
+
fallback() external payable { if (!IDirector(DIRECTOR).onCall()) revert("agent: the callee reverts"); }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
contract Director {
|
|
21
|
+
uint8[] kinds;
|
|
22
|
+
address[] froms;
|
|
23
|
+
uint256[] values;
|
|
24
|
+
bool[] rets;
|
|
25
|
+
bytes[] datas;
|
|
26
|
+
uint256 at;
|
|
27
|
+
address target;
|
|
28
|
+
bool[] public oks;
|
|
29
|
+
|
|
30
|
+
// One transaction of the run: its first call, and inside it every call and return the script holds.
|
|
31
|
+
function run(address t, uint8[] calldata k, address[] calldata f, uint256[] calldata v, bool[] calldata r, bytes[] calldata d) external {
|
|
32
|
+
target = t; kinds = k; froms = f; values = v; rets = r; at = 0;
|
|
33
|
+
delete datas;
|
|
34
|
+
delete oks;
|
|
35
|
+
for (uint256 i; i < d.length; i++) datas.push(d[i]);
|
|
36
|
+
step();
|
|
37
|
+
require(at == kinds.length, "director: the script is left over");
|
|
38
|
+
}
|
|
39
|
+
function step() internal {
|
|
40
|
+
uint256 i = at++;
|
|
41
|
+
require(kinds[i] == 0, "director: a return outside a call");
|
|
42
|
+
oks.push(Agent(payable(froms[i])).act(target, values[i], datas[i]));
|
|
43
|
+
}
|
|
44
|
+
function onCall() external returns (bool) {
|
|
45
|
+
while (at < kinds.length) {
|
|
46
|
+
if (kinds[at] == 1) return rets[at++];
|
|
47
|
+
step();
|
|
48
|
+
}
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
function count() external view returns (uint256) { return oks.length; }
|
|
52
|
+
}
|