Files
aji/tools/litmus/to_air.py
dev 4242132b2a 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.
2026-10-06 08:05:01 +03:00

344 lines
14 KiB
Python

#!/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()))