omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / bench / multipl-e / humaneval_to_om.py
| 1 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 2 | """MultiPL-E translator from the Python benchmarks to Omega (OM-2 profile). |
| 3 | |
| 4 | Foreign-harness adapter: MultiPL-E loads translators as Python classes named |
| 5 | ``Translator`` in ``dataset_builder/humaneval_to_<ext>.py``, so this file is Python. It |
| 6 | is not first-party Omega and is not part of any Omega product path. Every |
| 7 | program it writes is plain OM-2 for the pinned ``omc`` (see ``bench/README.md`` in |
| 8 | https://github.com/aien-dev/omega-rosetta). |
| 9 | |
| 10 | Shape of a translated problem:: |
| 11 | |
| 12 | om2 |
| 13 | note <docstring lines> |
| 14 | note <interface notes: renamed parameters, result-array convention> |
| 15 | fn NAME PARAM TYPE ... to TYPE |
| 16 | <completion: body lines and the closing end> |
| 17 | <tests: one `fn tc_K to bool` per assert, then `fn main to int`> |
| 18 | |
| 19 | ``main`` returns K+1 when test case K fails (so 1..98), writes the line |
| 20 | ``MPE_OK_LINE`` and returns 0 when every case holds. A trap exits 100+code. |
| 21 | |
| 22 | Type mapping:: |
| 23 | |
| 24 | int -> long float -> f64 bool -> bool |
| 25 | List[int] -> view long * List[float] -> view f64 * |
| 26 | str -> view uchar * (bytes; non-ASCII test strings are refused) |
| 27 | Tuple[int, int] (homogeneous int/float) -> view long * / view f64 * |
| 28 | |
| 29 | A list, string or tuple RESULT becomes an extra last parameter ``res edit T *`` and |
| 30 | the function returns the element count as ``long``; the test checks the count and |
| 31 | then every element. Every other type is refused with a reason (``translate_prompt`` |
| 32 | returns None and ``self.refusal`` names why). |
| 33 | """ |
| 34 | |
| 35 | import ast |
| 36 | import math |
| 37 | import re |
| 38 | from typing import List, Optional |
| 39 | |
| 40 | # omega-mv commit whose pinned omc defines this profile. |
| 41 | OMEGA_MV_PIN = "e5b32567a7aff3ce594e3254a622a846a6cd190b" |
| 42 | |
| 43 | # Every word of the pinned omc keyword tables (seed/omc/omc.om `fn kw` and |
| 44 | # `fn kw2` at OMEGA_MV_PIN, decoded from their packed little-endian constants). |
| 45 | # A parameter or function may not use any of these as its name. |
| 46 | KEYWORDS = frozenset( |
| 47 | """ |
| 48 | abstract accept add and argcnt argread at big bind bitcast bool bound break byte |
| 49 | chdir chmod chown connect const continue cwd devcall devctl div dupfd edit else |
| 50 | end envcnt envread eq execprog exit export f32 f64 fabs faccess false fchdir |
| 51 | fchmod fclose fdsync field flock fmax fmin fn fopen for fork free fresh fseek |
| 52 | fsqrt fstat fsync ftrunc ge get getdnts getegid geteuid getgid getpgid getpid |
| 53 | getppid getsid getuid global gt holds i16 i32 i64 i8 if inline int killpid |
| 54 | layout le len link listen little long lstat lt makedir mapaddr mapbind mapdrop |
| 55 | mapget maphold mapnew mapread mapset mapwrite memfd monons mul ne neg new not |
| 56 | note offsetof open ops or out own part peercred pipefds pollfds pread put pwrite |
| 57 | random read readlnk realns recv rem renames ret rmdir rotl rotr seal send |
| 58 | sendmsg setpgid setsid shl short shr shutdown sizeof sleepns sockname socknew |
| 59 | sockopt stat struct sub symlnk syncfs text to trap true truncate u16 u32 u64 u8 |
| 60 | uchar uint ulong umask unlink unroll ushort uvmctl view void waitio waitpid |
| 61 | while write xor |
| 62 | """.split() |
| 63 | ) |
| 64 | # Names the generated test harness itself declares. |
| 65 | HARNESS_NAMES = frozenset(["main", "res", "r", "w", "mpe_ok", "om2", "ir"]) |
| 66 | HARNESS_NAME_RE = re.compile(r"(tc_\d+|t\d+_\d+|a\d+)\Z") |
| 67 | |
| 68 | MAX_LOCAL = 8 # error 13: a non-function name has at most 8 characters |
| 69 | MAX_FN = 63 # function names |
| 70 | MAX_SLOTS = 6 # error 9: six parameter slots; an unsized view takes two |
| 71 | MAX_CASES = 98 # exit codes 1..98 name the failing case; 100+ are traps |
| 72 | RESULT_CAP = 4096 # minimum capacity of the result array handed to the candidate |
| 73 | I64_MIN, I64_MAX = -(2**63), 2**63 - 1 |
| 74 | MPE_OK_LINE = "MultiPL-E Omega: all tests passed" |
| 75 | |
| 76 | |
| 77 | class Refused(Exception): |
| 78 | """A problem the OM-2 mapping cannot express. ``code`` is the tally key.""" |
| 79 | |
| 80 | def __init__(self, code: str, detail: str = ""): |
| 81 | super().__init__(f"{code}: {detail}" if detail else code) |
| 82 | self.code = code |
| 83 | self.detail = detail |
| 84 | |
| 85 | |
| 86 | class Scalar: |
| 87 | def __init__(self, om: str): |
| 88 | self.om = om # long | f64 | bool |
| 89 | |
| 90 | slots = 1 |
| 91 | |
| 92 | def __repr__(self): |
| 93 | return self.om |
| 94 | |
| 95 | |
| 96 | class Seq: |
| 97 | """A list, string or fixed tuple: an unsized view of `elem`.""" |
| 98 | |
| 99 | def __init__(self, elem: str, py: str, fixed: Optional[int] = None): |
| 100 | self.elem = elem # long | f64 | uchar |
| 101 | self.py = py # list | str | tuple |
| 102 | self.fixed = fixed |
| 103 | |
| 104 | slots = 2 |
| 105 | |
| 106 | def __repr__(self): |
| 107 | return f"view {self.elem} *" |
| 108 | |
| 109 | |
| 110 | SCALARS = {"int": "long", "float": "f64", "bool": "bool"} |
| 111 | SEQ_ELEMS = {"int": "long", "float": "f64"} |
| 112 | |
| 113 | |
| 114 | def _head(node: ast.expr) -> str: |
| 115 | if isinstance(node, ast.Name): |
| 116 | return node.id |
| 117 | if isinstance(node, ast.Attribute): |
| 118 | return node.attr |
| 119 | return type(node).__name__ |
| 120 | |
| 121 | |
| 122 | def om_type(ann: Optional[ast.expr]): |
| 123 | """Map one Python annotation to Scalar/Seq, or raise Refused.""" |
| 124 | if ann is None: |
| 125 | raise Refused("type:untyped", "parameter or return has no annotation") |
| 126 | text = ast.unparse(ann) |
| 127 | if isinstance(ann, ast.Constant) and ann.value is None: |
| 128 | raise Refused("type:None", "no result value to test") |
| 129 | if isinstance(ann, ast.Name): |
| 130 | if ann.id in SCALARS: |
| 131 | return Scalar(SCALARS[ann.id]) |
| 132 | if ann.id == "str": |
| 133 | return Seq("uchar", "str") |
| 134 | raise Refused(f"type:{ann.id}", text) |
| 135 | if isinstance(ann, ast.Subscript): |
| 136 | head = _head(ann.value) |
| 137 | if head in ("List", "list"): |
| 138 | inner = ann.slice |
| 139 | if isinstance(inner, ast.Name) and inner.id in SEQ_ELEMS: |
| 140 | return Seq(SEQ_ELEMS[inner.id], "list") |
| 141 | if isinstance(inner, ast.Name) and inner.id == "str": |
| 142 | raise Refused("type:List[str]", "OM-2 has no array-of-strings type") |
| 143 | if isinstance(inner, ast.Name) and inner.id == "bool": |
| 144 | raise Refused("type:List[bool]", "omc refuses bool arrays (new bool N, error 9)") |
| 145 | raise Refused("type:List[compound]", text) |
| 146 | if head in ("Tuple", "tuple"): |
| 147 | elts = ann.slice.elts if isinstance(ann.slice, ast.Tuple) else [ann.slice] |
| 148 | names = [e.id if isinstance(e, ast.Name) else None for e in elts] |
| 149 | if len(set(names)) == 1 and names[0] in SEQ_ELEMS: |
| 150 | return Seq(SEQ_ELEMS[names[0]], "tuple", fixed=len(elts)) |
| 151 | raise Refused("type:Tuple[mixed]", text) |
| 152 | raise Refused(f"type:{head}", text) |
| 153 | raise Refused("type:other", text) |
| 154 | |
| 155 | |
| 156 | def _name_ok(name: str, used: set) -> bool: |
| 157 | return ( |
| 158 | name not in KEYWORDS |
| 159 | # The pinned omc looks a word up in its keyword table by its first eight bytes |
| 160 | # only (omc.om `fn kw` takes one packed ulong), so it reads a longer name such as |
| 161 | # truncate_number or continue_x as the keyword truncate / continue (error 16). |
| 162 | and name[:8] not in KEYWORDS |
| 163 | and name not in HARNESS_NAMES |
| 164 | and name not in used |
| 165 | and not HARNESS_NAME_RE.match(name) |
| 166 | ) |
| 167 | |
| 168 | |
| 169 | def fit_name(py: str, used: set, limit: int) -> str: |
| 170 | """An Omega name for Python identifier `py`: at most `limit` characters, not a |
| 171 | keyword (nor starting with an eight-letter one), not a harness name, not used.""" |
| 172 | base = py[:limit] |
| 173 | if len(base) > 8 and base[:8] in KEYWORDS: |
| 174 | base = base[0].upper() + base[1:] |
| 175 | if _name_ok(base, used): |
| 176 | return base |
| 177 | for k in range(1, 100): |
| 178 | suffix = "_" if k == 1 else f"_{k}" |
| 179 | cand = base[: limit - len(suffix)] + suffix |
| 180 | if _name_ok(cand, used): |
| 181 | return cand |
| 182 | raise Refused("name:unmappable", py) |
| 183 | |
| 184 | |
| 185 | def f64_literal(v) -> str: |
| 186 | """Exact round-trip OM-2 float literal (digits.digits[e[-]digits]).""" |
| 187 | f = float(v) |
| 188 | if not math.isfinite(f): |
| 189 | raise Refused("value:non-finite float", repr(v)) |
| 190 | if isinstance(v, int) and float(f) != v: |
| 191 | raise Refused("value:int not exact in f64", repr(v)) |
| 192 | r = repr(f) |
| 193 | if "e" in r: |
| 194 | mant, exp = r.split("e") |
| 195 | if "." not in mant: |
| 196 | mant += ".0" |
| 197 | return f"{mant}e{int(exp)}" |
| 198 | if "." not in r: |
| 199 | r += ".0" |
| 200 | return r |
| 201 | |
| 202 | |
| 203 | class OmExpr(str): |
| 204 | """A rendered expression (for doctests and the seen_tests table) that keeps |
| 205 | its structure in `.node` for test generation.""" |
| 206 | |
| 207 | def __new__(cls, text: str, node): |
| 208 | s = super().__new__(cls, text) |
| 209 | s.node = node |
| 210 | return s |
| 211 | |
| 212 | |
| 213 | def _render(node) -> str: |
| 214 | kind = node[0] |
| 215 | if kind == "lit": |
| 216 | v = node[1] |
| 217 | if isinstance(v, bool): |
| 218 | return "true" if v else "false" |
| 219 | if isinstance(v, float): |
| 220 | return repr(v) |
| 221 | if isinstance(v, str): |
| 222 | return '"' + v.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t") + '"' |
| 223 | if v is None: |
| 224 | return "none" |
| 225 | return str(v) |
| 226 | if kind == "var": |
| 227 | return node[1] |
| 228 | if kind in ("list", "tuple", "set"): |
| 229 | o, c = {"list": "[]", "tuple": "()", "set": "{}"}[kind] |
| 230 | return o + ", ".join(_render(e) for e in node[1]) + c |
| 231 | if kind == "dict": |
| 232 | return "{" + ", ".join(f"{_render(k)}: {_render(v)}" for k, v in zip(node[1], node[2])) + "}" |
| 233 | if kind == "call": |
| 234 | parts = [_render(node[1])] + [_render(a) for a in node[2]] |
| 235 | return " ".join(parts) |
| 236 | raise ValueError(node) |
| 237 | |
| 238 | |
| 239 | _TEXT_SAFE = re.compile(rb"[\x20-\x7e\n\t]*\Z") |
| 240 | |
| 241 | |
| 242 | def _text_literal(b: bytes) -> Optional[str]: |
| 243 | """An OM-2 `text` literal for bytes b, or None when b needs an escape omc lacks.""" |
| 244 | if not _TEXT_SAFE.match(b): |
| 245 | return None |
| 246 | s = b.decode("ascii") |
| 247 | return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t") + '"' |
| 248 | |
| 249 | |
| 250 | class Translator: |
| 251 | stop = ["\nfn ", "\nstruct ", "\nglobal ", "\ntext ", "\nconst ", "\nlayout ", "\nabstract "] |
| 252 | |
| 253 | def __init__(self): |
| 254 | self.refusal: Optional[Refused] = None |
| 255 | self.params = [] # [(py_name, om_name, type)] |
| 256 | self.ret = None |
| 257 | self.fn = None |
| 258 | self.py_fn = None |
| 259 | self.res = None |
| 260 | self.cases = [] |
| 261 | |
| 262 | def file_ext(self): |
| 263 | return "om" |
| 264 | |
| 265 | def no_completion_prompt_stub(self): |
| 266 | return "trap 14\nend\n" |
| 267 | |
| 268 | # ---- prompt --------------------------------------------------------------- |
| 269 | |
| 270 | def translate_prompt(self, name: str, args: List[ast.arg], returns, description: str) -> Optional[str]: |
| 271 | self.refusal = None |
| 272 | try: |
| 273 | return self._prompt(name, args, returns, description) |
| 274 | except Refused as e: |
| 275 | self.refusal = e |
| 276 | return None |
| 277 | |
| 278 | def _prompt(self, name, args, returns, description): |
| 279 | self.py_fn = name |
| 280 | self.fn = fit_name(name, set(), MAX_FN) |
| 281 | used = {self.fn} |
| 282 | self.params = [] |
| 283 | for a in args: |
| 284 | t = om_type(a.annotation) |
| 285 | om = fit_name(a.arg, used, MAX_LOCAL) |
| 286 | used.add(om) |
| 287 | self.params.append((a.arg, om, t)) |
| 288 | self.ret = om_type(returns) |
| 289 | self.res = None |
| 290 | if isinstance(self.ret, Seq): |
| 291 | self.res = "res" # HARNESS_NAMES keeps parameters off this name |
| 292 | slots = sum(t.slots for _, _, t in self.params) + (2 if self.res else 0) |
| 293 | if slots > MAX_SLOTS: |
| 294 | raise Refused("abi:parameter slots", f"{slots} > {MAX_SLOTS}") |
| 295 | |
| 296 | lines = ["om2"] |
| 297 | for line in description.strip().split("\n"): |
| 298 | lines.append(("note " + line).rstrip()) |
| 299 | renamed = [(py, om) for py, om, _ in self.params if py != om] |
| 300 | if self.fn != name: |
| 301 | renamed.insert(0, (name, self.fn)) |
| 302 | for py, om in renamed: |
| 303 | lines.append(f"note Omega name: {py} is {om} here.") |
| 304 | if self.res: |
| 305 | what = {"str": "bytes", "list": "elements", "tuple": "elements"}[self.ret.py] |
| 306 | lines.append( |
| 307 | f"note Result: write the {what} into res (len res >= {RESULT_CAP}) and return how many were written." |
| 308 | ) |
| 309 | sig = [self.fn] |
| 310 | for _, om, t in self.params: |
| 311 | sig.append(f"{om} {t.om}" if isinstance(t, Scalar) else f"{om} view {t.elem} *") |
| 312 | if self.res: |
| 313 | sig.append(f"res edit {self.ret.elem} *") |
| 314 | rt = "long" if self.res else self.ret.om |
| 315 | lines.append("fn " + " ".join(sig) + f" to {rt}") |
| 316 | return "\n".join(lines) + "\n" |
| 317 | |
| 318 | # ---- values --------------------------------------------------------------- |
| 319 | |
| 320 | def gen_literal(self, c): |
| 321 | return ("lit", c) |
| 322 | |
| 323 | def gen_var(self, v): |
| 324 | if v == "candidate" or v == self.py_fn: |
| 325 | return ("var", self.fn or v) |
| 326 | return ("var", v) |
| 327 | |
| 328 | def gen_list(self, l): |
| 329 | return ("list", l) |
| 330 | |
| 331 | def gen_tuple(self, t): |
| 332 | return ("tuple", t) |
| 333 | |
| 334 | def gen_dict(self, keys, values): |
| 335 | return ("dict", keys, values) |
| 336 | |
| 337 | def gen_set(self, s): |
| 338 | return ("set", s) |
| 339 | |
| 340 | def gen_call(self, func, args): |
| 341 | return ("call", func, args) |
| 342 | |
| 343 | def finalize(self, expr, context): |
| 344 | return OmExpr(_render(expr), expr) |
| 345 | |
| 346 | # ---- tests ---------------------------------------------------------------- |
| 347 | |
| 348 | def test_suite_prefix_lines(self, entry_point): |
| 349 | self.cases = [] |
| 350 | return [] |
| 351 | |
| 352 | def test_suite_suffix_lines(self): |
| 353 | lines = [f'text mpe_ok "{MPE_OK_LINE}\\n"', "fn main to int"] |
| 354 | for k in range(len(self.cases)): |
| 355 | lines += [f"if not tc_{k}", f"ret {k + 1}", "end"] |
| 356 | lines += ["w = write 1 mpe_ok 0 len mpe_ok", "ret 0", "end"] |
| 357 | return lines |
| 358 | |
| 359 | def _scalar(self, node, t: Scalar, rhs: bool) -> str: |
| 360 | if node[0] != "lit": |
| 361 | raise Refused("value:non-literal", _render(node)) |
| 362 | v = node[1] |
| 363 | if t.om == "bool": |
| 364 | if isinstance(v, bool): |
| 365 | return "true" if v else "false" |
| 366 | if rhs and isinstance(v, int) and v in (0, 1): |
| 367 | return "true" if v else "false" |
| 368 | raise Refused("value:not a bool", repr(v)) |
| 369 | if t.om == "long": |
| 370 | if isinstance(v, bool): |
| 371 | return "1" if v else "0" |
| 372 | if isinstance(v, float) and v.is_integer(): |
| 373 | v = int(v) |
| 374 | if not isinstance(v, int): |
| 375 | raise Refused("value:not an int", repr(v)) |
| 376 | if not I64_MIN <= v <= I64_MAX: |
| 377 | raise Refused("value:int outside i64", repr(v)) |
| 378 | return str(v) |
| 379 | if isinstance(v, bool) or not isinstance(v, (int, float)): |
| 380 | raise Refused("value:not a float", repr(v)) |
| 381 | return f64_literal(v) |
| 382 | |
| 383 | def _elements(self, node, t: Seq, rhs: bool) -> List[str]: |
| 384 | if t.py == "str": |
| 385 | if node[0] != "lit" or not isinstance(node[1], str): |
| 386 | raise Refused("value:not a str", _render(node)) |
| 387 | if not node[1].isascii(): |
| 388 | raise Refused("value:non-ASCII string", "Omega strings are bytes, Python str is code points") |
| 389 | return [str(b) for b in node[1].encode("ascii")] |
| 390 | if node[0] not in ("list", "tuple"): |
| 391 | raise Refused("value:not a sequence", _render(node)) |
| 392 | if t.fixed is not None and len(node[1]) != t.fixed: |
| 393 | raise Refused("value:tuple arity", _render(node)) |
| 394 | return [self._scalar(e, Scalar(t.elem), rhs) for e in node[1]] |
| 395 | |
| 396 | def deep_equality(self, left, right): |
| 397 | try: |
| 398 | return self._case(left.node, right.node) |
| 399 | except Refused as e: |
| 400 | self.refusal = e |
| 401 | raise |
| 402 | |
| 403 | def _case(self, call, expect): |
| 404 | if call[0] != "call" or call[1] != ("var", self.fn): |
| 405 | raise Refused("tests:not a direct candidate call", _render(call)) |
| 406 | if len(call[2]) != len(self.params): |
| 407 | raise Refused("tests:arity", _render(call)) |
| 408 | k = len(self.cases) |
| 409 | if k >= MAX_CASES: |
| 410 | raise Refused("tests:too many cases", f"> {MAX_CASES}") |
| 411 | texts, body, argv = [], [], [] |
| 412 | for j, (node, (_, _, t)) in enumerate(zip(call[2], self.params)): |
| 413 | if isinstance(t, Scalar): |
| 414 | argv.append(self._scalar(node, t, rhs=False)) |
| 415 | continue |
| 416 | elems = self._elements(node, t, rhs=False) |
| 417 | # An empty string goes through `part a 0 0`, never `text t ""`: the pinned omc |
| 418 | # takes a zero-length name as an unsized parameter (omc.om arrarg, nm_len 0) |
| 419 | # and passes a stale register as the count, so `len` is garbage in the callee. |
| 420 | if t.py == "str" and elems: |
| 421 | lit = _text_literal(node[1].encode("ascii")) |
| 422 | if lit is not None: |
| 423 | texts.append(f"text t{k}_{j} {lit}") |
| 424 | argv.append(f"t{k}_{j}") |
| 425 | continue |
| 426 | zero = "0.0" if t.elem == "f64" else "0" |
| 427 | body.append(f"a{j} = new {t.elem} {max(1, len(elems))} {zero}") |
| 428 | body += [f"put a{j} {i} {v}" for i, v in enumerate(elems)] |
| 429 | argv.append(f"a{j}" if elems else f"part a{j} 0 0") |
| 430 | if self.res: |
| 431 | zero = "0.0" if self.ret.elem == "f64" else "0" |
| 432 | exp = self._elements(expect, self.ret, rhs=True) |
| 433 | body.append(f"res = new {self.ret.elem} {max(RESULT_CAP, len(exp))} {zero}") |
| 434 | argv.append("res") |
| 435 | body.append(f"r = {self.fn} {' '.join(argv)}".rstrip()) |
| 436 | body += [f"if ne r {len(exp)}", "ret false", "end"] |
| 437 | for i, v in enumerate(exp): |
| 438 | body += [f"if ne get res {i} {v}", "ret false", "end"] |
| 439 | body.append("ret true") |
| 440 | else: |
| 441 | exp = self._scalar(expect, self.ret, rhs=True) |
| 442 | body.append(f"r = {self.fn} {' '.join(argv)}".rstrip()) |
| 443 | body.append(f"ret eq r {exp}") |
| 444 | self.cases.append(k) |
| 445 | return "\n".join(texts + [f"fn tc_{k} to bool"] + body + ["end"]) |