Phase 5: atomics through every layer (RFC 0015)
AIR: linear atomic<T> (AtomicScalar), atomic.new/take/load/store/RMW/ cmpxchg (two results)/fence with explicit orderings; feature atomics published. Verifier: ordering tables (E4201), ordinary access (E4202), effects [atomic] / [atomic, atomic.weak], linearity, take while lent (E4101, also for mutex.take). Interpreter: timestamped message machine (src/interp/weak.zig); views travel through spawn/join, channels, mutexes, close and cancel; seq_cst reads the latest message and programs without weak reads make no extra draw (existing records unchanged). aji explore: exhaustive exploration that branches only before visible operations. Litmus: 20/20 tests give exactly the oracle's sets; differential test (1500 random programs) found no unsound outcome. .aji layer 10, Quick Reference atomics, source coverage 67/67, audit report atomic_operations. AIR bundle +5.9 %, QUICK.md +0.5k.
This commit is contained in:
1 parent
ce9ef03bc0
commit
4242132b2a
70 files changed
+2630
-80
No files matched your search
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Differential soundness test of the interpreter against the oracle
|
||||
(spec 04 §20.5: for every program, observed ⊆ allowed).
|
||||
|
||||
Generates small random litmus programs (2–3 tasks, 1–3 operations each, valid
|
||||
orderings only), computes the allowed outcomes with the independent oracle
|
||||
(tools/litmus/enumerate.py) and the interpreter's outcomes with
|
||||
`aji explore`, and fails if the interpreter produces an outcome the oracle
|
||||
does not allow. Exact equality is reported, not required: the interpreter is
|
||||
only required to be complete on the normative corpus.
|
||||
|
||||
Usage: python3 tools/litmus/differential.py [--seed N] [--count N] [--aji PATH]
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import enumerate as oracle # noqa: E402
|
||||
import to_air # noqa: E402
|
||||
|
||||
LOADS = ["rlx", "acq", "sc"]
|
||||
STORES = ["rlx", "rel", "sc"]
|
||||
RMWS = ["rlx", "acq", "rel", "ar", "sc"]
|
||||
FENCES = ["acq", "rel", "ar", "sc"]
|
||||
CAS = {"rlx": ["rlx"], "acq": ["rlx", "acq"], "rel": ["rlx"], "ar": ["rlx", "acq"], "sc": ["rlx", "acq", "sc"]}
|
||||
|
||||
|
||||
def program(rng, n):
|
||||
locs = ["x", "y"][: rng.choice([1, 2, 2])]
|
||||
tasks = []
|
||||
reg = 0
|
||||
observe = []
|
||||
for t in range(rng.choice([2, 2, 3])):
|
||||
ops = []
|
||||
for _ in range(rng.randint(1, 3)):
|
||||
kind = rng.choice(["store", "store", "load", "load", "rmw", "cas", "fence"])
|
||||
loc = rng.choice(locs)
|
||||
if kind == "store":
|
||||
ops.append(f"store {loc} {rng.randint(1, 2)} {rng.choice(STORES)}")
|
||||
elif kind == "fence":
|
||||
ops.append(f"fence {rng.choice(FENCES)}")
|
||||
else:
|
||||
r = f"r{reg}"
|
||||
reg += 1
|
||||
observe.append(f"T{t}.{r}")
|
||||
if kind == "load":
|
||||
ops.append(f"{r} = load {loc} {rng.choice(LOADS)}")
|
||||
elif kind == "rmw":
|
||||
ops.append(f"{r} = rmw {rng.choice(['add', 'xchg'])} {loc} {rng.randint(1, 2)} {rng.choice(RMWS)}")
|
||||
else:
|
||||
s = rng.choice(list(CAS))
|
||||
ops.append(f"{r} = cas {loc} {rng.randint(0, 2)} {rng.randint(1, 3)} {s} {rng.choice(CAS[s])}")
|
||||
tasks.append(ops)
|
||||
# Keep the oracle's brute force small: at most six operations in all and
|
||||
# four writes per location (it enumerates every modification order).
|
||||
if sum(len(ops) for ops in tasks) > 6 or any(
|
||||
sum(1 for ops in tasks for o in ops if (o.startswith(f"store {l}") or f" {l} " in o and ("rmw" in o or "cas" in o))) > 4 for l in locs
|
||||
):
|
||||
return program(rng, n)
|
||||
observe += [f"final {l}" for l in locs]
|
||||
lines = [f"name: diff{n}", "init: " + " ".join(f"{l}=0" for l in locs)]
|
||||
for t, ops in enumerate(tasks):
|
||||
lines.append(f"T{t}:")
|
||||
lines += [f" {o}" for o in ops]
|
||||
lines.append("observe: " + " ".join(observe))
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main(argv):
|
||||
seed, count = 1, 200
|
||||
aji = os.path.join(ROOT, "zig-out", "bin", "aji")
|
||||
while argv:
|
||||
if argv[0] == "--seed":
|
||||
seed = int(argv[1])
|
||||
elif argv[0] == "--count":
|
||||
count = int(argv[1])
|
||||
elif argv[0] == "--aji":
|
||||
aji = argv[1]
|
||||
else:
|
||||
raise SystemExit(__doc__)
|
||||
argv = argv[2:]
|
||||
rng = random.Random(seed)
|
||||
unsound = exact = 0
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for n in range(count):
|
||||
text = program(rng, n)
|
||||
allowed = {tuple(o) for o in oracle.enumerate_program(oracle.parse(text))[0]}
|
||||
prog = to_air.parse(text)
|
||||
air = os.path.join(tmp, f"d{n}.air")
|
||||
open(air, "w").write(to_air.translate(text))
|
||||
r = subprocess.run([aji, "explore", "--grant", "heap=mem.alloc:65536", air], capture_output=True, text=True)
|
||||
res = next((json.loads(l) for l in r.stdout.splitlines() if l.strip().startswith('{"runs"')), None)
|
||||
if res is None:
|
||||
print(f"ERROR program {n}:\n{text}{r.stdout[:500]}{r.stderr[:500]}")
|
||||
return 1
|
||||
observed = {tuple(o["outcome"]["value"][f"o{i}"] for i in range(len(prog["observe"]))) for o in res["outcomes"]}
|
||||
if observed - allowed:
|
||||
unsound += 1
|
||||
print(f"UNSOUND program {n} (seed {seed}): interpreter produced {sorted(observed - allowed)}\n{text}")
|
||||
elif observed == allowed and res["complete"]:
|
||||
exact += 1
|
||||
print(f"{count} programs: {count - unsound} sound ({exact} exact), {unsound} unsound")
|
||||
return 1 if unsound else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Interpreter conformance on the normative litmus corpus (spec 04 §20.5).
|
||||
|
||||
For every test, the outcomes the interpreter produces under exhaustive
|
||||
exploration (`aji explore`) MUST equal the stated allowed set:
|
||||
|
||||
observed_exhaustive == allowed
|
||||
|
||||
Usage: python3 tools/litmus/run_interp.py [--aji PATH] [tests/litmus/*.lit]
|
||||
"""
|
||||
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import check # noqa: E402 (stated sets)
|
||||
import to_air # noqa: E402
|
||||
|
||||
|
||||
def main(argv):
|
||||
aji = os.path.join(ROOT, "zig-out", "bin", "aji")
|
||||
if argv[:1] == ["--aji"]:
|
||||
aji, argv = argv[1], argv[2:]
|
||||
files = argv or sorted(glob.glob(os.path.join(ROOT, "tests", "litmus", "*.lit")))
|
||||
failures = 0
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for f in files:
|
||||
name = os.path.relpath(f, ROOT)
|
||||
allowed, forbidden = check.stated(f)
|
||||
air = os.path.join(tmp, os.path.basename(f) + ".air")
|
||||
prog = to_air.parse(open(f).read())
|
||||
open(air, "w").write(to_air.translate(open(f).read()))
|
||||
r = subprocess.run([aji, "explore", "--grant", "heap=mem.alloc:65536", air], capture_output=True, text=True)
|
||||
lines = [json.loads(l) for l in r.stdout.splitlines() if l.strip()]
|
||||
result = next((l for l in lines if "outcomes" in l), None)
|
||||
if result is None:
|
||||
failures += 1
|
||||
print(f"ERROR {name}: {r.stdout.strip()[:300]} {r.stderr.strip()[:300]}")
|
||||
continue
|
||||
observed = set()
|
||||
others = []
|
||||
for o in result["outcomes"]:
|
||||
out = o["outcome"]
|
||||
if out.get("status") != "returned":
|
||||
others.append(out)
|
||||
continue
|
||||
observed.add(tuple(out["value"][f"o{i}"] for i in range(len(prog["observe"]))))
|
||||
problems = []
|
||||
if not result["complete"]:
|
||||
problems.append(f"exploration incomplete after {result['runs']} runs")
|
||||
if others:
|
||||
problems.append(f"non-returning outcomes {others[:3]}")
|
||||
if observed - allowed:
|
||||
problems.append(f"interpreter produced unallowed {sorted(observed - allowed)}")
|
||||
if allowed - observed:
|
||||
problems.append(f"interpreter never produced allowed {sorted(allowed - observed)}")
|
||||
if observed & forbidden:
|
||||
problems.append(f"interpreter produced forbidden {sorted(observed & forbidden)}")
|
||||
if problems:
|
||||
failures += 1
|
||||
print(f"MISMATCH {name}: " + "; ".join(problems))
|
||||
else:
|
||||
print(f"ok {name} ({result['runs']} runs)")
|
||||
print(f"\n{len(files) - failures} exact, {failures} not")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,343 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Translate a litmus test (tests/litmus/README.md) into a text AIR program.
|
||||
|
||||
The program's result is a struct `@Out` with one u64 field per observed
|
||||
value, in `observe:` order. Run it with
|
||||
`aji explore --grant heap=mem.alloc:65536 FILE.air`.
|
||||
|
||||
Mapping:
|
||||
|
||||
- every location is an `atomic<u64>` created in `@main` and lent to the
|
||||
tasks as `ref<atomic<u64>>`; `final x` is `atomic.take` after all joins;
|
||||
- every task is a function returning a struct of its registers and of the
|
||||
results of the tasks it joins;
|
||||
- a channel is a `channel.make u64` with room for every send; each sending
|
||||
task receives its own sender and closes it after its last send, the
|
||||
receiving task receives the receiver and closes it at its end;
|
||||
- a mutex is a `mutex<u64>` lent as `ref<mutex<u64>>`;
|
||||
- `spawn Tn` / `join Tn` open a task scope in the spawning task.
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
ORD = {"rlx": "relaxed", "acq": "acquire", "rel": "release", "ar": "acq_rel", "sc": "seq_cst"}
|
||||
RMW = {"xchg": "xchg", "add": "add.wrap", "sub": "sub.wrap", "and": "and", "or": "or", "xor": "xor"}
|
||||
|
||||
|
||||
def parse(text):
|
||||
prog = {"name": None, "init": {}, "tasks": {}, "order": [], "spawned": set(), "observe": []}
|
||||
cur = None
|
||||
for raw in text.splitlines():
|
||||
line = raw.split("#", 1)[0].rstrip()
|
||||
if not line.strip():
|
||||
continue
|
||||
if not line.startswith((" ", "\t")):
|
||||
cur = None
|
||||
key, _, rest = line.partition(":")
|
||||
m = re.fullmatch(r"(T\d+)( \(spawned\))?", key.strip())
|
||||
if m:
|
||||
cur = m.group(1)
|
||||
prog["tasks"][cur] = []
|
||||
prog["order"].append(cur)
|
||||
if m.group(2):
|
||||
prog["spawned"].add(cur)
|
||||
elif key == "name":
|
||||
prog["name"] = rest.strip()
|
||||
elif key == "init":
|
||||
for kv in rest.split():
|
||||
k, v = kv.split("=")
|
||||
prog["init"][k] = int(v)
|
||||
elif key == "observe":
|
||||
toks = rest.split()
|
||||
i = 0
|
||||
while i < len(toks):
|
||||
if toks[i] == "final":
|
||||
prog["observe"].append(("final", toks[i + 1]))
|
||||
i += 2
|
||||
else:
|
||||
t, r = toks[i].split(".")
|
||||
prog["observe"].append(("reg", t, r))
|
||||
i += 1
|
||||
continue
|
||||
prog["tasks"][cur].append(line.split())
|
||||
return prog
|
||||
|
||||
|
||||
class Gen:
|
||||
def __init__(self, prog):
|
||||
self.p = prog
|
||||
self.lines = []
|
||||
self.n = 0
|
||||
locs = list(prog["init"])
|
||||
self.locs = locs
|
||||
self.chans = sorted({op[1] for ops in prog["tasks"].values() for op in ops if op[0] in ("send", "recv")})
|
||||
self.mutexes = sorted({op[1] for ops in prog["tasks"].values() for op in ops if op[0] in ("lock", "unlock")})
|
||||
# Which task sends / receives on each channel; who spawns whom.
|
||||
self.senders = {c: [t for t in prog["order"] if any(op[:2] == ["send", c] for op in prog["tasks"][t])] for c in self.chans}
|
||||
self.receiver = {c: next(t for t in prog["order"] if any(op[:2] == ["recv", c] for op in prog["tasks"][t])) for c in self.chans}
|
||||
self.spawns = {t: [op[1] for op in prog["tasks"][t] if op[0] == "spawn"] for t in prog["order"]}
|
||||
|
||||
def fresh(self, base):
|
||||
self.n += 1
|
||||
return f"%{base}_{self.n}"
|
||||
|
||||
def emit(self, s):
|
||||
self.lines.append(s)
|
||||
|
||||
def regs(self, t):
|
||||
out = []
|
||||
for op in self.p["tasks"][t]:
|
||||
if len(op) > 1 and op[1] == "=":
|
||||
out.append(op[0])
|
||||
return out
|
||||
|
||||
def ret_type(self, t):
|
||||
return f"@R_{t}"
|
||||
|
||||
def type_decls(self):
|
||||
for t in self.p["order"]:
|
||||
fields = [f"{r}: u64" for r in self.regs(t)] + [f"j_{c}: {self.ret_type(c)}" for c in self.spawns[t]]
|
||||
self.emit(f"type {self.ret_type(t)} = struct {{ {', '.join(fields)} }}" if fields else f"type {self.ret_type(t)} = struct {{}}")
|
||||
fields = [f"o{i}: u64" for i in range(len(self.p["observe"]))]
|
||||
self.emit(f"type @Out = struct {{ {', '.join(fields)} }}")
|
||||
|
||||
def params(self, t):
|
||||
"""The parameters of task t: refs of every location and mutex, its
|
||||
endpoints, and the endpoints of the tasks it spawns."""
|
||||
ps = [(f"%{l}", "ref<atomic<u64>>") for l in self.locs]
|
||||
ps += [(f"%m_{m}", "ref<mutex<u64>>") for m in self.mutexes]
|
||||
for c in self.chans:
|
||||
for tt in self.closure(t):
|
||||
if tt in self.senders[c]:
|
||||
ps.append((f"%tx_{c}_{tt}", "sender<u64>"))
|
||||
if self.receiver[c] == tt:
|
||||
ps.append((f"%rx_{c}", "receiver<u64>"))
|
||||
return ps
|
||||
|
||||
def closure(self, t):
|
||||
out = [t]
|
||||
for c in self.spawns[t]:
|
||||
out += self.closure(c)
|
||||
return out
|
||||
|
||||
def task(self, t, effects):
|
||||
ps = self.params(t)
|
||||
self.emit("")
|
||||
self.emit(f"fn @{t}({', '.join(f'{n}: {ty}' for n, ty in ps)}) -> {self.ret_type(t)}")
|
||||
self.emit(f"effects [{', '.join(effects)}]")
|
||||
self.emit("entry:")
|
||||
joined = {}
|
||||
scope = None
|
||||
handles = {}
|
||||
last_send = {c: max((i for i, op in enumerate(self.p["tasks"][t]) if op[:2] == ["send", c]), default=-1) for c in self.chans}
|
||||
guards = {}
|
||||
for i, op in enumerate(self.p["tasks"][t]):
|
||||
if op[0] == "store":
|
||||
k = self.fresh("k")
|
||||
self.emit(f" {k} = const.u64 {op[2]}")
|
||||
self.emit(f" atomic.store.{ORD[op[3]]} %{op[1]}, {k}")
|
||||
elif op[0] == "fence":
|
||||
self.emit(f" atomic.fence.{ORD[op[1]]}")
|
||||
elif op[1] == "=" and op[2] == "load":
|
||||
self.emit(f" %{op[0]} = atomic.load.{ORD[op[4]]} %{op[3]}")
|
||||
elif op[1] == "=" and op[2] == "rmw":
|
||||
k = self.fresh("k")
|
||||
self.emit(f" {k} = const.u64 {op[5]}")
|
||||
self.emit(f" %{op[0]} = atomic.{RMW[op[3]]}.{ORD[op[6]]} %{op[4]}, {k}")
|
||||
elif op[1] == "=" and op[2] == "cas":
|
||||
e, n = self.fresh("e"), self.fresh("n")
|
||||
self.emit(f" {e} = const.u64 {op[4]}")
|
||||
self.emit(f" {n} = const.u64 {op[5]}")
|
||||
self.emit(f" %{op[0]}, {self.fresh('ok')} = atomic.cmpxchg.{ORD[op[6]]}.{ORD[op[7]]} %{op[3]}, {e}, {n}")
|
||||
elif op[0] == "send":
|
||||
c = op[1]
|
||||
tok = self.fresh("tok")
|
||||
b = self.fresh("tx")
|
||||
ok = self.fresh("sent")[1:]
|
||||
bad = self.fresh("send_failed")[1:]
|
||||
self.emit(f" {tok} = const.u64 0")
|
||||
self.emit(f" {b} = borrow.mut %tx_{c}_{t}")
|
||||
self.emit(f" channel.send {b}, {tok}, ok -> @{ok}, closed -> @{bad}, cancelled -> @{bad}")
|
||||
self.emit(f"{bad}(%v_{bad}: u64):")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}:")
|
||||
self.emit(f" borrow.end {b}")
|
||||
if i == last_send[c]:
|
||||
self.emit(f" channel.close_sender %tx_{c}_{t}")
|
||||
elif op[0] == "recv":
|
||||
c = op[1]
|
||||
b = self.fresh("rx")
|
||||
ok = self.fresh("got")[1:]
|
||||
bad = self.fresh("recv_failed")[1:]
|
||||
self.emit(f" {b} = borrow.mut %rx_{c}")
|
||||
self.emit(f" channel.recv {b}, ok -> @{ok}, closed -> @{bad}, cancelled -> @{bad}")
|
||||
self.emit(f"{bad}:")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}(%msg_{ok}: u64):")
|
||||
self.emit(f" borrow.end {b}")
|
||||
elif op[0] == "lock":
|
||||
ok = self.fresh("locked")[1:]
|
||||
bad = self.fresh("lock_cancelled")[1:]
|
||||
g = f"%g_{ok}"
|
||||
self.emit(f" mutex.lock %m_{op[1]}, ok -> @{ok}, cancelled -> @{bad}")
|
||||
self.emit(f"{bad}:")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}({g}: guard<u64>):")
|
||||
guards[op[1]] = g
|
||||
elif op[0] == "unlock":
|
||||
self.emit(f" mutex.unlock {guards.pop(op[1])}")
|
||||
elif op[0] == "spawn":
|
||||
c = op[1]
|
||||
if scope is None:
|
||||
scope = self.fresh("scope")
|
||||
self.emit(f" {scope} = task.scope.begin")
|
||||
args = [n for n, _ in self.params(c)]
|
||||
h = self.fresh("task")
|
||||
self.emit(f" {h} = task.spawn {scope}, @{c}({', '.join(args)})")
|
||||
handles[c] = h
|
||||
elif op[0] == "join":
|
||||
c = op[1]
|
||||
r = self.fresh("joined")
|
||||
self.emit(f" {r} = task.join {handles[c]}")
|
||||
joined[c] = r
|
||||
else:
|
||||
raise SystemExit(f"unknown operation {op}")
|
||||
for c in self.chans:
|
||||
if self.receiver[c] == t:
|
||||
ok = self.fresh("closed")[1:]
|
||||
pend = self.fresh("pending")[1:]
|
||||
self.emit(f" channel.close_receiver %rx_{c}, ok -> @{ok}, pending -> @{pend}")
|
||||
self.emit(f"{pend}(%p_{pend}: receiver<u64>):")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}:")
|
||||
if scope is not None:
|
||||
self.emit(f" task.scope.end {scope}")
|
||||
fields = [f"%{r}" for r in self.regs(t)] + [joined[c] for c in self.spawns[t]]
|
||||
res = self.fresh("result")
|
||||
self.emit(f" {res} = struct.make {self.ret_type(t)}({', '.join(fields)})")
|
||||
self.emit(f" ret {res}")
|
||||
|
||||
def main(self, effects):
|
||||
roots = [t for t in self.p["order"] if t not in self.p["spawned"]]
|
||||
self.emit("")
|
||||
self.emit("fn @main(%heap: cap<mem.alloc>) -> @Out")
|
||||
self.emit(f"effects [{', '.join(effects)}]")
|
||||
self.emit("entry:")
|
||||
for l in self.locs:
|
||||
v = self.fresh("init")
|
||||
self.emit(f" {v} = const.u64 {self.p['init'][l]}")
|
||||
self.emit(f" %a_{l} = atomic.new {v}")
|
||||
self.emit(f" %{l} = borrow.ref %a_{l}")
|
||||
for m in self.mutexes:
|
||||
z = self.fresh("z")
|
||||
self.emit(f" {z} = const.u64 0")
|
||||
self.emit(f" %mx_{m} = mutex.make {z}")
|
||||
self.emit(f" %m_{m} = borrow.ref %mx_{m}")
|
||||
for c in self.chans:
|
||||
sends = sum(1 for ops in self.p["tasks"].values() for op in ops if op[:2] == ["send", c])
|
||||
cap = self.fresh("cap")
|
||||
ok = self.fresh("chan")[1:]
|
||||
bad = self.fresh("oom")[1:]
|
||||
self.emit(f" {cap} = const.usize {max(sends, 1)}")
|
||||
self.emit(f" channel.make u64, {cap}, %heap, ok -> @{ok}, err -> @{bad}")
|
||||
self.emit(f"{bad}(%e_{bad}: alloc_error):")
|
||||
self.emit(" trap")
|
||||
self.emit(f"{ok}(%tx0_{c}: sender<u64>, %rx_{c}: receiver<u64>):")
|
||||
senders = self.senders[c]
|
||||
for i, s in enumerate(senders):
|
||||
if i + 1 < len(senders):
|
||||
b = self.fresh("txb")
|
||||
self.emit(f" {b} = borrow.ref %tx0_{c}")
|
||||
self.emit(f" %tx_{c}_{s} = channel.sender.dup {b}")
|
||||
self.emit(f" borrow.end {b}")
|
||||
else:
|
||||
self.emit(f" %tx_{c}_{s} = copy %tx0_{c}" if False else f" ; last sender takes the original")
|
||||
if senders:
|
||||
self.last_sender_alias = getattr(self, "last_sender_alias", {})
|
||||
self.last_sender_alias[c] = senders[-1]
|
||||
# Rename the original sender to the last sending task's name.
|
||||
text = "\n".join(self.lines)
|
||||
for c, s in getattr(self, "last_sender_alias", {}).items():
|
||||
text = text.replace(f"%tx0_{c}", f"%tx_{c}_{s}")
|
||||
self.lines = text.split("\n")
|
||||
self.emit(" %scope = task.scope.begin")
|
||||
for t in roots:
|
||||
args = [n for n, _ in self.params(t)]
|
||||
self.emit(f" %h_{t} = task.spawn %scope, @{t}({', '.join(args)})")
|
||||
for t in roots:
|
||||
self.emit(f" %res_{t} = task.join %h_{t}")
|
||||
self.emit(" task.scope.end %scope")
|
||||
for l in self.locs:
|
||||
self.emit(f" borrow.end %{l}")
|
||||
for m in self.mutexes:
|
||||
self.emit(f" borrow.end %m_{m}")
|
||||
self.emit(f" %mv_{m} = mutex.take %mx_{m}")
|
||||
finals = {}
|
||||
for l in self.locs:
|
||||
finals[l] = f"%final_{l}"
|
||||
self.emit(f" %final_{l} = atomic.take %a_{l}")
|
||||
outs = []
|
||||
for o in self.p["observe"]:
|
||||
if o[0] == "final":
|
||||
outs.append(finals[o[1]])
|
||||
continue
|
||||
_, t, r = o
|
||||
# The struct path from a root task down to t.
|
||||
path = self.path_to(t)
|
||||
cur = f"%res_{path[0]}"
|
||||
for parent, child in zip(path, path[1:]):
|
||||
v = self.fresh("j")
|
||||
self.emit(f" {v} = struct.get {self.ret_type(parent)}.j_{child}, {cur}")
|
||||
cur = v
|
||||
v = self.fresh("o")
|
||||
self.emit(f" {v} = struct.get {self.ret_type(t)}.{r}, {cur}")
|
||||
outs.append(v)
|
||||
self.emit(f" %out = struct.make @Out({', '.join(outs)})")
|
||||
self.emit(" ret %out")
|
||||
|
||||
def path_to(self, t):
|
||||
for root in self.p["order"]:
|
||||
if root in self.p["spawned"]:
|
||||
continue
|
||||
path = self.find(root, t)
|
||||
if path:
|
||||
return path
|
||||
raise SystemExit(f"task {t} is never started")
|
||||
|
||||
def find(self, cur, t):
|
||||
if cur == t:
|
||||
return [cur]
|
||||
for c in self.spawns[cur]:
|
||||
p = self.find(c, t)
|
||||
if p:
|
||||
return [cur] + p
|
||||
return None
|
||||
|
||||
def module(self):
|
||||
name = re.sub(r"[^a-z0-9_]", "_", self.p["name"].lower())
|
||||
effects = ["atomic", "atomic.weak", "mem.alloc", "task.spawn", "task.wait"]
|
||||
self.type_decls()
|
||||
decls = self.lines
|
||||
self.lines = []
|
||||
self.main(effects)
|
||||
body_main = self.lines
|
||||
self.lines = []
|
||||
for t in self.p["order"]:
|
||||
self.task(t, effects)
|
||||
header = [
|
||||
f"module litmus.{name}",
|
||||
"air 0",
|
||||
"lang 0.1",
|
||||
"features [atomics, cancellation, capabilities, channels, effects, heap, ownership, resources, sync, tasks]",
|
||||
"",
|
||||
]
|
||||
return "\n".join(header + decls + body_main + self.lines) + "\n"
|
||||
|
||||
|
||||
def translate(text):
|
||||
return Gen(parse(text)).module()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.stdout.write(translate(open(sys.argv[1]).read()))
|
||||
@@ -79,6 +79,12 @@ CHECKLIST = [
|
||||
("graphs", "`arc.from_frozen` / `arc.clone` / `arc.release` / `arc.at`", r"arc\.(from_frozen|clone|release|at)\(", True),
|
||||
("graphs", "`iref` equality", r"(?s)(?:island|frozen|arc)\.root\(.*\b\w+ (?:==|!=) (?:\w+|arc\.root\(\w+\)) \{", False),
|
||||
("graphs", "graphs through channels and tasks", r"channel\.make<(island|arc)<", True),
|
||||
("atomics", "`atomic.new` / `atomic.take`", r"atomic\.(new|take)\(", True),
|
||||
("atomics", "`atomic.load` / `atomic.store` with an ordering", r"atomic\.(load|store)\([^)]*(relaxed|acquire|release|seq_cst)\)", True),
|
||||
("atomics", "read-modify-write (`swap`, `add.wrap`, `sub.wrap`, `and`, `or`, `xor`)", r"atomic\.(swap|add\.wrap|sub\.wrap|and|or|xor)\(", False),
|
||||
("atomics", "`let (old, exchanged) = atomic.compare_exchange(…)`", r"let \(\w+, \w+\) = atomic\.compare_exchange\(", True),
|
||||
("atomics", "`atomic.fence`", r"atomic\.fence\(", False),
|
||||
("atomics", "cells lent to tasks (`ref c = cell;`)", r"(?s)ref \w+ = \w+;.*task\.spawn\(.*atomic\.", True),
|
||||
("unsafe", "`ref unchecked` / `assume`", r"\bunchecked\b|\bassume\(", True),
|
||||
("unsafe", "`trusted` rejected", r"\btrusted\b", True),
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user