inets 0.1.0__py3-none-any.whl
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.
- inets/__init__.py +25 -0
- inets/__main__.py +104 -0
- inets/errors.py +22 -0
- inets/ivm.py +205 -0
- inets/ivy.py +188 -0
- inets/net.py +470 -0
- inets/ski.py +382 -0
- inets/system.py +542 -0
- inets/systems/__init__.py +0 -0
- inets/systems/combinators.rules +36 -0
- inets/systems/ivm.rules +112 -0
- inets/systems/lazy.rules +250 -0
- inets/systems/ski.rules +150 -0
- inets-0.1.0.dist-info/METADATA +286 -0
- inets-0.1.0.dist-info/RECORD +19 -0
- inets-0.1.0.dist-info/WHEEL +5 -0
- inets-0.1.0.dist-info/entry_points.txt +2 -0
- inets-0.1.0.dist-info/licenses/LICENSE +21 -0
- inets-0.1.0.dist-info/top_level.txt +1 -0
inets/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Interaction nets: declare a system as a table of rules, check it, and reduce nets by it.
|
|
2
|
+
|
|
3
|
+
>>> import inets
|
|
4
|
+
>>> system = inets.bundled("combinators")
|
|
5
|
+
>>> system.check()
|
|
6
|
+
[]
|
|
7
|
+
>>> net = inets.Net(system)
|
|
8
|
+
>>> a, b = net.free(), net.free()
|
|
9
|
+
>>> net.wire(net.make("con", a, b), net.make("dup", net.make("era"), net.make("era")))
|
|
10
|
+
>>> result = net.reduce()
|
|
11
|
+
>>> result.reason, result.counts
|
|
12
|
+
('normal', {'commute': 1, 'erase': 2})
|
|
13
|
+
|
|
14
|
+
See :mod:`inets.system` for the table format, :mod:`inets.net` for nets and schedules,
|
|
15
|
+
:mod:`inets.ski` for the combinators S, K and I as agents, :mod:`inets.ivm` for programs
|
|
16
|
+
of Vine's IVM, and :mod:`inets.ivy` for Ivy text.
|
|
17
|
+
"""
|
|
18
|
+
from .errors import Error, IvyError, Stuck, TableError, TermError
|
|
19
|
+
from .net import Host, Library, Net, Port, Result
|
|
20
|
+
from .system import Agent, Rule, System, bundled
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
|
|
24
|
+
__all__ = ["System", "Agent", "Rule", "bundled", "Net", "Port", "Result", "Host", "Library",
|
|
25
|
+
"Error", "TableError", "IvyError", "TermError", "Stuck"]
|
inets/__main__.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""The command line.
|
|
2
|
+
|
|
3
|
+
inets check TABLE check a table: a file, or a bundled name
|
|
4
|
+
inets rules TABLE list a table's rules, marking those that are not local
|
|
5
|
+
inets run ski TERM [--rounds | --lazy] [--dot]
|
|
6
|
+
reduce a term of S, K, I (prefix form): by need, or
|
|
7
|
+
with every pair fired, by the ski or the lazy table;
|
|
8
|
+
--dot prints the net left, as Graphviz text
|
|
9
|
+
inets run ivm FILE.iv run a program of Vine's IVM
|
|
10
|
+
inets demo one term, K I Ω, reduced three ways
|
|
11
|
+
|
|
12
|
+
The bundled tables are combinators, ski, lazy and ivm. `python -m inets` is the same.
|
|
13
|
+
"""
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
from . import Error, System, bundled, ivm, ski
|
|
17
|
+
from .system import BUNDLED
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def table(name):
|
|
21
|
+
return bundled(name) if name in BUNDLED else System.load(name)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def show_result(result):
|
|
25
|
+
extra = f", {result.rounds} rounds, widest {result.widest}" if result.rounds else ""
|
|
26
|
+
counts = ", ".join(f"{k} {v}" for k, v in sorted(result.counts.items()))
|
|
27
|
+
print(f"stopped: {result.reason}; {result.interactions} interactions{extra}; "
|
|
28
|
+
f"{result.active_left} active pairs left" + (f"; {counts}" if counts else ""), file=sys.stderr)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def demo():
|
|
32
|
+
term = "``KI```SII``SII"
|
|
33
|
+
print("One term, K I Ω, where Ω reduces to itself without end. K discards its second argument,")
|
|
34
|
+
print("so the term has the normal form I. Whether a net reaches it depends on which pairs fire.\n")
|
|
35
|
+
for schedule, title, cap in (("need", "ski table, by need: only the pairs the answer depends on", 10 ** 4),
|
|
36
|
+
("rounds", "ski table, every pair fired: Ω runs although K will discard it", 300),
|
|
37
|
+
("lazy", "lazy table, every pair fired: the demand is carried in the net, and no work is shared", 10 ** 4)):
|
|
38
|
+
run = ski.run(term, schedule=schedule, max_interactions=cap)
|
|
39
|
+
r = run.result
|
|
40
|
+
answer = ski.show(run.term) if r.finished else f"none: stopped at the cap of {cap} interactions"
|
|
41
|
+
print(title)
|
|
42
|
+
print(f" answer {answer}; {r.interactions} interactions, of which {r.counts.get('contract', 0)} contractions; "
|
|
43
|
+
f"stopped because: {r.reason}; active pairs left: {r.active_left}")
|
|
44
|
+
print("\nBy need stops with active pairs left: what it reaches is a normal form of what the root can")
|
|
45
|
+
print("reach, not of the whole net. Ω is still there, unreduced, until it is swept away.")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def command(args):
|
|
49
|
+
if not args or args[0] in ("-h", "--help"):
|
|
50
|
+
print(__doc__)
|
|
51
|
+
return 0
|
|
52
|
+
verb, args = args[0], args[1:]
|
|
53
|
+
if verb == "check" and len(args) == 1:
|
|
54
|
+
system = table(args[0])
|
|
55
|
+
problems = system.check()
|
|
56
|
+
print(f"{len(system.agents)} agents, {len(system.rules)} rules, {'with' if system.signed else 'without'} signs; "
|
|
57
|
+
f"{len(problems)} problems")
|
|
58
|
+
for p in problems:
|
|
59
|
+
print(" " + p)
|
|
60
|
+
return 1 if problems else 0
|
|
61
|
+
if verb == "rules" and len(args) == 1:
|
|
62
|
+
for r in table(args[0]).rules:
|
|
63
|
+
print(f"{r.count or '?':<11} {r}" + (f" [not local: {', '.join(r.not_local)}]" if r.not_local else ""))
|
|
64
|
+
return 0
|
|
65
|
+
if verb == "run" and len(args) >= 2 and args[0] == "ski":
|
|
66
|
+
flags = [a for a in args[1:] if a.startswith("--")]
|
|
67
|
+
terms = [a for a in args[1:] if not a.startswith("--")]
|
|
68
|
+
if len(terms) != 1 or any(f not in ("--rounds", "--lazy", "--dot") for f in flags) or {"--rounds", "--lazy"} <= set(flags):
|
|
69
|
+
print(__doc__)
|
|
70
|
+
return 2
|
|
71
|
+
schedule = "rounds" if "--rounds" in flags else "lazy" if "--lazy" in flags else "need"
|
|
72
|
+
run = ski.run(terms[0], schedule=schedule)
|
|
73
|
+
if "--dot" in flags:
|
|
74
|
+
print(run.net.dot())
|
|
75
|
+
else:
|
|
76
|
+
print(ski.show(run.term) if run.result.finished else "stopped at the cap")
|
|
77
|
+
show_result(run.result)
|
|
78
|
+
return 0 if run.result.finished else 1
|
|
79
|
+
if verb == "run" and len(args) == 2 and args[0] == "ivm":
|
|
80
|
+
with open(args[1], encoding="utf-8") as f:
|
|
81
|
+
run = ivm.run(f.read())
|
|
82
|
+
sys.stdout.write(run.output)
|
|
83
|
+
sys.stdout.flush()
|
|
84
|
+
show_result(run.result)
|
|
85
|
+
if run.flags:
|
|
86
|
+
print("flags: " + ", ".join(sorted(run.flags)), file=sys.stderr)
|
|
87
|
+
return 1 if run.flags or not run.result.finished else 0
|
|
88
|
+
if verb == "demo" and not args:
|
|
89
|
+
demo()
|
|
90
|
+
return 0
|
|
91
|
+
print(__doc__)
|
|
92
|
+
return 2
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def main(argv=None):
|
|
96
|
+
try:
|
|
97
|
+
return command(list(sys.argv[1:] if argv is None else argv))
|
|
98
|
+
except (Error, OSError, UnicodeError) as e:
|
|
99
|
+
print(f"inets: {e}", file=sys.stderr)
|
|
100
|
+
return 2
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
sys.exit(main())
|
inets/errors.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""The package's errors. All derive from :class:`Error`."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Error(Exception):
|
|
5
|
+
"""Anything this package raises on purpose."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TableError(Error):
|
|
9
|
+
"""A table that cannot be read."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class IvyError(Error):
|
|
13
|
+
"""Ivy text that cannot be read, or that is not a net."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TermError(Error):
|
|
17
|
+
"""Text that is not a term of S, K and I, or a term that cannot be used as asked."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Stuck(Error):
|
|
21
|
+
"""A net that cannot go on: an active pair no rule applies to, or a value wanted
|
|
22
|
+
that depends on a free port."""
|
inets/ivm.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Programs of Vine's IVM, run by the ``ivm`` table.
|
|
2
|
+
|
|
3
|
+
>>> from inets import ivm
|
|
4
|
+
>>> run = ivm.run('''
|
|
5
|
+
... iv:main {
|
|
6
|
+
... ^ = ivm:x(io0 io1)
|
|
7
|
+
... io0 = ivm:ext:merge[root:io:print_char](ivm:n32#72 io1)
|
|
8
|
+
... }''')
|
|
9
|
+
>>> run.output, run.result.counts
|
|
10
|
+
('H', {'graft': 1, 'annihilate': 1, 'extrinsic': 1})
|
|
11
|
+
|
|
12
|
+
The table (``inets.bundled("ivm")``) holds the IVM's twenty rules. This module is its
|
|
13
|
+
host: it reads Ivy text of the ``ivm:`` system, copies a named net when a reference is
|
|
14
|
+
expanded, and supplies some of the IVM's extrinsic functions (N32 arithmetic and
|
|
15
|
+
comparison, ``ivm:branch``, ``root:io:print_char``, and the IO value's split and merge).
|
|
16
|
+
A program that calls any other stops with an :class:`~inets.errors.Error`.
|
|
17
|
+
|
|
18
|
+
The interaction counts are the IVM's own: on the programs tried they equal what ``ivm
|
|
19
|
+
run`` reports, kind by kind. Not modelled: memory, depth, workers, and the IVM's "vicious
|
|
20
|
+
circle" flag, which comes from its memory accounting.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import io
|
|
25
|
+
from dataclasses import dataclass, replace
|
|
26
|
+
|
|
27
|
+
from . import ivy
|
|
28
|
+
from .errors import Error, IvyError
|
|
29
|
+
from .net import Host, Net, Result
|
|
30
|
+
from .system import bundled
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Value:
|
|
35
|
+
"""An extrinsic value. ``copy`` says whether its type may be copied."""
|
|
36
|
+
type: str
|
|
37
|
+
data: object = None
|
|
38
|
+
copy: bool = True
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class Fn:
|
|
43
|
+
"""What an extrinsic function node carries: the function's name, whether it is a
|
|
44
|
+
split (one value in, two ports out) or a merge (two values in, one port out), and
|
|
45
|
+
whether a merge's arguments are exchanged."""
|
|
46
|
+
name: str
|
|
47
|
+
split: bool = False
|
|
48
|
+
exchanged: bool = False
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def merge(self):
|
|
52
|
+
return not self.split
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def swapped(self):
|
|
56
|
+
return replace(self, exchanged=not self.exchanged)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
IO = Value("io", copy=False)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def agent_of(tree):
|
|
63
|
+
"""The agent and parameter that a node of the ``ivm:`` system means."""
|
|
64
|
+
path, payload, names = tree.path, tree.payload, tree.names
|
|
65
|
+
if path in ("ivm:graft", "ivm:ext:split", "ivm:ext:merge", "ivm:ext:merge:swap") and len(names) != 1:
|
|
66
|
+
raise IvyError(f"{path} takes one name in square brackets")
|
|
67
|
+
if path in ("ivm:eraser", "ivm:error"):
|
|
68
|
+
return "era", None
|
|
69
|
+
if path == "ivm:graft":
|
|
70
|
+
return "graft", names[0]
|
|
71
|
+
if path in ("ivm:x", "ivm:y"):
|
|
72
|
+
return "comb", int(path == "ivm:y")
|
|
73
|
+
if path == "ivm:n32":
|
|
74
|
+
return "val", Value("n32", payload or 0)
|
|
75
|
+
if path == "ivm:f32":
|
|
76
|
+
return "val", Value("f32", payload or 0)
|
|
77
|
+
if path == "ivm:nil":
|
|
78
|
+
return "val", Value("nil")
|
|
79
|
+
if path == "ivm:branch":
|
|
80
|
+
return "val", Value("branch", tuple(names))
|
|
81
|
+
if path in ("ivm:ext:split", "ivm:ext:merge", "ivm:ext:merge:swap"):
|
|
82
|
+
return "fn", Fn(names[0], path == "ivm:ext:split", path == "ivm:ext:merge:swap")
|
|
83
|
+
raise IvyError("not a node of the ivm: system: " + path)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _n32(f):
|
|
87
|
+
def run(host, a, b):
|
|
88
|
+
if a.type != "n32" or b.type != "n32":
|
|
89
|
+
return None
|
|
90
|
+
r = f(a.data, b.data)
|
|
91
|
+
return None if r is None else Value("n32", int(r) & 0xFFFFFFFF)
|
|
92
|
+
return run
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _branch(host, index, branches):
|
|
96
|
+
if index.type != "n32" or branches.type != "branch" or index.data >= len(branches.data):
|
|
97
|
+
return None
|
|
98
|
+
return ("graft", branches.data[index.data])
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _print_char(host, io_value, n):
|
|
102
|
+
if io_value.type != "io" or n.type != "n32":
|
|
103
|
+
return None
|
|
104
|
+
host.out.write(chr(n.data))
|
|
105
|
+
return io_value
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
EXTRINSICS = {
|
|
109
|
+
"vi:n32:add": _n32(lambda a, b: a + b),
|
|
110
|
+
"vi:n32:sub": _n32(lambda a, b: a - b),
|
|
111
|
+
"vi:n32:mul": _n32(lambda a, b: a * b),
|
|
112
|
+
"vi:n32:div": _n32(lambda a, b: a // b if b else None),
|
|
113
|
+
"vi:n32:rem": _n32(lambda a, b: a % b if b else None),
|
|
114
|
+
"vi:n32:eq": _n32(lambda a, b: a == b),
|
|
115
|
+
"vi:n32:ne": _n32(lambda a, b: a != b),
|
|
116
|
+
"vi:n32:lt": _n32(lambda a, b: a < b),
|
|
117
|
+
"vi:n32:le": _n32(lambda a, b: a <= b),
|
|
118
|
+
"vi:n32:shl": _n32(lambda a, b: a << (b & 31)),
|
|
119
|
+
"vi:n32:shr": _n32(lambda a, b: a >> (b & 31)),
|
|
120
|
+
"vi:n32:and": _n32(lambda a, b: a & b),
|
|
121
|
+
"vi:n32:or": _n32(lambda a, b: a | b),
|
|
122
|
+
"vi:n32:xor": _n32(lambda a, b: a ^ b),
|
|
123
|
+
"vi:n32:add_high": _n32(lambda a, b: (a + b) >> 32),
|
|
124
|
+
"vi:n32:mul_high": _n32(lambda a, b: (a * b) >> 32),
|
|
125
|
+
"ivm:branch": _branch,
|
|
126
|
+
"root:io:print_char": _print_char,
|
|
127
|
+
"vi:io:split": lambda host, v: [v, IO] if v.type == "io" else None,
|
|
128
|
+
"vi:io:merge": lambda host, a, b: a if a.type == "io" and b.type == "io" else None,
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class IvmHost(Host):
|
|
133
|
+
"""Named nets from Ivy text, and the extrinsic functions above."""
|
|
134
|
+
|
|
135
|
+
def __init__(self, nets, out=None):
|
|
136
|
+
self.nets = nets
|
|
137
|
+
self.out = out if out is not None else io.StringIO()
|
|
138
|
+
|
|
139
|
+
def expand(self, net, name):
|
|
140
|
+
if name not in self.nets:
|
|
141
|
+
raise Error(f"no net named {name}")
|
|
142
|
+
if any(path == "ivm:error" for path in _paths(self.nets[name])):
|
|
143
|
+
net.flags.add("error")
|
|
144
|
+
return ivy.instantiate(net, self.nets[name], agent_of)
|
|
145
|
+
|
|
146
|
+
def call(self, net, function, values, ports):
|
|
147
|
+
if function.name not in EXTRINSICS:
|
|
148
|
+
raise Error(f"inets.ivm has no extrinsic function {function.name}")
|
|
149
|
+
if function.exchanged:
|
|
150
|
+
values = values[::-1]
|
|
151
|
+
try:
|
|
152
|
+
result = EXTRINSICS[function.name](self, *values)
|
|
153
|
+
except TypeError:
|
|
154
|
+
raise Error(f"{function.name} was given {len(values)} values") from None
|
|
155
|
+
if result is None:
|
|
156
|
+
net.flags.add("ext_generic")
|
|
157
|
+
result = [None] * len(ports)
|
|
158
|
+
elif not isinstance(result, list):
|
|
159
|
+
result = [result]
|
|
160
|
+
for port, value in zip(ports, result):
|
|
161
|
+
if value is None:
|
|
162
|
+
net.wire(port, net.make("era"))
|
|
163
|
+
elif isinstance(value, tuple):
|
|
164
|
+
net.wire(port, net.make(value[0], param=value[1]))
|
|
165
|
+
else:
|
|
166
|
+
net.wire(port, net.make("val", param=value))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _paths(equations):
|
|
170
|
+
stack = [t for pair in equations for t in pair]
|
|
171
|
+
while stack:
|
|
172
|
+
t = stack.pop()
|
|
173
|
+
if not isinstance(t, str):
|
|
174
|
+
yield t.path
|
|
175
|
+
stack.extend(t.kids)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@dataclass
|
|
179
|
+
class Run:
|
|
180
|
+
"""A finished run of a program: the net, why it stopped, what it printed, and the
|
|
181
|
+
flags it raised: the net's own (the IVM's names), and ``no_io`` if the IO value was
|
|
182
|
+
not what came back, which the IVM too works out after the run."""
|
|
183
|
+
net: Net
|
|
184
|
+
result: Result
|
|
185
|
+
output: str
|
|
186
|
+
flags: set
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def run(text, order="stack", seed=0, max_interactions=10 ** 7):
|
|
190
|
+
"""Runs a program given as Ivy text of the ``ivm:`` system, as ``ivm run`` starts it:
|
|
191
|
+
``iv:main`` meets a label-0 combinator holding the IO value and the result."""
|
|
192
|
+
nets = ivy.read(text)
|
|
193
|
+
host = IvmHost(nets)
|
|
194
|
+
net = Net(bundled("ivm"), host)
|
|
195
|
+
root = net.free()
|
|
196
|
+
if "iv:main" not in nets:
|
|
197
|
+
raise IvyError("the program has no net iv:main")
|
|
198
|
+
start = net.make("comb", net.make("val", param=IO), root, param=0)
|
|
199
|
+
net.wire(net.make("graft", param="iv:main"), start)
|
|
200
|
+
result = net.reduce(order, seed, max_interactions)
|
|
201
|
+
flags = set(net.flags)
|
|
202
|
+
end = net.link[root].node
|
|
203
|
+
if not (net.kind[end] == "val" and net.param[end].type == "io"):
|
|
204
|
+
flags.add("no_io")
|
|
205
|
+
return Run(net, result, host.out.getvalue(), flags)
|
inets/ivy.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Ivy text: Vine's notation for nets.
|
|
2
|
+
|
|
3
|
+
A file is named nets. A net is equations between trees, in braces. A tree is a wire (a
|
|
4
|
+
name used exactly twice in the net), the net's free port ``^``, or a node: a name with a
|
|
5
|
+
``:`` in it, an optional payload ``#12``, optional names in square brackets, and its
|
|
6
|
+
auxiliary ports' trees in round brackets. A node stands for its principal port. ``//``
|
|
7
|
+
starts a comment.
|
|
8
|
+
|
|
9
|
+
iv:main {
|
|
10
|
+
^ = ivm:x(io0 io1)
|
|
11
|
+
io0 = ivm:ext:merge[root:io:print_char](ivm:n32#72 io1)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
:func:`read` gives each net as a list of equations; :func:`instantiate` builds one in a
|
|
15
|
+
:class:`~inets.net.Net`, given a function that says which agent a node name means.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
import sys
|
|
21
|
+
from typing import NamedTuple
|
|
22
|
+
|
|
23
|
+
from .errors import IvyError
|
|
24
|
+
from .net import Port
|
|
25
|
+
|
|
26
|
+
TOKEN = re.compile(r"\s*([{}()\[\],=;^]|#[0-9A-Fa-fx]+|[A-Za-z0-9_:]+)")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Tree(NamedTuple):
|
|
30
|
+
"""A node in Ivy text: its name's path, its payload (or None), the names in its
|
|
31
|
+
square brackets, and the trees on its auxiliary ports. A wire is a plain string."""
|
|
32
|
+
path: str
|
|
33
|
+
payload: int | None
|
|
34
|
+
names: tuple
|
|
35
|
+
kids: tuple
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def read(text):
|
|
39
|
+
"""``{net name: [(tree, tree)]}``: each net as its equations. A tree is a wire's name
|
|
40
|
+
(``"^"`` for the free port) or a :class:`Tree`. A net's name is its whole text,
|
|
41
|
+
payload and bracketed names included."""
|
|
42
|
+
text = re.sub(r"//[^\n]*", "", text)
|
|
43
|
+
toks, at = [], 0
|
|
44
|
+
while at < len(text):
|
|
45
|
+
m = TOKEN.match(text, at)
|
|
46
|
+
if not m:
|
|
47
|
+
if not text[at:].strip():
|
|
48
|
+
break
|
|
49
|
+
raise IvyError("cannot read: " + text[at:at + 40].strip())
|
|
50
|
+
toks.append(m.group(1))
|
|
51
|
+
at = m.end()
|
|
52
|
+
pos = 0
|
|
53
|
+
|
|
54
|
+
def name():
|
|
55
|
+
nonlocal pos
|
|
56
|
+
path = toks[pos]
|
|
57
|
+
pos += 1
|
|
58
|
+
payload, names = None, []
|
|
59
|
+
if pos < len(toks) and toks[pos].startswith("#"):
|
|
60
|
+
try:
|
|
61
|
+
payload = int(toks[pos][1:], 0)
|
|
62
|
+
except ValueError:
|
|
63
|
+
raise IvyError(f"{toks[pos]} is not a number") from None
|
|
64
|
+
pos += 1
|
|
65
|
+
if pos < len(toks) and toks[pos] == "[":
|
|
66
|
+
pos += 1
|
|
67
|
+
while toks[pos] != "]":
|
|
68
|
+
names.append(name()[3])
|
|
69
|
+
if toks[pos] == ",":
|
|
70
|
+
pos += 1
|
|
71
|
+
pos += 1
|
|
72
|
+
whole = path + (f"#{payload}" if payload is not None else "") + (f"[{','.join(names)}]" if names else "")
|
|
73
|
+
return path, payload, names, whole
|
|
74
|
+
|
|
75
|
+
def tree(eqs):
|
|
76
|
+
nonlocal pos
|
|
77
|
+
if toks[pos] == "^" or ":" not in toks[pos]:
|
|
78
|
+
pos += 1
|
|
79
|
+
out = toks[pos - 1]
|
|
80
|
+
if not re.fullmatch(r"\^|[A-Za-z0-9_]+", out):
|
|
81
|
+
raise IvyError(f"expected a wire or a node, not {out}")
|
|
82
|
+
else:
|
|
83
|
+
path, payload, names, _ = name()
|
|
84
|
+
kids = []
|
|
85
|
+
if pos < len(toks) and toks[pos] == "(":
|
|
86
|
+
pos += 1
|
|
87
|
+
while toks[pos] != ")":
|
|
88
|
+
kids.append(tree(eqs))
|
|
89
|
+
pos += 1
|
|
90
|
+
out = Tree(path, payload, tuple(names), tuple(kids))
|
|
91
|
+
while pos < len(toks) and toks[pos] == "{": # equations attached to a tree
|
|
92
|
+
pos += 1
|
|
93
|
+
block(eqs)
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
def block(eqs):
|
|
97
|
+
nonlocal pos
|
|
98
|
+
while toks[pos] != "}":
|
|
99
|
+
a = tree(eqs)
|
|
100
|
+
if toks[pos] != "=":
|
|
101
|
+
raise IvyError("expected = in a net")
|
|
102
|
+
pos += 1
|
|
103
|
+
eqs.append((a, tree(eqs)))
|
|
104
|
+
if toks[pos] == ";":
|
|
105
|
+
pos += 1
|
|
106
|
+
pos += 1
|
|
107
|
+
|
|
108
|
+
nets = {}
|
|
109
|
+
limit = sys.getrecursionlimit()
|
|
110
|
+
sys.setrecursionlimit(max(limit, 20000))
|
|
111
|
+
try:
|
|
112
|
+
while pos < len(toks):
|
|
113
|
+
net = name()[3]
|
|
114
|
+
if pos >= len(toks) or toks[pos] != "{":
|
|
115
|
+
raise IvyError("expected { after " + net)
|
|
116
|
+
pos += 1
|
|
117
|
+
eqs = []
|
|
118
|
+
block(eqs)
|
|
119
|
+
nets[net] = eqs
|
|
120
|
+
except IndexError:
|
|
121
|
+
raise IvyError("the text ends in the middle of a net") from None
|
|
122
|
+
except RecursionError:
|
|
123
|
+
raise IvyError("a tree is nested too deeply to read") from None
|
|
124
|
+
finally:
|
|
125
|
+
sys.setrecursionlimit(limit)
|
|
126
|
+
return nets
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def instantiate(net, equations, agent_of):
|
|
130
|
+
"""Builds a net's equations in ``net`` and returns the port its free port ``^`` is
|
|
131
|
+
joined to. ``agent_of(tree)`` gives ``(agent kind, parameter)`` for a node."""
|
|
132
|
+
# Wires said to be one (`a = b`) are one wire: find each wire's representative.
|
|
133
|
+
same = {}
|
|
134
|
+
|
|
135
|
+
def find(w):
|
|
136
|
+
while same.get(w, w) != w:
|
|
137
|
+
same[w] = same.get(same[w], same[w])
|
|
138
|
+
w = same[w]
|
|
139
|
+
return w
|
|
140
|
+
|
|
141
|
+
for a, b in equations:
|
|
142
|
+
if isinstance(a, str) and isinstance(b, str):
|
|
143
|
+
same[find(a)] = find(b)
|
|
144
|
+
waiting = {}
|
|
145
|
+
|
|
146
|
+
def meet(wire, port):
|
|
147
|
+
wire = find(wire)
|
|
148
|
+
if wire in waiting:
|
|
149
|
+
net.wire(waiting.pop(wire), port)
|
|
150
|
+
else:
|
|
151
|
+
waiting[wire] = port
|
|
152
|
+
|
|
153
|
+
def build(tree):
|
|
154
|
+
"""A tree's principal port. (An explicit stack: trees can be deep.)"""
|
|
155
|
+
root, stack = None, [(tree, None)]
|
|
156
|
+
while stack:
|
|
157
|
+
t, parent = stack.pop()
|
|
158
|
+
kind, param = agent_of(t)
|
|
159
|
+
n = net.add_node(kind, param)
|
|
160
|
+
if len(t.kids) != net.system.agents[kind].arity:
|
|
161
|
+
raise IvyError(f"{t.path} is written with {len(t.kids)} ports, and {kind} has {net.system.agents[kind].arity}")
|
|
162
|
+
for i, kid in enumerate(t.kids, 1):
|
|
163
|
+
if isinstance(kid, str):
|
|
164
|
+
meet(kid, Port(n, i))
|
|
165
|
+
else:
|
|
166
|
+
stack.append((kid, Port(n, i)))
|
|
167
|
+
if parent is None:
|
|
168
|
+
root = Port(n, 0)
|
|
169
|
+
else:
|
|
170
|
+
net.wire(parent, Port(n, 0))
|
|
171
|
+
return root
|
|
172
|
+
|
|
173
|
+
for a, b in equations:
|
|
174
|
+
if isinstance(a, str) and isinstance(b, str):
|
|
175
|
+
continue
|
|
176
|
+
if isinstance(a, str):
|
|
177
|
+
meet(a, build(b))
|
|
178
|
+
elif isinstance(b, str):
|
|
179
|
+
meet(b, build(a))
|
|
180
|
+
else:
|
|
181
|
+
net.wire(build(a), build(b))
|
|
182
|
+
root = find("^")
|
|
183
|
+
if root not in waiting:
|
|
184
|
+
raise IvyError("the net has no free port ^, or uses it twice")
|
|
185
|
+
out = waiting.pop(root)
|
|
186
|
+
if waiting:
|
|
187
|
+
raise IvyError("wires used once: " + ", ".join(sorted(waiting)))
|
|
188
|
+
return out
|