interplane.Get Omega
Read in your language

omega-mcp

aien-dev/omega-mcp

Brought by drakestapleton

branch main Branches Tags History

omega-mcp / tools / gen-reference.py

726 lines · 72288 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Data-authoring generator (host tool, not part of the server): writes data/reference.json and
3data/examples/*.om. The pin is read from the PIN file. Keyword ids, arities and keyword-table lines come from
4the pinned omega-mv source through the same decoder the oracle uses (tools/check-reference.py). Every other
5citation names a path and a quote, never a line: c() finds the quote in that file at the pinned revision and
6writes the lines it occupies, and stops the generator when the quote is missing or occurs more than once (a ctx
7argument then names the unique text that holds it). An error's site is the first `fail K` line of omc.om.
8tools/check-reference.py then re-verifies every committed entry against that source and the pinned omc.
9
10 python3 tools/gen-reference.py --omega-src <a git clone of omega-mv that contains the PIN revision>
11"""
12import argparse, importlib.util, json, os, re, sys
13HERE = os.path.dirname(os.path.abspath(__file__))
14sys.path.insert(0, HERE)
15from ref_examples import EX
16
17_ap = argparse.ArgumentParser()
18_ap.add_argument("--omega-src", required=True)
19_args = _ap.parse_args()
20_s = importlib.util.spec_from_file_location("checkref", os.path.join(HERE, "check-reference.py"))
21_m = importlib.util.module_from_spec(_s)
22_s.loader.exec_module(_m)
23
24
25REV, OMC_SHA = _m.read_pin()
26_src = _m.Src(_args.omega_src)
27OUT = os.path.join(HERE, "..", "data")
28P = f"omega-mv@{REV[:8]} "
29OMG = "docs/one_layer/OMEGESE.md"
30OMC = "seed/omc/omc.om"
31MAP = "seed/host/MAPPING.md"
32IRH = "src/compiler/osc_ir.h"
33
34
35def at(path, lines, quote):
36 """A citation at lines that a decoder derived from the source (keyword-table lines, error sites)."""
37 return {"ref": f"{P}{path}:{lines}", "quote": quote}
38
39
40_texts = {}
41
42
43def _text(path):
44 """path at the pin as one string of whitespace-normalised lines joined by spaces, and each character's line.
45 Lines the compiler's diagnostic generator wrote are left out (the block between `note D2-GENERATED-BEGIN`
46 and `note D2-GENERATED-END`, and every `note d2site ` line): they repeat the condition text of the
47 statement they describe, so a citation is always found at the statement itself."""
48 if path not in _texts:
49 parts, owner, gen = [], [], False
50 for n, line in enumerate(_src.lines(path), 1):
51 w = _m.norm(line)
52 if w == "note D2-GENERATED-BEGIN":
53 gen = True
54 if gen or w.startswith("note d2site "):
55 gen = gen and w != "note D2-GENERATED-END"
56 continue
57 if not w:
58 continue
59 if parts:
60 parts.append(" ")
61 owner.append(n)
62 parts.append(w)
63 owner.extend([n] * len(w))
64 _texts[path] = ("".join(parts), owner)
65 return _texts[path]
66
67
68def c(path, quote, ctx=None):
69 """Cite quote in path at the pin. The lines are found by content: ctx (default: the quote) must occur exactly
70 once and contain the quote, else the generator stops with the count, so a repin never needs a line remap."""
71 key = _m.norm(ctx if ctx is not None else quote)
72 if not key or _m.norm(quote) not in key:
73 raise SystemExit(f"gen-reference: {path}: quote {quote!r} is empty or not inside its ctx {ctx!r}")
74 t, owner = _text(path)
75 hits, i = [], t.find(key)
76 while i >= 0:
77 hits.append(i)
78 i = t.find(key, i + 1)
79 if len(hits) != 1:
80 raise SystemExit(f"gen-reference: {path} at omega-mv {REV[:8]} has {len(hits)} occurrences of {key!r}"
81 f" (lines {sorted({owner[h] for h in hits})}); cite text that occurs exactly once")
82 a, b = owner[hits[0]], owner[hits[0] + len(key) - 1]
83 return at(path, str(a) if a == b else f"{a}-{b}", quote)
84
85
86def site(k):
87 """Error k's emitting site: the first line of omc.om at the pin that is exactly `fail k`."""
88 for n, line in enumerate(_src.lines(OMC), 1):
89 if line.strip() == f"fail {k}":
90 return at(OMC, str(n), f"fail {k}")
91 raise SystemExit(f"gen-reference: {OMC} at omega-mv {REV[:8]} has no `fail {k}` line")
92
93
94TAB = {w: (i, line, t) for w, i, line, t in _m.kwtable(_src)}
95
96# ---------------------------------------------------------------- words
97W = {}
98
99
100def word(name, cat, form, arity, types, result, summary, cites, example, profile="OM-1", notes=None):
101 if name not in TAB:
102 raise SystemExit(f"gen-reference: {name!r} has an entry here but is not in the keyword table at omega-mv {REV[:8]}")
103 i, line, t = TAB[name]
104 e = {"table": t, "id": i, "category": cat, "profile": profile, "form": form, "arity": arity,
105 "types": types, "result": result, "summary": summary,
106 "citations": [at(OMC, f"{line}-{line + 1}", f"ret {i}")] + cites, "example": example}
107 if notes:
108 e["notes"] = notes
109 W[name] = e
110
111
112INT_P = {"fd", "flags", "mode", "pid", "signal", "events", "domain", "kind", "protocol", "backlog", "target",
113 "options", "level", "option", "whence", "op", "how", "mask", "pgid", "uid", "gid", "index_i",
114 "res", "which", "who", "priority"}
115ULONG_P = {"off", "n", "capacity", "index", "m"}
116LONG_P = {"offset", "length", "interval", "pos"}
117
118
119def host_types(params):
120 out = []
121 for p in params:
122 if p in ("A", "B", "PATH", "OUT"):
123 out.append(f"{p}: uchar array (sized, unsized view/edit, or text when only read)")
124 elif p in INT_P:
125 out.append(f"{p}: int")
126 elif p in ULONG_P:
127 out.append(f"{p}: ulong")
128 elif p in LONG_P:
129 out.append(f"{p}: long")
130 else:
131 raise SystemExit(f"untyped host parameter {p}")
132 return out
133
134
135HOST_HDR = c(OMG, "Offsets, byte counts, capacities and argument indices are `ulong`")
136HOST = [
137 # name, form (as in the table), category, summary, example
138 ("fopen", "fopen A off n flags mode", "host-file", "Open a length-delimited path relative to the current directory; return the descriptor.", "files"),
139 ("fclose", "fclose fd", "host-file", "Close a descriptor.", "files"),
140 ("fsync", "fsync fd", "host-file", "Sync file data and metadata.", "files"),
141 ("fdsync", "fdsync fd", "host-file", "Sync file data only (fdatasync).", "files"),
142 ("memfd", "memfd A off n flags", "host-file", "Create an anonymous in-memory file (memfd_create); return its descriptor.", "files"),
143 ("fchmod", "fchmod fd mode", "host-file", "Set permissions on an open descriptor.", "files"),
144 ("chmod", "chmod A off n mode", "host-file", "Set permissions on a checked path (fchmodat, flags 0).", "files"),
145 ("chown", "chown A off n uid gid", "host-dir", "Set ownership on a checked path (fchownat, flags 0).", "dirs"),
146 ("faccess", "faccess A off n mode", "host-file", "Check access to a checked path (faccessat): mode 0/1/2/4.", "files"),
147 ("getuid", "getuid", "host-process", "Real user id of the process.", "dirs"),
148 ("geteuid", "geteuid", "host-process", "Effective user id of the process.", "dirs"),
149 ("getgid", "getgid", "host-process", "Real group id of the process.", "dirs"),
150 ("getegid", "getegid", "host-process", "Effective group id of the process.", "dirs"),
151 ("fchdir", "fchdir fd", "host-dir", "Change the working directory to an open directory descriptor.", "dirs"),
152 ("getppid", "getppid", "host-process", "Parent process id.", "procs"),
153 ("setsid", "setsid", "host-process", "Create a session and become its leader.", "procs"),
154 ("getpgid", "getpgid pid", "host-process", "Process group id of pid (0 = self).", "procs"),
155 ("getsid", "getsid pid", "host-process", "Session id of pid (0 = self).", "procs"),
156 ("syncfs", "syncfs fd", "host-file", "Sync the filesystem containing an open descriptor.", "files"),
157 ("shutdown", "shutdown fd how", "host-net", "Shut down part of a connected socket (how 0 read, 1 write, 2 both).", "sockets"),
158 ("flock", "flock fd op", "host-file", "Advisory whole-file lock (Linux flock); op 1 shared, 2 exclusive, 8 unlock, |4 nonblocking.", "files"),
159 ("setpgid", "setpgid pid pgid", "host-process", "Set a process's group (0 = self/own pid).", "procs"),
160 ("umask", "umask mask", "host-file", "Set the file-mode mask; return the previous mask.", "files"),
161 ("fseek", "fseek fd offset whence", "host-file", "Seek; return the resulting file offset.", "files"),
162 ("ftrunc", "ftrunc fd length", "host-file", "Set an open descriptor's length (ftruncate).", "files"),
163 ("truncate", "truncate A off n length", "host-file", "Set a checked path's length (truncate).", "files"),
164 ("unlink", "unlink A off n", "host-file", "Remove the named file.", "files"),
165 ("makedir", "makedir A off n mode", "host-dir", "Create a directory.", "dirs"),
166 ("rmdir", "rmdir A off n", "host-dir", "Remove an empty directory.", "dirs"),
167 ("cwd", "cwd A off capacity", "host-dir", "Write the current directory into writable bytes; the count includes the trailing zero.", "dirs"),
168 ("chdir", "chdir A off n", "host-dir", "Change the working directory to a checked, nonempty path.", "dirs"),
169 ("readlnk", "readlnk PATH off n OUT off capacity", "host-dir", "Read a symbolic link into writable output bytes; no zero byte is appended.", "dirs"),
170 ("getdnts", "getdnts fd A off n", "host-dir", "Write raw Linux getdents64 records; return bytes written.", "dirs"),
171 ("fstat", "fstat fd A off n", "host-file", "Write the 128-byte Linux ARM64 stat structure of an open descriptor.", "files"),
172 ("stat", "stat A off n B off capacity", "host-file", "Metadata for a checked path (newfstatat) into a 128-byte ARM64 stat structure.", "files"),
173 ("lstat", "lstat A off n B off capacity", "host-file", "As stat, without following a final symbolic link.", "files"),
174 ("renames", "renames A off n flags", "host-dir", "Rename the two paths of a packed list (renameat2); flag 1 refuses replacement.", "dirs"),
175 ("link", "link A off n", "host-dir", "Create a hard link from a packed two-path list (old, new).", "dirs"),
176 ("symlnk", "symlnk A off n", "host-dir", "Create a symbolic link from a packed two-path list (target text, link path).", "dirs"),
177 ("monons", "monons", "host-time", "Monotonic nanoseconds, for elapsed-time measurement.", "clock"),
178 ("realns", "realns", "host-time", "Realtime nanoseconds since the Unix epoch.", "clock"),
179 ("sleepns", "sleepns interval", "host-time", "Sleep for nonnegative nanoseconds; a negative interval traps 3.", "clock"),
180 ("socknew", "socknew domain kind protocol", "host-net", "Create a socket.", "sockets"),
181 ("bind", "bind fd A off n", "host-net", "Bind a socket to the address bytes of the slice.", "sockets"),
182 ("connect", "connect fd A off n", "host-net", "Connect using the address bytes of the slice.", "sockets"),
183 ("listen", "listen fd backlog", "host-net", "Listen for connections.", "sockets"),
184 ("accept", "accept fd flags", "host-net", "Accept a connection (accept4) without peer-address output; return the descriptor.", "sockets"),
185 ("sockname", "sockname fd A off n", "host-net", "Write the socket's address bytes; return the full address length.", "sockets"),
186 ("sockopt", "sockopt fd level option A off n", "host-net", "Set one allowlisted four-byte socket option.", "sockets"),
187 ("recv", "recv fd A off n flags", "host-net", "Receive into a writable slice.", "sockets"),
188 ("send", "send fd A off n flags", "host-net", "Send a slice; MSG_NOSIGNAL is added so a closed peer returns an error.", "sockets"),
189 ("waitio", "waitio fd events interval", "host-net", "Poll one descriptor: readiness bits, 0 on timeout, or negative errno.", "sockets"),
190 ("peercred", "peercred fd A off capacity", "host-net", "Read SO_PEERCRED (pid, uid, gid as little-endian int32) into at least 12 writable bytes.", "sockets"),
191 ("pollfds", "pollfds A off n interval", "host-net", "Poll packed eight-byte pollfd records in a writable slice.", "sockets"),
192 ("sendmsg", "sendmsg fd A off n flags", "host-net", "Send one checked payload through a private msghdr, no ancillary data.", "sockets"),
193 ("fork", "fork", "host-process", "Copy the process: 0 in the child, the child pid in the parent.", "procs"),
194 ("getpid", "getpid", "host-process", "The current process id.", "procs"),
195 ("killpid", "killpid pid signal", "host-process", "Send a signal; signal 0 checks existence and permission.", "procs"),
196 ("waitpid", "waitpid pid A off n options", "host-process", "Wait with wait4; write a four-byte status; return the pid.", "procs"),
197 ("pipefds", "pipefds A off n flags", "host-process", "Create a pipe (pipe2); write two little-endian 32-bit descriptors.", "procs"),
198 ("dupfd", "dupfd fd target flags", "host-process", "Duplicate onto a chosen descriptor (dup3).", "procs"),
199 ("execprog", "execprog A off n", "host-process", "Replace the process using a packed argument list and an empty environment; returns only on failure.", "procs"),
200 ("argcnt", "argcnt", "host-process", "Argument count, including the executable name.", "argsenv"),
201 ("argread", "argread index A off capacity", "host-process", "Copy one argument's bytes without a terminator; return its length.", "argtrap"),
202 ("envcnt", "envcnt", "host-process", "Number of environment entries.", "argsenv"),
203 ("envread", "envread index A off capacity", "host-process", "Copy one environment entry without its terminator; return its length.", "argsenv"),
204 ("random", "random A off n flags", "host-time", "Fill a writable byte slice from getrandom; return the bytes written.", "clock"),
205 ("peername", "peername fd A off n", "host-net", "Write the connected peer's address bytes (getpeername) into a writable slice; return the full address length (greater than n means truncated).", "peername"),
206 ("execenv", "execenv A off n B off m", "host-process", "As execprog, but the child's environment is exactly the packed list B (count 1..64, at most 4096 bytes) instead of an empty one; both packets are checked (trap 3) first; returns only on failure. AArch64 and x86linux.", "limits"),
207 ("prlimit", "prlimit pid res A off n", "host-process", "Linux prlimit64 on pid (0 = this process): n 16 writes the old {rlim_cur, rlim_max} to A[off..off+16) as two little-endian u64; n 32 sets the pair read from A[off..off+16) and writes the old pair to A[off+16..off+32); any other n returns -22. Returns 0 or minus errno.", "limits"),
208 ("cpuset", "cpuset pid A off n", "host-process", "sched_setaffinity from a byte mask slice (pid 0 = calling thread); 0 or minus errno; an empty permitted mask is -22.", "sched"),
209 ("cpuget", "cpuget pid A off n", "host-process", "sched_getaffinity into a writable byte mask slice; the count of bytes copied or minus errno.", "sched"),
210 ("cpunow", "cpunow", "host-process", "getcpu: a snapshot of the CPU number, or minus errno.", "sched"),
211 ("setprio", "setprio which who priority", "host-process", "setpriority (which 0, who 0 = this thread); 0 or minus errno; Linux privilege checks remain.", "sched"),
212 ("getprio", "getprio which who", "host-process", "getpriority: the raw kernel result 20 minus nice, or minus errno.", "sched"),
213 ("execpure", "execpure A off n", "host-process", "As execprog, then run the executable through descriptor 3 under a fixed strict stdio profile (execveat AT_EMPTY_PATH); returns only on failure. AArch64 only (error 25 under target x86linux).", "procs"),
214]
215# OMEGESE section 10 (docs/one_layer/OMEGESE.md, argread/envread rows) at the pin: argread/envread trap 3 on an index
216# at or past argcnt/envcnt (they do not return an errno), and argcnt/envcnt cannot fail
217# OMEGESE section 10 at the pin: an OM-2 function unit may use this subset on AArch64; every other host word
218# stays program mode only (error 9 in function mode)
219OM2FN = {"fopen", "fclose", "fstat", "stat", "lstat", "getuid", "geteuid", "getgid", "getegid", "monons", "realns", "sleepns"}
220OM2FN_CITE = c(OMG, "an OM-2 function unit (first line `om2`, no `fn main`) may use the file")
221HOST_TAIL = {
222 "argread": " Program mode only. An index at or past argcnt traps 3 (check argcnt first; the example shows the trap); insufficient capacity returns -105 without changing the slice.",
223 "envread": " Program mode only. An index at or past envcnt traps 3; insufficient capacity returns -105 without changing the slice.",
224 "argcnt": " Program mode only; never fails.",
225 "envcnt": " Program mode only; never fails.",
226}
227for name, form, cat, summ, exid in HOST:
228 params = form.split()[1:]
229 quote = f"`{form}`" if name not in ("getuid", "geteuid", "getgid", "getegid") else f"`{name}`"
230 # the word's row of the host-word table; the four identity words share one row
231 row = "| `getuid` / `geteuid` / `getgid` / `getegid` |" if name in ("getuid", "geteuid", "getgid", "getegid") else f"| {quote} |"
232 notes = None
233 if name == "argread" or name == "envread":
234 params = ["index"] + params[1:]
235 if name == "pwrite":
236 pass
237 tail = HOST_TAIL.get(name, " Program mode only; failure is minus the Linux errno.")
238 cites = [c(OMG, quote, row), HOST_HDR]
239 if name in OM2FN:
240 tail = " Program mode, and OM-2 function units on AArch64 (error 9 in other function units); failure is minus the Linux errno."
241 cites.append(OM2FN_CITE)
242 word(name, cat, form, len(params), host_types(params), "long", summ + tail, cites, exid)
243
244# pread / pwrite are in section 9.5
245word("pread", "host-file", "pread fd A off n pos", 5, host_types(["fd", "A", "off", "n", "pos"]), "long",
246 "Read n bytes at file position pos into A[off..] without moving the descriptor offset; bytes read or -errno.",
247 [c(OMG, "`pread fd A off n pos` / `pwrite fd A off n pos` (pos long)")], "files")
248word("pwrite", "host-file", "pwrite fd A off n pos", 5, host_types(["fd", "A", "off", "n", "pos"]), "long",
249 "Write A[off..off+n-1] at file position pos without moving the descriptor offset; bytes written or -errno.",
250 [c(OMG, "`pread fd A off n pos` / `pwrite fd A off n pos` (pos long)")], "files")
251
252# device words (seed/host/MAPPING.md)
253DEV = [
254 ("devctl", "devctl fd request A off n", ["fd: int", "request: uint literal (FIONREAD 21531, an NVRM request, or one of the five aien-gpu ABI1 requests)", "A: writable uchar array", "off: ulong", "n: ulong"], "long",
255 "Checked Linux ioctl on an allowlisted request with its exact encoded size.", "mapping"),
256 ("mapnew", "mapnew fd offset bytes access mode", ["fd: int (-1 for anonymous)", "offset: ulong", "bytes: ulong", "access: int literal 1 or 3", "mode: int literal 1, 2, 33 or 34"], "long (handle)",
257 "Map a file or anonymous memory; a positive owned handle or negative errno.", "mapping"),
258 ("mapdrop", "mapdrop handle", ["handle: long"], "long", "Unmap an owned mapping; 0 or negative errno.", "mapping"),
259 ("mapread", "mapread handle offset A off n", ["handle: long", "offset: ulong", "A: writable uchar array", "off: ulong", "n: ulong"], "long",
260 "Copy n bytes from the mapping into A; return n.", "mapping"),
261 ("mapwrite", "mapwrite handle offset A off n", ["handle: long", "offset: ulong", "A: uchar array (text and views accepted)", "off: ulong", "n: ulong"], "long",
262 "Copy n bytes from A into a writable mapping; return n.", "mapping"),
263 ("devcall", "devcall fd request H hoff 32 P poff n", ["fd: int", "request: uint literal (RM_ALLOC or RM_CONTROL)", "H: writable uchar array", "hoff: ulong", "32: header length", "P: writable uchar array", "poff: ulong", "n: ulong (at most 1048576; larger traps 3)"], "long",
264 "Checked NVIDIA RM_ALLOC / RM_CONTROL call with a private header and a bounded parameter span.", "mapping"),
265 ("uvmctl", "uvmctl fd command A off n", ["fd: int", "command: uint literal from the UVM allowlist", "A: writable uchar array", "off: ulong", "n: ulong (the request's exact payload length)"], "long",
266 "Allowlisted Linux UVM ioctl with its exact writable payload.", "mapping"),
267 ("mapaddr", "mapaddr handle", ["handle: long"], "ulong", "Base address of an owned live mapping or reservation (no access through it).", "mapping"),
268 ("mapget", "mapget handle offset width", ["handle: long", "offset: ulong", "width: int literal 4 or 8"], "ulong",
269 "One aligned 32- or 64-bit load from a readable mapping.", "mapping"),
270 ("mapset", "mapset handle offset width value", ["handle: long", "offset: ulong", "width: int literal 4 or 8", "value: ulong"], "long",
271 "One aligned 32- or 64-bit store into a writable mapping; returns 0.", "mapping"),
272 ("maphold", "maphold address bytes", ["address: ulong (at least 64 KiB, span below 1 TiB)", "bytes: ulong"], "long (handle)",
273 "Reserve an unused page-aligned span (PROT_NONE, MAP_FIXED_NOREPLACE).", "mapping"),
274 ("vfioctl", "vfioctl fd request A off n", ["fd: int", "request: uint literal from the VFIO allowlist", "A: uchar array", "off: ulong", "n: ulong (the request's exact byte count)"], "long",
275 "Allowlisted VFIO ioctl with its exact byte count (argsz is written for spans of 8 bytes or more); signed Linux ioctl result.", "vfio"),
276 ("vfiomap", "vfiomap fd A off 32", ["fd: int", "A: uchar array holding a vfio_region_info", "off: ulong", "32: record length"], "long (handle)",
277 "Read-only shared mapping of exactly one VFIO region; region flags without READ and MMAP, or a size of zero, trap 3. A handle or negative errno.", "vfio"),
278 ("vfiomapw", "vfiomapw fd A off 32", ["fd: int", "A: uchar array holding a vfio_region_info", "off: ulong", "32: record length"], "long (handle)",
279 "As vfiomap, but the region flags must also contain WRITE and the mapping is read/write (mapget/mapset drive device registers).", "vfio"),
280 ("eventfd", "eventfd initial", ["initial: uint"], "long",
281 "Create a Linux eventfd (CLOEXEC, NONBLOCK, no semaphore mode); read/write exactly eight bytes, close with fclose. An fd or negative errno.", "vfio"),
282 ("vfioirq", "vfioirq fd request A off n", ["fd: int from a successful vfioctl GROUP_GET_DEVICE_FD", "request: uint literal 15213 (GET_IRQ_INFO) or 15214 (SET_IRQS)", "A: writable uchar array", "off: ulong", "n: ulong (checked against the caller's argsz)"], "long",
283 "Typed VFIO IRQ ioctl: an fd that is not an acquired VFIO device, or a malformed form, traps 3 before the ioctl.", "vfioirq_trap"),
284 ("mapbind", "mapbind handle fd offset access", ["handle: long", "fd: int", "offset: ulong", "access: int literal 1 or 3"], "long",
285 "Bind a shared file or device mapping over a whole owned reservation.", "mapping"),
286]
287# seed/host/MAPPING.md at the pin: OM-2 function units may also use the twelve mapping/device words; the VFIO and
288# eventfd words are program mode only
289VFIO = {"vfioctl", "vfiomap", "vfiomapw", "eventfd", "vfioirq"}
290DEV_FN = c(MAP, "An OM-2 function unit (first line `om2`, no `fn main`) may also use `devctl`")
291DEV_VFIO = c(MAP, "These additions are program-mode only; hosted x86 VFIO and function-mode VFIO are not implemented.")
292for name, form, types, res, summ, exid in DEV:
293 if name in VFIO:
294 tail, extra = " Program mode only, AArch64 Linux.", DEV_VFIO
295 else:
296 tail, extra = " Program mode, and OM-2 function units (error 9 in OM-1 function units).", DEV_FN
297 word(name, "device", form, len(form.split()) - 1, types, res,
298 summ + tail, [c(MAP, f"`{form}`"), extra], exid)
299word("cpufence", "device", "cpufence", 0, [], "-",
300 "Statement: host CPU publication barrier; every load and store before it completes before any after it "
301 "(AArch64 DSB SY, x86-64 MFENCE). Accepted in function and program mode.",
302 [c(OMG, "`cpufence` | Publication barrier (keyword id 199)."),
303 c(MAP, "`cpufence` | Statement, keyword 199")], "cpu_order")
304word("cpurelax", "device", "cpurelax", 0, [], "-",
305 "Statement: spin-wait hint for a bounded poll loop, no ordering (AArch64 YIELD, x86-64 PAUSE). "
306 "Accepted in function and program mode.",
307 [c(OMG, "`cpurelax` | Spin-wait hint, no ordering (keyword id 200)."),
308 c(MAP, "`cpurelax` | Statement, keyword 200")], "cpu_order")
309
310# KFD device words (OMEGESE "KFD device words" at the pin): program mode on Linux only
311KFD_MODE = c(OMG, "Program-mode Linux only: native AArch64 and `target x86linux`.")
312for name, form, arity, types, res, summ, quote, exid in [
313 ("kfdres", "kfdres n", 1, ["n: ulong (nonzero multiple of 4096; otherwise trap 3)"], "long (handle)",
314 "Reserve n bytes of address space with no access (PROT_NONE) at a kernel-chosen address aligned to 2 MiB; "
315 "no memory is committed. A positive owned handle or negative errno.",
316 "`kfdres n` reserves a nonzero, 4096-byte-multiple `ulong` length", "kfd"),
317 ("kfdmap", "kfdmap fd offset n", 3, ["fd: int (a DRM render descriptor or /dev/kfd; any other descriptor traps 3)",
318 "offset: ulong", "n: ulong (zero traps 3)"], "long (handle)",
319 "Map n bytes of an AMD device read/write and shared at a kernel-chosen address. "
320 "A positive owned handle or negative errno.",
321 "`kfdmap fd offset n` maps `n` bytes read/write and shared", "kfdmap_trap"),
322 ("kfdctl", "kfdctl fd request H off n [SUFFIX]", 5,
323 ["fd: int", "request: uint literal from the KFD allowlist (another request is error 9)", "H: writable uchar array",
324 "off: ulong", "n: ulong (the request's exact record length; a literal of another length is error 9)",
325 "SUFFIX: fixed by the request. None for GET_VERSION, ACQUIRE_VM, DESTROY_QUEUE, FREE_MEMORY_OF_GPU, "
326 "CREATE_EVENT and DESTROY_EVENT; a span `P poff pn` for GET_PROCESS_APERTURES_NEW, MAP_MEMORY_TO_GPU, "
327 "UNMAP_MEMORY_FROM_GPU and WAIT_EVENTS; one reservation handle for ALLOC_MEMORY_OF_GPU and "
328 "SET_SCRATCH_BACKING_VA; five handles `ring wptr rptr eop ctx` for CREATE_QUEUE"], "long",
329 "Allowlisted AMD KFD ioctl through a private copy of the header; every address the kernel receives comes "
330 "from a checked span or a live owned handle, and caller address fields must be zero (trap 3). "
331 "The ioctl result or negative errno.",
332 "`kfdctl fd request H off n ...` uses a writable `uchar` header span.", "kfd"),
333]:
334 word(name, "device", form, arity, types, res,
335 summ + " Program mode only, Linux (error 9 in function mode, error 25 on firmware targets).",
336 [c(OMG, quote), KFD_MODE], exid)
337
338# types
339TYPES = [("bool", None, "1-bit truth value: true 1, false 0", 1, "control"),
340 ("uchar", None, "unsigned 8-bit", 1, "ints"), ("u8", "uchar", "unsigned 8-bit", 1, "ints"),
341 ("ushort", None, "unsigned 16-bit", 2, "ints"), ("u16", "ushort", "unsigned 16-bit", 2, "ints"),
342 ("uint", None, "unsigned 32-bit", 4, "ints"), ("u32", "uint", "unsigned 32-bit", 4, "ints"),
343 ("ulong", None, "unsigned 64-bit", 8, "ints"), ("u64", "ulong", "unsigned 64-bit", 8, "ints"),
344 ("byte", None, "signed 8-bit", 1, "ints"), ("i8", "byte", "signed 8-bit", 1, "ints"),
345 ("short", None, "signed 16-bit", 2, "ints"), ("i16", "short", "signed 16-bit", 2, "ints"),
346 ("int", None, "signed 32-bit", 4, "hello"), ("i32", "int", "signed 32-bit", 4, "ints"),
347 ("long", None, "signed 64-bit", 8, "ints"), ("i64", "long", "signed 64-bit", 8, "ints")]
348for name, alias, desc, size, exid in TYPES:
349 signed = desc.startswith("signed")
350 cite = (c(OMG, "`true` and `false` are the bool numbers 1 and 0.") if name == "bool" else
351 c(OMG, "(byte 8,") if signed else
352 c(OMG, "(uchar 8, ushort 16, uint 32, ulong 64 bits)"))
353 summ = f"Type word: {desc} integer, sizeof {size}." if name != "bool" else "Type word: bool (true 1, false 0), sizeof 1; never an array element."
354 if alias:
355 summ = f"Alias of {alias} (same keyword id): {desc}, sizeof {size}."
356 if name != "bool":
357 summ += (" Signed add/sub/mul/neg/div/shl trap 1 on overflow." if signed else " Arithmetic wraps modulo 2^width.")
358 word(name, "type", f"{name} VALUE (conversion) | NAME {name} (parameter) | to {name} (result)", 1,
359 ["VALUE: any integer, float or bool value"], name if not alias else alias,
360 summ + " As a prefix it converts a value, trapping 5 when out of range.",
361 [cite, c(OMG, "A conversion `<type> v` traps 5 when the value is outside the new type.")], exid)
362QTY = "spec/quantities-and-modular.md"
363word("qty", "type", "qty VALUE (conversion) | NAME qty (parameter) | to qty (result)", 1,
364 ["VALUE: an integer value"], "qty",
365 "Type word: unsigned quantity 0..2^64-1. add, sub and mul are checked and trap 1 when the exact result leaves "
366 "that range; mixing a quantity with a modular word (ulong etc.) is error 7. Convert explicitly: `qty w`, `ulong q`.",
367 [c(QTY, "Arithmetic operations are checked at runtime."),
368 c(QTY, "is rejected at compile time (error 7)",
369 "An operation combining a modular word and a quantity (e.g. `add ulong_val qty_val`) is rejected at compile time (error 7)"),
370 c(QTY, "The seeded syntax is prefix conversion (`q = qty w`, `w = ulong q`).")], "qty")
371DIT_SCRUB = c(OMG, "program mode only (error 9 in function mode), AArch64 only (error 25 under `target x86linux`), and give a long")
372word("dit", "host-cpu", "dit v", 1, ["v: int 0 or 1 (else trap 3)"], "long",
373 "Value word: set PSTATE.DIT (data-independent timing) to v and give the previous bit as 0 or 1. "
374 "OM-2 units only, program mode only, AArch64 only.",
375 [c(OMG, "**`dit v`** (v int, else error 7) sets PSTATE.DIT"), DIT_SCRUB], "secrets", profile="OM-2")
376word("scrub", "host-cpu", "scrub n", 1, ["n: ulong, a multiple of 16 at most 1048576 (else trap 3)"], "long",
377 "Value word: zero the n dead stack bytes below SP and every register holding no live value; gives 0. "
378 "OM-2 units only, program mode only, AArch64 only.",
379 [c(OMG, "**`scrub n`** (n ulong, else error 7) zeroes the dead stack and the dead registers and gives 0."),
380 DIT_SCRUB], "secrets", profile="OM-2")
381
382OPS = [("add", "a + b", "Unsigned add, sub, mul, shl, neg, not wrap modulo 2^width", "ints"),
383 ("sub", "a - b", "Unsigned add, sub, mul, shl, neg, not wrap modulo 2^width", "arith"),
384 ("mul", "a * b", "Unsigned add, sub, mul, shl, neg, not wrap modulo 2^width", "arith"),
385 ("div", "a / b, rounding toward zero; divisor 0 traps 2", "div and rem trap 2 when the divisor is 0.", "arith"),
386 ("rem", "remainder with the sign of the dividend; divisor 0 traps 2", "div and rem trap 2 when the divisor is 0.", "ints"),
387 ("and", "bitwise and (bool and for bools; eager)", "the two values of an op", "arith"),
388 ("or", "bitwise or (bool or for bools; eager)", "the two values of an op", "arith"),
389 ("xor", "bitwise exclusive or", "the two values of an op", "arith"),
390 ("shl", "shift left; amount outside 0..width-1 traps 7", "A shift amount outside 0 .. width - 1 traps 7", "arith"),
391 ("shr", "shift right (arithmetic for signed); amount outside 0..width-1 traps 7", "shr of a signed value keeps the sign.", "arith")]
392for name, desc, quote, exid in OPS:
393 word(name, "operator", f"{name} A B", 2, ["A: number type T", "B: the same type T"], "T",
394 f"Binary operator: {desc}. Both operands have one type (no implicit conversion, error 7).",
395 [c(OMG, quote)], exid)
396for name, desc in (("eq", "equal"), ("ne", "not equal"), ("lt", "less than"), ("le", "less or equal"),
397 ("gt", "greater than"), ("ge", "greater or equal")):
398 word(name, "operator", f"{name} A B", 2, ["A: number type T", "B: the same type T"], "bool",
399 f"Comparison: {desc} (unsigned or signed by the operands' type; IEEE for floats).",
400 [c(OMG, "comparisons `eq ne lt le gt ge`")], "arith")
401word("neg", "operator", "neg A", 1, ["A: number type T"], "T",
402 "Negation: wraps for unsigned types, traps 1 for the signed minimum, IEEE for floats.",
403 [c(OMG, "Signed add, sub, mul, neg, div and shl trap 1")], "arith")
404word("not", "operator", "not A", 1, ["A: integer type T or bool"], "T",
405 "Bitwise complement of an integer; logical not of a bool.",
406 [c(OMG, "Unsigned add, sub, mul, shl, neg, not wrap modulo 2^width")], "arith")
407
408D = "data"
409word("get", D, "get A i | get P field [i]", 2, ["A: array", "i: integer index"], "element type",
410 "Read element i of an array (or a struct/layout field). A constant index outside is error 21; a run-time one traps 3. In a run-time pool (global NAME T *) every index, a number included, is checked against the current length when the program runs (trap 3, never error 21).",
411 [c(OMG, "`get A i` reads element i"), c(OMG, "a number index included (it is checked at run time, never error 21)")], "arrays")
412word("len", D, "len A", 1, ["A: array or text"], "ulong", "Length of an array as a ulong. For a run-time pool (global NAME T *) the current length, read when the program runs and never folded; a contract on it is checked at run time.",
413 [c(OMG, "`len A` is A's length as a ulong."), c(OMG, "`len NAME` is the current length, a run-time ulong, never folded")], "hello")
414word("read", D, "read fd A off n", 4, ["fd: int", "A: writable uchar array", "off: ulong", "n: ulong"], "long",
415 "Read n bytes from fd into A[off..]; bytes read or minus errno. Slice outside A traps 3.",
416 [c(OMG, "`read fd A off n` and `write fd A off n` (fd int, off and n ulong)")], "files")
417word("write", D, "write fd A off n", 4, ["fd: int", "A: uchar array or text", "off: ulong", "n: ulong"], "long",
418 "Write A[off..off+n-1] to fd; bytes written or minus errno. Slice outside A traps 3.",
419 [c(OMG, "`read fd A off n` and `write fd A off n` (fd int, off and n ulong)")], "hello")
420word("true", D, "true", 0, [], "bool", "The bool value 1.", [c(OMG, "`true` and `false` are the bool numbers 1 and 0.")], "control")
421word("false", D, "false", 0, [], "bool", "The bool value 0.", [c(OMG, "`true` and `false` are the bool numbers 1 and 0.")], "control")
422word("view", D, "NAME view T N | NAME view T * (parameter) | view A (argument)", 3, ["T: element type", "N: length or * (OM-2 unsized)"], "-",
423 "Read-only array parameter of exact type and length; writing through it is error 20.",
424 [c(OMG, "A parameter `NAME view T N` or `NAME edit T N`")], "arrays")
425word("edit", D, "NAME edit T N | NAME edit T * (parameter) | edit A (argument)", 3, ["T: element type", "N: length or * (OM-2 unsized)"], "-",
426 "Writable array parameter of exact type and length; a global is never passed (error 19).",
427 [c(OMG, "A parameter `NAME view T N` or `NAME edit T N`")], "arrays")
428
429S = "structure"
430word("fn", S, "fn NAME (PARAM TYPE)* to TYPE|void [inline]", 3, ["NAME: up to 63 characters", "PARAM: up to 63 characters, at most 6 slots"], "-",
431 "Start a function; `end` closes it. `fn main` makes a whole Linux program (program mode).",
432 [c(OMG, "a function; `end` closes it"), c(OMG, "A program with a line `fn main` is a whole Linux program")], "hello")
433word("to", S, "fn ... to TYPE|void", 1, ["TYPE: a scalar type or void"], "-", "Introduces a function's result type.",
434 [c(OMG, "to <type> | void")], "hello")
435word("end", S, "end", 0, [], "-", "Closes fn, if/else, while, for, struct and layout blocks. A missing end is error 15.",
436 [c(OMG, "`end` closes it")], "hello")
437word("if", S, "if COND / [else] / end", 1, ["COND: bool"], "-", "Conditional block.",
438 [c(OMG, "if <cond> / else / end")], "control")
439word("else", S, "else", 0, [], "-", "Second arm of an if block.", [c(OMG, "if <cond> / else / end")], "control")
440word("while", S, "while COND [bound N] / end", 1, ["COND: bool", "N: 1..9223372036854775807 (IR mode 1..1000000)"], "-",
441 "Loop while COND holds; past N iterations (default 1000000) it traps 4.",
442 [c(OMG, "while <cond> [bound N] / end")], "control")
443word("bound", S, "while COND bound N | for NAME TYPE COUNT bound N", 1,
444 ["N: number or integer const 1..9223372036854775807 (IR mode 1..1000000)"], "-",
445 "Pass limit of a while or for loop; one more pass traps 4. Without it a while (and a for whose count is not a "
446 "number) stops at 1000000 passes.",
447 [c(OMG, "N 1..9223372036854775807 (a number or any integer const; IR mode: 1..1000000), default 1000000; past N iterations: trap 4"),
448 c(OMG, "N as for while.")], "control")
449word("for", S, "for NAME TYPE COUNT [bound N] / end", 3, ["NAME: new counter", "TYPE: integer type", "COUNT: number or value of TYPE"], "-",
450 "Counted loop: NAME = 0 .. COUNT-1. With no bound a number COUNT runs unguarded and any other COUNT traps 4 "
451 "after 1000000 passes; with `bound N` any COUNT traps 4 after N passes.",
452 [c(OMG, "for <name> <type> <count> [bound N] / end"),
453 c(OMG, "With no bound a number count is not guarded and any other count traps 4 after 1000000 passes; with `bound N` any count traps 4 after N passes")],
454 "for_guard")
455word("ret", S, "ret [VALUE]", 1, ["VALUE: the function's result type (none for void)"], "-",
456 "Return from the function; ends the path (a later line in the block is error 17).",
457 [c(OMG, "ret [<value>]")], "hello")
458word("=", S, "NAME = VALUE", 2, ["NAME: new or existing name of the same type", "VALUE: any value"], "-",
459 "Bind or overwrite a name (the = may be left out).",
460 [c(OMG, "<name> = <value>")], "hello")
461word("(", S, "( VALUE )", 1, ["VALUE: any value"], "VALUE's type", "Grouping: returns exactly the value inside; adds no code.",
462 [c(OMG, "`(` and `)` are separate words", "`(` and `)` are separate words even when written against a value")], "calls")
463word(")", S, "( VALUE )", 1, ["VALUE: any value"], "VALUE's type", "Closes a group; a missing ) is error 16.",
464 [c(OMG, "`(` and `)` are separate words", "`(` and `)` are separate words even when written against a value")], "calls")
465word("void", S, "fn ... to void", 0, [], "-", "A function that returns no value; ret without a value or reaching end returns.",
466 [c(OMG, "`to void` makes a void function")], "arrays")
467
468ST = "statement"
469word("global", ST, "global NAME T N | global NAME T *", 3, ["NAME: up to 63 characters", "T: element type", "N: 1..16777216, or * (a run-time pool)"], "-",
470 "A zero-filled pool of N elements in the program image. Program mode only; never passed as an argument (error 19). `global NAME T *` (omc only, AArch64 Linux program mode) is a run-time pool: its length is 0 when the program starts and enlarge grows it; a bool element type is error 9.",
471 [c(OMG, "`global NAME T N`: a pool of N elements (1 .. 16777216)"), c(OMG, "`global NAME T *`: a run-time pool of element type T")], "arrays")
472word("enlarge", ST, "r = enlarge NAME n", 2, ["NAME: a run-time pool (global NAME T *)", "n: ulong", "r: long"], "long",
473 "Grow the run-time pool NAME to n elements (omc only): the old values are kept, the new elements are 0 and r is 0; n at or below len NAME changes nothing and r is 0 (enlarge never shrinks). n times the element size at or past 2^63: r is -22; the host refusing the mapping: r is its negative errno, -12 (ENOMEM); NAME is then unchanged and nothing traps. Only the whole of an assignment (error 9 inside a value, a put or a condition; a bare enlarge line is error 16); a name that is not a run-time pool is error 7. The memory is held until the process ends.",
474 [c(OMG, "`r = enlarge NAME n`: n a ulong and r a long"), c(OMG, "Results: n at or below `len NAME`: 0, nothing changes (`enlarge` never shrinks)"),
475 c(OMG, "n times the element size at or past 2^63: -22 and NAME is unchanged"), c(OMG, "the host's negative errno, -12 (ENOMEM), and NAME is unchanged"),
476 c(OMG, "A refusal is a result the program handles; it is never a trap.")], "pools")
477word("text", ST, 'text NAME "bytes"', 2, ["NAME: up to 63 characters", "bytes: escapes \\n \\t \\\\ \\\""], "-",
478 "A read-only uchar array holding the quoted bytes. Program mode only.",
479 [c(OMG, '`text NAME "bytes"`: a read-only array of uchar')], "hello")
480word("put", ST, "put A i v | put P field [i] v", 3, ["A: writable array", "i: integer index", "v: element type"], "-",
481 "Store v at element i. Into a view or text: error 20.",
482 [c(OMG, "put <array> <index> <value>")], "arrays")
483word("free", ST, "free (refused)", 0, [], "-",
484 "Reserved and always refused with error 9: arrays are given back when their function returns (decision 24).",
485 [c(OMG, "There is no `free`: nothing is given back by hand (decision 24), and the word is refused (error 9)."),
486 c(OMC, "if or or or eq c 77 eq c 78 eq c 79 eq c 81")], "free_refused")
487word("own", ST, "own (refused)", 0, [], "-",
488 "Reserved word from the om4 draft; as a statement omc refuses it with error 9.",
489 [c(OMC, "if or or or eq c 77 eq c 78 eq c 79 eq c 81")], "own_refused")
490word("exit", ST, "exit v", 1, ["v: int"], "-", "End the program with status v modulo 256; ends the path.",
491 [c(OMG, "`exit v` (v int) ends the program with status v modulo 256.")], "exit")
492word("note", ST, "note ...", 0, [], "-", "A comment line: nothing after the first word is read.",
493 [c(OMG, "`note ...` is a line the translator does not read beyond its first word.")], "hello")
494word("new", ST, "NAME = new T N v | NAME = new STRUCT v1 .. vn", 3, ["T: element type", "N: length", "v: initial element value"], "array",
495 "A local array of N elements, each v, on the stack; only in a function's outermost block (error 9).",
496 [c(OMG, "`NAME = new T N v`: a local array of N elements, each v, on the stack")], "arrays")
497word("break", ST, "break", 0, [], "-", "Leave the innermost loop; outside a loop error 9.",
498 [c(OMG, "leave the innermost loop; outside a loop: error 9.")], "control")
499word("trap", ST, "trap N", 1, ["N: 1..14"], "-", "Stop with trap code N: program mode exits 100 + N.",
500 [c(OMG, "trap <code 1..14> stop with that code")], "trapword")
501word("continue", ST, "continue", 0, [], "-", "Jump to the next iteration (a while's head, a for's increment).",
502 [c(OMG, "jump to the next iteration")], "control")
503word("const", ST, "const NAME TYPE LITERAL", 3, ["NAME: up to 63 characters", "TYPE: integer or float type", "LITERAL: value of TYPE"], "-",
504 "A named typed constant, usable as a value, array length, for count, while bound or trap code.",
505 [c(OMG, "`const NAME TYPE LITERAL` at top level defines a named value before use.")], "consts")
506
507word("struct", "struct", "struct Name field type [len] ... end", 3, ["fields: 1..16, at most 64 eight-byte cells"], "-",
508 "A record type of eight-byte cells, declared on one line before the first fn.",
509 [c(OMG, "`struct Name field type [len] ... end`, one line, before the first `fn`.")], "structs")
510word("sizeof", "struct", "sizeof T | sizeof STRUCT", 1, ["T: scalar type or struct"], "ulong",
511 "Size in bytes; a compile-time constant.", [c(OMG, "`sizeof T` is the size in bytes of a scalar type")], "structs")
512word("offsetof", "struct", "offsetof STRUCT field", 2, ["STRUCT: struct name", "field: field name"], "ulong",
513 "Byte offset of a field; a compile-time constant.", [c(OMG, "`offsetof S f` is the byte offset of field `f`")], "structs")
514
515F = "float"
516word("f32", F, "f32 VALUE | 1.5f32", 1, ["VALUE: integer or float value"], "f32", "IEEE-754 binary32 type and conversion.",
517 [c(OMG, "`f32` and `f64` are IEEE-754 binary32 and binary64.")], "floats")
518word("f64", F, "f64 VALUE | 1.5f64", 1, ["VALUE: integer or float value"], "f64", "IEEE-754 binary64 type and conversion.",
519 [c(OMG, "`f32` and `f64` are IEEE-754 binary32 and binary64.")], "floats")
520word("bitcast", F, "bitcast T VALUE", 2, ["T: type of the same width", "VALUE: f32/i32/u32 or f64/i64/u64"], "T",
521 "Reinterpret the bits of a same-width value.", [c(OMG, "`bitcast T value` reinterprets a value of the same width")], "floats")
522for name, form, ar, summ in (("fsqrt", "fsqrt X", 1, "IEEE square root."), ("fabs", "fabs X", 1, "Absolute value."),
523 ("fmin", "fmin A B", 2, "IEEE minNum (FMINNM)."), ("fmax", "fmax A B", 2, "IEEE maxNum (FMAXNM).")):
524 word(name, F, form, ar, ["X: f32 or f64" if ar == 1 else "A, B: one float type"], "the operand type", summ,
525 [c(OMG, "Intrinsics `fsqrt x` and `fabs x` take one float; `fmin a b` and `fmax a b` take two of one float")], "floats")
526
527word("fma", F, "fma A B C", 3, ["A, B, C: one explicit float type (f32 or f64)"], "the operand type",
528 "Fused multiply-add: A*B+C with one rounding of the exact result (AArch64 FMADD); ordinary mul then add round twice. "
529 "Mixed or integer operands are error 7, an unresolved decimal literal error 11; x86linux and x86efi refuse it with error 9.",
530 [c(OMG, "`fma a b c` multiplies `a` by `b` and adds `c` with **one rounding of the exact combined result**."),
531 c(OMG, "The words are `bitcast`, `fsqrt`, `fabs`, `fmin`, `fmax` and `fma`")], "fma")
532
533O2 = "OM-2"
534OM2 = c(OMG, "rotr rotl unroll inline fresh abstract seal open holds layout field at little big part out")
535for name, form, ar, types, res, summ, quote, exid in [
536 ("rotr", "rotr X N", 2, ["X: unsigned type T", "N: T"], "T", "Rotate right; N outside 0..w-1 traps 7.", "`rotr x n` and `rotl x n`", "om2_rotate"),
537 ("rotl", "rotl X N", 2, ["X: unsigned type T", "N: T"], "T", "Rotate left; N outside 0..w-1 traps 7.", "`rotr x n` and `rotl x n`", "om2_rotate"),
538 ("unroll", "for i T K unroll", 0, ["K: number 1..64"], "-", "Compile the loop body K times with a constant counter.", "`for i T K unroll`", "om2_unroll"),
539 ("inline", "fn NAME ... to T inline", 0, [], "-", "Compile every call of the function in place.", "`fn NAME ... to T inline`", "om2_unroll"),
540 ("fresh", "NAME edit T N fresh", 0, ["N: at most 64"], "-", "Incoming elements are unspecified; every read needs a prior write (error 27).", "A parameter `s edit T N fresh`", "om2_fresh"),
541 ("abstract", "abstract NAME T [ops W ...]", 2, ["T: uint or ulong", "W: rotr rotl and or xor"], "-", "Declare an abstract type made only by seal in NAMEmk.", "`abstract NAME T [ops W ...]`", "om2_abstract"),
542 ("seal", "seal NAME v", 2, ["NAME: abstract type", "v: its base type T"], "NAME", "Make an abstract value; only inside the function NAMEmk (else error 28).", "A value of it is made only by `seal NAME v`", "om2_abstract"),
543 ("open", "open v", 1, ["v: abstract value"], "base type T", "The base value of an abstract value.", "`open v` gives the T value.", "om2_abstract"),
544 ("holds", "holds NAME dup32", 2, ["NAME: ulong abstract type"], "-", "Run-time invariant on every seal: high 32 bits equal low 32 (trap 10).", "`holds NAME dup32`, at top level before the first `fn`", "om2_abstract"),
545 ("ops", "abstract NAME T ops W ...", 1, ["W: rotr rotl and or xor"], "-", "The operations allowed on an abstract type.", "[ops W ...]", "om2_abstract"),
546 ("layout", "layout NAME SIZE / field ... / end", 2, ["NAME: up to 8 bytes", "SIZE: 1..4096"], "-", "An external byte layout over a uchar array of SIZE bytes.", "`layout NAME SIZE`", "om2_layout"),
547 ("field", "field F T [COUNT] at OFF little|big", 5, ["T: integer type", "COUNT: 1..4096", "OFF: byte offset"], "-", "One field of a layout.", "`field F T [COUNT] at OFF little|big`", "om2_layout"),
548 ("at", "field F T at OFF ...", 1, ["OFF: byte offset"], "-", "Introduces a layout field's byte offset.", "at OFF little|big", "om2_layout"),
549 ("little", "field ... at OFF little", 0, [], "-", "Little-endian layout field.", "at OFF little|big", "om2_layout"),
550 ("big", "field ... at OFF big", 0, [], "-", "Big-endian layout field (REV on load/store).", "at OFF little|big", "om2_layout"),
551 ("part", "part A o k", 3, ["A: array name", "o: ulong", "k: ulong"], "view/edit of k elements", "Elements o..o+k-1 of A, only as an argument for an unsized parameter.", "`part A o k` (o, k ulong; another type is error 7)", "om2_part"),
552 ("out", "NAME out T N", 2, ["T: element type", "N: length"], "-", "A parameter written by the unit; inside it is an edit of T N.", "A parameter `NAME out T N`", "om2_out"),
553 ("export", "export fn NAME ...", 0, [], "-", "Mark a function-mode entry (no fn main).", "`export fn NAME ...` at top level", "om2_export"),
554]:
555 word(name, O2, form, ar, types, res, summ + " OM-2 units only (first line `om2`).", [c(OMG, quote), OM2], exid, profile="OM-2")
556
557missing = sorted(set(TAB) - set(W))
558extra = sorted(set(W) - set(TAB))
559assert not missing and not extra, (missing, extra)
560
561# ---------------------------------------------------------------- errors
562G15 = "seed/omc/gate15.sh"
563ERR = {
564 1: ("stdin read failed", "The compiler could not read its input (stdin is not readable, e.g. a directory).", "Give omc a readable source file on stdin.", None),
565 2: ("stdout write failed", "The compiler could not write the binary (stdout is full or closed).", "Write omc's stdout to a regular file with space.", None),
566 3: ("unknown name or field", "A word is used as a name but nothing of that name is in scope (or a struct has no such field).", "Declare the name first, or fix its spelling.", (OMG, "An unknown field is error 3.")),
567 4: ("line ends early", "The line stops before a required operand or word.", "Supply the missing operand (see the word's form).", (OMG, "error 4 if the line ends before `end`")),
568 5: ("extra words", "Words remain on the line after a complete statement.", "Remove the extra words or split the line.", (OMG, "trailing words (error 5)")),
569 6: ("malformed number", "A number has a non-digit character, more than 20 digits or a bad hex form.", "Write a plain decimal (or OM-2 lowercase 0x hex) number.", (OMG, "more than 20 digits, or a character that is not a digit, is error 6")),
570 7: ("type mismatch", "Two values of an operation, an assignment or a call argument have different types; there are no implicit conversions.", "Convert explicitly with a type word, e.g. `add int a int b`.", (OMG, "or the line is refused (error 7).")),
571 8: ("out of range", "A literal is outside its type, or a count/bound/trap code is out of its range.", "Use a value inside the type's range or a wider type.", (OMG, "it must be a")),
572 9: ("word not allowed here", "The word is not permitted in this position: break/continue outside a loop, new outside the outermost block, free/own/global/text as a statement, a seventh parameter slot, recursion in function mode.", "Move the statement to a valid position or use the documented alternative.", (OMG, "outside a loop: error 9.")),
573 10: ("duplicate name", "A name already in scope, a function or a struct is declared again.", "Choose a new name.", (OMG, "A new name")),
574 11: ("ambiguous bare number", "A number appears where no context gives it a type.", "Prefix it with a type word, e.g. `x = int 5`.", (OMG, "A bare number takes the type the place needs.")),
575 12: ("register pool exhausted", "More than 16 values are live at once in a function.", "Split the function or reuse names so fewer values are live.", (OMG, "A function that needs more than the 16 registers it hands out is error 12 (no spilling).")),
576 13: ("name too long", "A name has more than 63 characters, or an abstract, layout or layout-field name (or any name in IR mode) has more than 8.", "Shorten the name: at most 63 characters, 8 for abstract, layout and layout-field names and in IR mode.", (OMG, "A name may have up to 63 characters (error 13 beyond): functions, locals, parameters, `for` counters, globals, texts, constants, structs and struct fields.")),
577 14: ("capacity exceeded", "The unit needs more than a capacity omc still has. Every table that grows with the unit (input, output, names, functions, calls, trap sites, blocks, breaks) lives in one arena that has no size of its own: it grows while the host gives it memory, and the unit is refused only when the host refuses that growth (for example under an address-space limit) or the caller's memory ceiling OMC_MEMORY_MAX is reached; stderr then carries an `omc-use` record with full=1 after the error line. The other bounds are values nested deeper than 32768 levels, AArch64 output past 128 MiB, and the fixed tables OMEGESE 9.6 lists (for example 16 fields a struct, as in the example, 32 `export fn`, 64 unrolled copies and 4 inline levels).", "Bring the construct under the bound OMEGESE 9.6 names, split the unit, or give the compiler more memory. A unit whose first line is `usage` compiles as usual and prints its `omc-use` record (what each arena group holds) instead of the binary.", [(OMG, "input past a real capacity is refused with error 14, never overrun"), (OMG, "It grows while the host gives it memory; the host's refusal is error 14"), (OMG, "16 structs, 16 fields and 64 cells a struct")]),
578 15: ("missing end", "The input ends inside an open block.", "Add the missing `end`.", (OMG, "Missing function `end` is error 15.")),
579 16: ("syntax error or unknown word", "A line does not start with a known statement form, or a type/length position holds something else.", "Check the word's spelling and form with lookup.", (OMG, "a pool written without its length is refused (error 16)")),
580 17: ("line after a path end", "A line follows ret, break, continue, trap or exit in the same block and can never run.", "Delete the unreachable line or move it before the path end.", (OMG, "(a later line in the same block is error 17)", "outside a loop: error 9. Like ret, it ends the path (a later line in the same block is error 17)")),
581 18: ("missing ret", "A function with a result type can reach its end without a ret.", "Add a ret on every path (or make the function void).", (OMG, "A function with a return type whose `end` can be reached is error 18.")),
582 19: ("global passed or same array twice", "A global is passed as an argument, or one array is passed twice in a call.", "Copy the global into a local array (new) or pass distinct arrays.", (OMG, "A global is")),
583 20: ("write to a read-only array", "put, read or an edit argument targets a view or a text.", "Write into a local, global or edit array instead.", (OMG, "A view is read-only; `put`, `read` into it, or passing it as edit is error 20.")),
584 21: ("constant index out of range", "A literal index is outside the array or field.", "Use an index below the length.", (OMG, "A number index must be inside A when om4 reads it (error 21)")),
585 22: ("bad text literal", "A text literal has an unknown escape or no closing quote.", "Use only \\n \\t \\\\ \\\" escapes and close the quote.", (OMG, "any other escape, or a quote missing its end,")),
586 23: ("size capacity", "An array is over 16777216 elements, globals over 1 GiB or local arrays over 4 MiB.", "Use a smaller array.", (OMG, "at most 4 MiB of local arrays (error 23)")),
587 24: ("branch displacement out of range", "A branch target is misaligned or out of reach: B.cond, CBZ and CBNZ reach 2^18 words, B and BL 2^25.", "Split very large functions or programs; this is reached only by programs with about 1 MiB of code between a conditional branch and its target.", (OMG, "refused with error 24 before any output is accepted")),
588 25: ("not available on this target", "Under `target x86linux` or `target x86efi` a construct that target cannot emit: raw AArch64 `emit`, an AArch64-only word (dit, scrub, execpure), a bare unit or a Linux host word under x86efi, or an efi OP outside 0..14.", "Use the default AArch64 target for that construct, or write it with words the target supports.", (OMG, "a bare unit is refused at line 1 with error 25")),
589 26: ("bad memory ceiling", "The compiler's environment entry OMC_MEMORY_MAX is not empty, 0, or 1 to 19 decimal digits below 2^63, or an environment entry is too long to read whole. It is refused before any input is read, so the line is 0.", "Unset OMC_MEMORY_MAX, or set it to the ceiling in decimal bytes (0 or empty: none).", (OMG, "| omc 26 | the compiler's environment entry OMC_MEMORY_MAX is not empty")),
590 27: ("fresh element read before write (OM-2 init)", "A fresh parameter element is read before it is definitely written, or the array is passed on.", "Write every element before reading it (put with a number index).", (OMG, "else error 27, `obligation=init`, on the get line")),
591 28: ("abstract constructor violation (OM-2 ctor)", "seal outside the NAMEmk constructor, or a bad holds predicate.", "Seal only inside the function named NAME followed by mk.", (OMG, "a `seal` anywhere else is")),
592 29: ("layout violation (OM-2 layout)", "A `layout` line after the first `fn`; SIZE outside 1..4096; a field COUNT outside 1..4096 (a written 0 included); a field that starts or ends past SIZE; or two fields sharing a byte. A SIZE, COUNT or OFF written as 2^64 or more is error 8 instead.", "Put every layout above the first fn, keep SIZE and COUNT in 1..4096 (leave COUNT out for one element), and keep every field inside SIZE and apart from the others.", (OMG, "SIZE outside 1..4096 or a `layout` after the first `fn` is error 29")),
593 30: ("contract syntax (OM-2)", "Misplaced requires/ensures/invariant, result outside a value postcondition, or a forbidden predicate operation.", "Put contracts first in the function or loop body and use only pure integer/bool operations.", (OMG, "Compiler error **30** means misplaced")),
594}
595ERRS = {}
596for k, (meaning, cause, fix, doc) in ERR.items():
597 cites = [site(k), c(OMC, "fn fail code ulong to void")]
598 for d in (doc if isinstance(doc, list) else [doc] if doc else []):
599 cites.append(c(*d))
600 e = {"meaning": meaning, "cause": cause, "fix": fix, "citations": cites}
601 if k == 1:
602 e["example"] = None
603 e["reproduce"] = "omc < / (stdin is a directory: the read fails, exit 1, stderr 'omc: line 1: error 1')"
604 elif k == 2:
605 e["example"] = None
606 e["reproduce"] = "omc < ok.om > /dev/full (the write fails with ENOSPC, exit 2)"
607 elif k == 26:
608 e["example"] = None
609 e["reproduce"] = "OMC_MEMORY_MAX=12x omc < ok.om (refused before the input is read, exit 26, stderr 'omc: line 0: error 26')"
610 elif k == 24:
611 e["example"] = None
612 e["example_note"] = "No minimal example: it needs about 1 MiB of machine code between a branch and its target."
613 else:
614 e["example"] = f"e{k:02d}"
615 e["citations"].append(c(G15, "refusal cases (codes 1..30; 24 with its accept side)"))
616 ERRS[str(k)] = e
617
618# ---------------------------------------------------------------- traps
619TR = {1: ("OVERFLOW", "checked signed arithmetic out of range", "Signed add/sub/mul/neg/div/shl produced a value outside the type.", "Use a wider type, check the range first, or use an unsigned type if wrapping is intended.", (OMG, "Signed add, sub, mul, neg, div and shl trap 1")),
620 2: ("DIV0", "division by zero", "div or rem with a divisor of 0.", "Check the divisor before dividing.", (OMG, "div and rem trap 2 when the divisor is 0.")),
621 3: ("BOUNDS", "index or slice out of bounds", "A run-time index is not below the length, or a host/read/write slice is outside its array.", "Check the index against len A, or fix off/n.", (OMG, "traps 3 when it is not below the length")),
622 4: ("LOOP_BOUND", "loop exceeded its bound", "A while or for ran past its bound N; with no bound a while, and a for whose count is not a number, stop at 1000000 passes.", "Fix the loop condition or give the loop a larger `bound N` (up to 9223372036854775807).", (OMG, "past N iterations: trap 4")),
623 5: ("CAST", "checked conversion out of range", "A conversion `T v` got a value outside T.", "Check the range before converting, or convert to a wider type.", (OMG, "A conversion `<type> v` traps 5 when the value is outside the new type.")),
624 6: ("OOM", "stack pool exhausted", "A call or local array would go below the fixed 8 MiB stack (deep recursion).", "Bound the recursion or use a loop / smaller local arrays.", (OMG, "a call or a local array that would go below it traps")),
625 7: ("SHIFT", "shift or rotate amount out of range", "A shift or rotate amount is outside 0..width-1.", "Check the amount against the width.", (OMG, "A shift amount outside 0 .. width - 1 traps 7")),
626 8: ("RUNTIME", "runtime invariant broken", "A runtime invariant (double release, bad handle) failed; checked native code raises it only through `trap 8`.", "Find the explicit trap 8 in the program.", (IRH, "OSC_TRAP_RUNTIME = 8")),
627 9: ("REQUIRES", "precondition failed", "A requires clause was false on entry.", "Call the function only with arguments that satisfy its requires clauses.", (OMG, "False `requires` uses existing trap **9** (program exit **109**)")),
628 10: ("ENSURES", "postcondition or invariant failed", "An ensures, invariant or holds check was false.", "Fix the function body or loop so the stated property holds.", (OMG, "`ensures` or `invariant` uses existing trap **10** (exit **110**).")),
629 11: ("ARENA_FULL", "arena allocation over capacity", "An OSC arena allocation exceeded the arena's capacity; native program mode raises it only through `trap 11`.", "Find the explicit trap 11 in the program.", (IRH, "OSC_TRAP_ARENA_FULL = 11")),
630 12: ("STALE", "stale versioned handle", "A handle whose generation no longer matches its slot; native program mode raises it only through `trap 12`.", "Find the explicit trap 12 in the program.", (IRH, "OSC_TRAP_STALE = 12")),
631 13: ("POOL_FULL", "pool allocation with every slot live", "An OSC pool allocation found no free slot; native program mode raises it only through `trap 13`.", "Find the explicit trap 13 in the program.", (IRH, "OSC_TRAP_POOL_FULL = 13")),
632 14: ("RETIRED", "pool slot retired at the maximum generation", "An OSC pool allocation found only retired slots; native program mode raises it only through `trap 14`.", "Find the explicit trap 14 in the program.", (IRH, "OSC_TRAP_RETIRED = 14"))}
633TRAPS = {}
634for k, (name, meaning, cause, fix, doc) in TR.items():
635 TRAPS[str(k)] = {"name": name, "meaning": meaning, "cause": cause, "fix": fix,
636 "citations": [c(*doc), c(OMG, "A trap in program mode ends the program with exit status 100 + the trap code")],
637 "example": "contract_fail" if k == 9 else f"t{k:02d}"}
638TRAPS["4"]["citations"].insert(1, c(OMG, "With no bound a number count is not guarded and any other count traps 4 after 1000000 passes"))
639
640# ---------------------------------------------------------------- topics
641TOP = {
642 "requires": {"form": "requires BOOL", "summary": "OM-2 precondition: part of a function's prefix, checked on entry; false traps 9.",
643 "details": "Clauses run in declaration order after parameter binding. Predicates are pure: integer/bool operations, conversions, len and array reads only.",
644 "citations": [c(OMG, "`requires BOOL` and `ensures BOOL` form a function's prefix"), c(OMG, "False `requires` uses existing trap **9**")], "example": "contract_fail"},
645 "ensures": {"form": "ensures BOOL", "summary": "OM-2 postcondition: checked on every normal return; `result` names the returned value; false traps 10.",
646 "details": "Not run on exit or a trap. A parameter means its current value at return.",
647 "citations": [c(OMG, "Postconditions execute in declaration order on **every normal return**")], "example": "contracts"},
648 "invariant": {"form": "invariant BOOL", "summary": "OM-2 loop invariant: the prefix of a while or for body, checked at the loop head; false traps 10.",
649 "details": "Runs on entry, every backedge and before the final false condition.",
650 "citations": [c(OMG, "`invariant BOOL` forms the prefix of a `while` or `for` body")], "example": "contracts"},
651 "result": {"form": "result", "summary": "OM-2: the returned value, available only inside ensures clauses (elsewhere error 30).",
652 "details": "It has the declared return type; the caller receives the same value after the checks.",
653 "citations": [c(OMG, "The read-only name `result` is available only in value postconditions.")], "example": "contracts"},
654 "om2": {"form": "om2 | om2 diag | om2 fmt", "summary": "First line that opts a unit into profile OM-2 (rotate, unroll, inline, layout, abstract types, contracts, unsized views).",
655 "details": "Leading blank and note lines are skipped; in an OM-1 unit the om2 line is error 16.",
656 "citations": [c(OMG, "when the next line is exactly `om2`")], "example": "om2_rotate"},
657 "exit_status": {"summary": "Program exit status: main's value modulo 256; a trap N exits 100 + N; exit v exits v modulo 256.",
658 "details": "An explicit exit 101..114 cannot be told apart from a trap by status alone.",
659 "citations": [c(OMG, "main's value modulo 256"), c(OMG, "exit status 100 + the trap code")], "example": "exit"},
660 "packed_list": {"summary": "Host-word argument lists: little-endian u16 count, then per record a u16 length and the bytes.",
661 "details": "An exec argument packet (execprog, execpure, the first packet of execenv) is at most 65536 bytes with count 1..1024; every other packed list (renames, link, symlnk, the execenv environment) at most 4096 bytes with count 1..64. Zero bytes, truncation, trailing bytes or an out-of-range count trap 3.",
662 "citations": [c(OMG, "A packed list is a little-endian `u16` count followed by that many records"),
663 c(OMG, "An exec argument packet (`execprog`, `execpure` and the first packet of `execenv`) is at most 65536 bytes with count 1..1024;")], "example": "dirs"},
664 "paths": {"summary": "Host paths are length-delimited byte slices of at most 4095 bytes; embedded zero bytes trap 3.",
665 "details": "Relative paths resolve against the current directory (AT_FDCWD).",
666 "citations": [c(OMG, "Paths are at most 4095 bytes.")], "example": "files"},
667 "host_words": {"summary": "Native host words: Linux system calls with checked slices; results are long, negative errno on failure.",
668 "details": "They do not form a sandbox: they run with the process's permissions. Program mode only, except that an OM-2 function unit may use fopen, fclose, fstat, stat, lstat, the four identity words, the clocks monons, realns and sleepns, and the twelve mapping/device words on AArch64.",
669 "citations": [c(OMG, "These operations do not form a sandbox"), OM2FN_CITE], "example": "files"},
670 "compile_errors": {"summary": "omc writes `omc: line N: error K` to stderr and exits with K; use explain_error for any K.",
671 "details": "Codes 1..30 exist at the pin.",
672 "citations": [c(OMC, "fn fail code ulong to void")], "example": "e03"},
673 "traps": {"summary": "Run-time traps 1..14 end a program with exit 100 + code.",
674 "details": "Codes are part of the observable semantics and are never renumbered. Loops trap 4 past their bound: N from `bound N`, else 1000000 for a while and for a for whose count is not a number.",
675 "citations": [c(IRH, "Trap codes are part of the observable semantics"),
676 c(OMG, "default 1000000; past N iterations: trap 4"),
677 c(OMG, "With no bound a number count is not guarded and any other count traps 4 after 1000000 passes")], "example": "t02"},
678 "loops": {"form": "while COND [bound N] / end | for NAME TYPE COUNT [bound N] / end",
679 "summary": "Every loop except a for with a number count and no bound traps 4 (exit 104) past a pass limit.",
680 "details": "`bound N` (1..9223372036854775807; IR mode 1..1000000) caps a while or a for at N passes. Without it a while, and a for whose COUNT is not a number, stop at 1000000 passes; a for with a number COUNT is unguarded.",
681 "citations": [c(OMG, "N 1..9223372036854775807 (a number or any integer const; IR mode: 1..1000000), default 1000000; past N iterations: trap 4"),
682 c(OMG, "With no bound a number count is not guarded and any other count traps 4 after 1000000 passes; with `bound N` any count traps 4 after N passes")], "example": "for_guard"},
683 "contracts": {"summary": "OM-2 contracts: requires, ensures and invariant clauses checked at run time (traps 9 and 10).",
684 "details": "Compiler error 30 covers misplaced contracts, unavailable result and impure predicates.",
685 "citations": [c(OMG, "Compiler error **30** means misplaced")], "example": "contracts"},
686}
687
688# ---------------------------------------------------------------- tools (MCP definitions)
689SRC = {"type": "string", "description": "Omega (.om) source text of one unit"}
690TOOLS = [
691 {"name": "compile", "title": "Compile Omega source",
692 "description": "Compile Omega (.om) source with the pinned seeded compiler omc (omega-mv@" + REV[:8] + "). Returns ok, the binary's size and sha256, or the compile error {line, code, meaning, fix}.",
693 "inputSchema": {"type": "object", "properties": {"source": SRC}, "required": ["source"], "additionalProperties": False}},
694 {"name": "run", "title": "Compile and run Omega source",
695 "description": "Compile Omega source and run the program in an isolated sandbox (no network, no host filesystem, empty environment, CPU/memory/file/process limits). Returns the compile result, capped stdout/stderr and the interpreted exit status (normal, trap N with its meaning, or the limit that stopped it).",
696 "inputSchema": {"type": "object", "properties": {"source": SRC, "stdin": {"type": "string", "description": "bytes given to the program on stdin (default empty)"},
697 "timeout_ms": {"type": "integer", "minimum": 1, "maximum": 30000, "description": "wall-clock limit in milliseconds (default 5000)"}},
698 "required": ["source"], "additionalProperties": False}},
699 {"name": "explain_error", "title": "Explain an Omega error or trap",
700 "description": "Explain a compile error code 1..30, an `omc: line N: error K` line, `trap T`, or a program exit status 101..114 (trap). Returns meaning, cause, fix, a minimal example and source citations.",
701 "inputSchema": {"type": "object", "properties": {"query": {"type": ["string", "integer"], "description": "an error code 1..30, an `omc: line N: error K` line, `trap T` (1..14) or an exit status 101..114; a string of 1..200 bytes or a nonnegative integer"}},
702 "required": ["query"], "additionalProperties": False}},
703 {"name": "lookup", "title": "Look up an Omega word or topic",
704 "description": "Look up any Omega keyword (all " + str(len(TAB)) + " entries of the compiler's keyword table) or a topic (requires, ensures, invariant, result, om2, exit_status, packed_list, paths, host_words, compile_errors, traps, loops, contracts): form, arity, types, result, example and citations. A query that is not an exact keyword or topic searches names and summaries (at most 20 results).",
705 "inputSchema": {"type": "object", "properties": {"query": {"type": "string", "minLength": 1, "maxLength": 64, "description": "exact keyword or topic, or a case-insensitive substring to search for"}},
706 "required": ["query"], "additionalProperties": False}},
707]
708
709if set(TAB) - set(W):
710 raise SystemExit(f"gen-reference: keywords at omega-mv {REV[:8]} with no entry here: {sorted(set(TAB) - set(W))}")
711ref = {"pin": {"omega_mv": REV, "omc_sha256": OMC_SHA},
712 "tools": TOOLS, "errors": ERRS, "traps": TRAPS, "words": W, "topics": TOP,
713 "examples": {i: exp for i, (src, exp) in EX.items()}}
714used = {e["example"] for e in W.values()} | {e["example"] for e in ERRS.values() if e["example"]} | \
715 {e["example"] for e in TRAPS.values()} | {e["example"] for e in TOP.values()}
716unused = sorted(set(EX) - used)
717assert not unused, unused
718os.makedirs(OUT + "/examples", exist_ok=True)
719for f in os.listdir(OUT + "/examples"):
720 os.remove(OUT + "/examples/" + f)
721for i, (src, exp) in EX.items():
722 assert re.fullmatch(r"[a-z0-9_]+", i)
723 open(f"{OUT}/examples/{i}.om", "w").write(src)
724raw = json.dumps(ref, indent=1, ensure_ascii=True) + "\n"
725open(OUT + "/reference.json", "w").write(raw)
726print("words", len(W), "errors", len(ERRS), "traps", len(TRAPS), "examples", len(EX), "bytes", len(raw))