omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / bench / upstream / 0001-Add-Omega-OM-2-translator-and-evaluator.patch
| 1 | From b29c2173d3855117b54b5c7e5bc54f94911a12ff Mon Sep 17 00:00:00 2001 |
| 2 | From: Drake Stapleton <aien@aienos.com> |
| 3 | Date: Tue, 27 Oct 2026 06:55:03 -0500 |
| 4 | Subject: [PATCH] Add Omega (OM-2) translator and evaluator |
| 5 | |
| 6 | Adds dataset_builder/humaneval_to_om.py, evaluation/src/eval_om.py, the |
| 7 | Omega row in terms.csv, the om entry in containerized_eval.py and an |
| 8 | evaluation/test_inputs example (HumanEval_53: one passing completion, one |
| 9 | that does not compile). |
| 10 | --- |
| 11 | dataset_builder/humaneval_to_om.py | 445 ++++++++++++++++++ |
| 12 | dataset_builder/terms.csv | 1 + |
| 13 | evaluation/src/containerized_eval.py | 2 + |
| 14 | evaluation/src/eval_om.py | 143 ++++++ |
| 15 | .../om-hand-0.0-keep-HumanEval53.json | 19 + |
| 16 | 5 files changed, 610 insertions(+) |
| 17 | create mode 100644 dataset_builder/humaneval_to_om.py |
| 18 | create mode 100755 evaluation/src/eval_om.py |
| 19 | create mode 100644 evaluation/test_inputs/om-hand-0.0-keep-HumanEval53.json |
| 20 | |
| 21 | diff --git a/dataset_builder/humaneval_to_om.py b/dataset_builder/humaneval_to_om.py |
| 22 | new file mode 100644 |
| 23 | index 0000000..9e7c4a3 |
| 24 | --- /dev/null |
| 25 | +++ b/dataset_builder/humaneval_to_om.py |
| 26 | @@ -0,0 +1,445 @@ |
| 27 | +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 28 | +"""MultiPL-E translator from the Python benchmarks to Omega (OM-2 profile). |
| 29 | + |
| 30 | +Foreign-harness adapter: MultiPL-E loads translators as Python classes named |
| 31 | +``Translator`` in ``dataset_builder/humaneval_to_<ext>.py``, so this file is Python. It |
| 32 | +is not first-party Omega and is not part of any Omega product path. Every |
| 33 | +program it writes is plain OM-2 for the pinned ``omc`` (see ``bench/README.md`` in |
| 34 | +https://github.com/aien-dev/omega-rosetta). |
| 35 | + |
| 36 | +Shape of a translated problem:: |
| 37 | + |
| 38 | + om2 |
| 39 | + note <docstring lines> |
| 40 | + note <interface notes: renamed parameters, result-array convention> |
| 41 | + fn NAME PARAM TYPE ... to TYPE |
| 42 | + <completion: body lines and the closing end> |
| 43 | + <tests: one `fn tc_K to bool` per assert, then `fn main to int`> |
| 44 | + |
| 45 | +``main`` returns K+1 when test case K fails (so 1..98), writes the line |
| 46 | +``MPE_OK_LINE`` and returns 0 when every case holds. A trap exits 100+code. |
| 47 | + |
| 48 | +Type mapping:: |
| 49 | + |
| 50 | + int -> long float -> f64 bool -> bool |
| 51 | + List[int] -> view long * List[float] -> view f64 * |
| 52 | + str -> view uchar * (bytes; non-ASCII test strings are refused) |
| 53 | + Tuple[int, int] (homogeneous int/float) -> view long * / view f64 * |
| 54 | + |
| 55 | +A list, string or tuple RESULT becomes an extra last parameter ``res edit T *`` and |
| 56 | +the function returns the element count as ``long``; the test checks the count and |
| 57 | +then every element. Every other type is refused with a reason (``translate_prompt`` |
| 58 | +returns None and ``self.refusal`` names why). |
| 59 | +""" |
| 60 | + |
| 61 | +import ast |
| 62 | +import math |
| 63 | +import re |
| 64 | +from typing import List, Optional |
| 65 | + |
| 66 | +# omega-mv commit whose pinned omc defines this profile. |
| 67 | +OMEGA_MV_PIN = "e5b32567a7aff3ce594e3254a622a846a6cd190b" |
| 68 | + |
| 69 | +# Every word of the pinned omc keyword tables (seed/omc/omc.om `fn kw` and |
| 70 | +# `fn kw2` at OMEGA_MV_PIN, decoded from their packed little-endian constants). |
| 71 | +# A parameter or function may not use any of these as its name. |
| 72 | +KEYWORDS = frozenset( |
| 73 | + """ |
| 74 | + abstract accept add and argcnt argread at big bind bitcast bool bound break byte |
| 75 | + chdir chmod chown connect const continue cwd devcall devctl div dupfd edit else |
| 76 | + end envcnt envread eq execprog exit export f32 f64 fabs faccess false fchdir |
| 77 | + fchmod fclose fdsync field flock fmax fmin fn fopen for fork free fresh fseek |
| 78 | + fsqrt fstat fsync ftrunc ge get getdnts getegid geteuid getgid getpgid getpid |
| 79 | + getppid getsid getuid global gt holds i16 i32 i64 i8 if inline int killpid |
| 80 | + layout le len link listen little long lstat lt makedir mapaddr mapbind mapdrop |
| 81 | + mapget maphold mapnew mapread mapset mapwrite memfd monons mul ne neg new not |
| 82 | + note offsetof open ops or out own part peercred pipefds pollfds pread put pwrite |
| 83 | + random read readlnk realns recv rem renames ret rmdir rotl rotr seal send |
| 84 | + sendmsg setpgid setsid shl short shr shutdown sizeof sleepns sockname socknew |
| 85 | + sockopt stat struct sub symlnk syncfs text to trap true truncate u16 u32 u64 u8 |
| 86 | + uchar uint ulong umask unlink unroll ushort uvmctl view void waitio waitpid |
| 87 | + while write xor |
| 88 | + """.split() |
| 89 | +) |
| 90 | +# Names the generated test harness itself declares. |
| 91 | +HARNESS_NAMES = frozenset(["main", "res", "r", "w", "mpe_ok", "om2", "ir"]) |
| 92 | +HARNESS_NAME_RE = re.compile(r"(tc_\d+|t\d+_\d+|a\d+)\Z") |
| 93 | + |
| 94 | +MAX_LOCAL = 8 # error 13: a non-function name has at most 8 characters |
| 95 | +MAX_FN = 63 # function names |
| 96 | +MAX_SLOTS = 6 # error 9: six parameter slots; an unsized view takes two |
| 97 | +MAX_CASES = 98 # exit codes 1..98 name the failing case; 100+ are traps |
| 98 | +RESULT_CAP = 4096 # minimum capacity of the result array handed to the candidate |
| 99 | +I64_MIN, I64_MAX = -(2**63), 2**63 - 1 |
| 100 | +MPE_OK_LINE = "MultiPL-E Omega: all tests passed" |
| 101 | + |
| 102 | + |
| 103 | +class Refused(Exception): |
| 104 | + """A problem the OM-2 mapping cannot express. ``code`` is the tally key.""" |
| 105 | + |
| 106 | + def __init__(self, code: str, detail: str = ""): |
| 107 | + super().__init__(f"{code}: {detail}" if detail else code) |
| 108 | + self.code = code |
| 109 | + self.detail = detail |
| 110 | + |
| 111 | + |
| 112 | +class Scalar: |
| 113 | + def __init__(self, om: str): |
| 114 | + self.om = om # long | f64 | bool |
| 115 | + |
| 116 | + slots = 1 |
| 117 | + |
| 118 | + def __repr__(self): |
| 119 | + return self.om |
| 120 | + |
| 121 | + |
| 122 | +class Seq: |
| 123 | + """A list, string or fixed tuple: an unsized view of `elem`.""" |
| 124 | + |
| 125 | + def __init__(self, elem: str, py: str, fixed: Optional[int] = None): |
| 126 | + self.elem = elem # long | f64 | uchar |
| 127 | + self.py = py # list | str | tuple |
| 128 | + self.fixed = fixed |
| 129 | + |
| 130 | + slots = 2 |
| 131 | + |
| 132 | + def __repr__(self): |
| 133 | + return f"view {self.elem} *" |
| 134 | + |
| 135 | + |
| 136 | +SCALARS = {"int": "long", "float": "f64", "bool": "bool"} |
| 137 | +SEQ_ELEMS = {"int": "long", "float": "f64"} |
| 138 | + |
| 139 | + |
| 140 | +def _head(node: ast.expr) -> str: |
| 141 | + if isinstance(node, ast.Name): |
| 142 | + return node.id |
| 143 | + if isinstance(node, ast.Attribute): |
| 144 | + return node.attr |
| 145 | + return type(node).__name__ |
| 146 | + |
| 147 | + |
| 148 | +def om_type(ann: Optional[ast.expr]): |
| 149 | + """Map one Python annotation to Scalar/Seq, or raise Refused.""" |
| 150 | + if ann is None: |
| 151 | + raise Refused("type:untyped", "parameter or return has no annotation") |
| 152 | + text = ast.unparse(ann) |
| 153 | + if isinstance(ann, ast.Constant) and ann.value is None: |
| 154 | + raise Refused("type:None", "no result value to test") |
| 155 | + if isinstance(ann, ast.Name): |
| 156 | + if ann.id in SCALARS: |
| 157 | + return Scalar(SCALARS[ann.id]) |
| 158 | + if ann.id == "str": |
| 159 | + return Seq("uchar", "str") |
| 160 | + raise Refused(f"type:{ann.id}", text) |
| 161 | + if isinstance(ann, ast.Subscript): |
| 162 | + head = _head(ann.value) |
| 163 | + if head in ("List", "list"): |
| 164 | + inner = ann.slice |
| 165 | + if isinstance(inner, ast.Name) and inner.id in SEQ_ELEMS: |
| 166 | + return Seq(SEQ_ELEMS[inner.id], "list") |
| 167 | + if isinstance(inner, ast.Name) and inner.id == "str": |
| 168 | + raise Refused("type:List[str]", "OM-2 has no array-of-strings type") |
| 169 | + if isinstance(inner, ast.Name) and inner.id == "bool": |
| 170 | + raise Refused("type:List[bool]", "omc refuses bool arrays (new bool N, error 9)") |
| 171 | + raise Refused("type:List[compound]", text) |
| 172 | + if head in ("Tuple", "tuple"): |
| 173 | + elts = ann.slice.elts if isinstance(ann.slice, ast.Tuple) else [ann.slice] |
| 174 | + names = [e.id if isinstance(e, ast.Name) else None for e in elts] |
| 175 | + if len(set(names)) == 1 and names[0] in SEQ_ELEMS: |
| 176 | + return Seq(SEQ_ELEMS[names[0]], "tuple", fixed=len(elts)) |
| 177 | + raise Refused("type:Tuple[mixed]", text) |
| 178 | + raise Refused(f"type:{head}", text) |
| 179 | + raise Refused("type:other", text) |
| 180 | + |
| 181 | + |
| 182 | +def _name_ok(name: str, used: set) -> bool: |
| 183 | + return ( |
| 184 | + name not in KEYWORDS |
| 185 | + # The pinned omc looks a word up in its keyword table by its first eight bytes |
| 186 | + # only (omc.om `fn kw` takes one packed ulong), so it reads a longer name such as |
| 187 | + # truncate_number or continue_x as the keyword truncate / continue (error 16). |
| 188 | + and name[:8] not in KEYWORDS |
| 189 | + and name not in HARNESS_NAMES |
| 190 | + and name not in used |
| 191 | + and not HARNESS_NAME_RE.match(name) |
| 192 | + ) |
| 193 | + |
| 194 | + |
| 195 | +def fit_name(py: str, used: set, limit: int) -> str: |
| 196 | + """An Omega name for Python identifier `py`: at most `limit` characters, not a |
| 197 | + keyword (nor starting with an eight-letter one), not a harness name, not used.""" |
| 198 | + base = py[:limit] |
| 199 | + if len(base) > 8 and base[:8] in KEYWORDS: |
| 200 | + base = base[0].upper() + base[1:] |
| 201 | + if _name_ok(base, used): |
| 202 | + return base |
| 203 | + for k in range(1, 100): |
| 204 | + suffix = "_" if k == 1 else f"_{k}" |
| 205 | + cand = base[: limit - len(suffix)] + suffix |
| 206 | + if _name_ok(cand, used): |
| 207 | + return cand |
| 208 | + raise Refused("name:unmappable", py) |
| 209 | + |
| 210 | + |
| 211 | +def f64_literal(v) -> str: |
| 212 | + """Exact round-trip OM-2 float literal (digits.digits[e[-]digits]).""" |
| 213 | + f = float(v) |
| 214 | + if not math.isfinite(f): |
| 215 | + raise Refused("value:non-finite float", repr(v)) |
| 216 | + if isinstance(v, int) and float(f) != v: |
| 217 | + raise Refused("value:int not exact in f64", repr(v)) |
| 218 | + r = repr(f) |
| 219 | + if "e" in r: |
| 220 | + mant, exp = r.split("e") |
| 221 | + if "." not in mant: |
| 222 | + mant += ".0" |
| 223 | + return f"{mant}e{int(exp)}" |
| 224 | + if "." not in r: |
| 225 | + r += ".0" |
| 226 | + return r |
| 227 | + |
| 228 | + |
| 229 | +class OmExpr(str): |
| 230 | + """A rendered expression (for doctests and the seen_tests table) that keeps |
| 231 | + its structure in `.node` for test generation.""" |
| 232 | + |
| 233 | + def __new__(cls, text: str, node): |
| 234 | + s = super().__new__(cls, text) |
| 235 | + s.node = node |
| 236 | + return s |
| 237 | + |
| 238 | + |
| 239 | +def _render(node) -> str: |
| 240 | + kind = node[0] |
| 241 | + if kind == "lit": |
| 242 | + v = node[1] |
| 243 | + if isinstance(v, bool): |
| 244 | + return "true" if v else "false" |
| 245 | + if isinstance(v, float): |
| 246 | + return repr(v) |
| 247 | + if isinstance(v, str): |
| 248 | + return '"' + v.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t") + '"' |
| 249 | + if v is None: |
| 250 | + return "none" |
| 251 | + return str(v) |
| 252 | + if kind == "var": |
| 253 | + return node[1] |
| 254 | + if kind in ("list", "tuple", "set"): |
| 255 | + o, c = {"list": "[]", "tuple": "()", "set": "{}"}[kind] |
| 256 | + return o + ", ".join(_render(e) for e in node[1]) + c |
| 257 | + if kind == "dict": |
| 258 | + return "{" + ", ".join(f"{_render(k)}: {_render(v)}" for k, v in zip(node[1], node[2])) + "}" |
| 259 | + if kind == "call": |
| 260 | + parts = [_render(node[1])] + [_render(a) for a in node[2]] |
| 261 | + return " ".join(parts) |
| 262 | + raise ValueError(node) |
| 263 | + |
| 264 | + |
| 265 | +_TEXT_SAFE = re.compile(rb"[\x20-\x7e\n\t]*\Z") |
| 266 | + |
| 267 | + |
| 268 | +def _text_literal(b: bytes) -> Optional[str]: |
| 269 | + """An OM-2 `text` literal for bytes b, or None when b needs an escape omc lacks.""" |
| 270 | + if not _TEXT_SAFE.match(b): |
| 271 | + return None |
| 272 | + s = b.decode("ascii") |
| 273 | + return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t") + '"' |
| 274 | + |
| 275 | + |
| 276 | +class Translator: |
| 277 | + stop = ["\nfn ", "\nstruct ", "\nglobal ", "\ntext ", "\nconst ", "\nlayout ", "\nabstract "] |
| 278 | + |
| 279 | + def __init__(self): |
| 280 | + self.refusal: Optional[Refused] = None |
| 281 | + self.params = [] # [(py_name, om_name, type)] |
| 282 | + self.ret = None |
| 283 | + self.fn = None |
| 284 | + self.py_fn = None |
| 285 | + self.res = None |
| 286 | + self.cases = [] |
| 287 | + |
| 288 | + def file_ext(self): |
| 289 | + return "om" |
| 290 | + |
| 291 | + def no_completion_prompt_stub(self): |
| 292 | + return "trap 14\nend\n" |
| 293 | + |
| 294 | + # ---- prompt --------------------------------------------------------------- |
| 295 | + |
| 296 | + def translate_prompt(self, name: str, args: List[ast.arg], returns, description: str) -> Optional[str]: |
| 297 | + self.refusal = None |
| 298 | + try: |
| 299 | + return self._prompt(name, args, returns, description) |
| 300 | + except Refused as e: |
| 301 | + self.refusal = e |
| 302 | + return None |
| 303 | + |
| 304 | + def _prompt(self, name, args, returns, description): |
| 305 | + self.py_fn = name |
| 306 | + self.fn = fit_name(name, set(), MAX_FN) |
| 307 | + used = {self.fn} |
| 308 | + self.params = [] |
| 309 | + for a in args: |
| 310 | + t = om_type(a.annotation) |
| 311 | + om = fit_name(a.arg, used, MAX_LOCAL) |
| 312 | + used.add(om) |
| 313 | + self.params.append((a.arg, om, t)) |
| 314 | + self.ret = om_type(returns) |
| 315 | + self.res = None |
| 316 | + if isinstance(self.ret, Seq): |
| 317 | + self.res = "res" # HARNESS_NAMES keeps parameters off this name |
| 318 | + slots = sum(t.slots for _, _, t in self.params) + (2 if self.res else 0) |
| 319 | + if slots > MAX_SLOTS: |
| 320 | + raise Refused("abi:parameter slots", f"{slots} > {MAX_SLOTS}") |
| 321 | + |
| 322 | + lines = ["om2"] |
| 323 | + for line in description.strip().split("\n"): |
| 324 | + lines.append(("note " + line).rstrip()) |
| 325 | + renamed = [(py, om) for py, om, _ in self.params if py != om] |
| 326 | + if self.fn != name: |
| 327 | + renamed.insert(0, (name, self.fn)) |
| 328 | + for py, om in renamed: |
| 329 | + lines.append(f"note Omega name: {py} is {om} here.") |
| 330 | + if self.res: |
| 331 | + what = {"str": "bytes", "list": "elements", "tuple": "elements"}[self.ret.py] |
| 332 | + lines.append( |
| 333 | + f"note Result: write the {what} into res (len res >= {RESULT_CAP}) and return how many were written." |
| 334 | + ) |
| 335 | + sig = [self.fn] |
| 336 | + for _, om, t in self.params: |
| 337 | + sig.append(f"{om} {t.om}" if isinstance(t, Scalar) else f"{om} view {t.elem} *") |
| 338 | + if self.res: |
| 339 | + sig.append(f"res edit {self.ret.elem} *") |
| 340 | + rt = "long" if self.res else self.ret.om |
| 341 | + lines.append("fn " + " ".join(sig) + f" to {rt}") |
| 342 | + return "\n".join(lines) + "\n" |
| 343 | + |
| 344 | + # ---- values --------------------------------------------------------------- |
| 345 | + |
| 346 | + def gen_literal(self, c): |
| 347 | + return ("lit", c) |
| 348 | + |
| 349 | + def gen_var(self, v): |
| 350 | + if v == "candidate" or v == self.py_fn: |
| 351 | + return ("var", self.fn or v) |
| 352 | + return ("var", v) |
| 353 | + |
| 354 | + def gen_list(self, l): |
| 355 | + return ("list", l) |
| 356 | + |
| 357 | + def gen_tuple(self, t): |
| 358 | + return ("tuple", t) |
| 359 | + |
| 360 | + def gen_dict(self, keys, values): |
| 361 | + return ("dict", keys, values) |
| 362 | + |
| 363 | + def gen_set(self, s): |
| 364 | + return ("set", s) |
| 365 | + |
| 366 | + def gen_call(self, func, args): |
| 367 | + return ("call", func, args) |
| 368 | + |
| 369 | + def finalize(self, expr, context): |
| 370 | + return OmExpr(_render(expr), expr) |
| 371 | + |
| 372 | + # ---- tests ---------------------------------------------------------------- |
| 373 | + |
| 374 | + def test_suite_prefix_lines(self, entry_point): |
| 375 | + self.cases = [] |
| 376 | + return [] |
| 377 | + |
| 378 | + def test_suite_suffix_lines(self): |
| 379 | + lines = [f'text mpe_ok "{MPE_OK_LINE}\\n"', "fn main to int"] |
| 380 | + for k in range(len(self.cases)): |
| 381 | + lines += [f"if not tc_{k}", f"ret {k + 1}", "end"] |
| 382 | + lines += ["w = write 1 mpe_ok 0 len mpe_ok", "ret 0", "end"] |
| 383 | + return lines |
| 384 | + |
| 385 | + def _scalar(self, node, t: Scalar, rhs: bool) -> str: |
| 386 | + if node[0] != "lit": |
| 387 | + raise Refused("value:non-literal", _render(node)) |
| 388 | + v = node[1] |
| 389 | + if t.om == "bool": |
| 390 | + if isinstance(v, bool): |
| 391 | + return "true" if v else "false" |
| 392 | + if rhs and isinstance(v, int) and v in (0, 1): |
| 393 | + return "true" if v else "false" |
| 394 | + raise Refused("value:not a bool", repr(v)) |
| 395 | + if t.om == "long": |
| 396 | + if isinstance(v, bool): |
| 397 | + return "1" if v else "0" |
| 398 | + if isinstance(v, float) and v.is_integer(): |
| 399 | + v = int(v) |
| 400 | + if not isinstance(v, int): |
| 401 | + raise Refused("value:not an int", repr(v)) |
| 402 | + if not I64_MIN <= v <= I64_MAX: |
| 403 | + raise Refused("value:int outside i64", repr(v)) |
| 404 | + return str(v) |
| 405 | + if isinstance(v, bool) or not isinstance(v, (int, float)): |
| 406 | + raise Refused("value:not a float", repr(v)) |
| 407 | + return f64_literal(v) |
| 408 | + |
| 409 | + def _elements(self, node, t: Seq, rhs: bool) -> List[str]: |
| 410 | + if t.py == "str": |
| 411 | + if node[0] != "lit" or not isinstance(node[1], str): |
| 412 | + raise Refused("value:not a str", _render(node)) |
| 413 | + if not node[1].isascii(): |
| 414 | + raise Refused("value:non-ASCII string", "Omega strings are bytes, Python str is code points") |
| 415 | + return [str(b) for b in node[1].encode("ascii")] |
| 416 | + if node[0] not in ("list", "tuple"): |
| 417 | + raise Refused("value:not a sequence", _render(node)) |
| 418 | + if t.fixed is not None and len(node[1]) != t.fixed: |
| 419 | + raise Refused("value:tuple arity", _render(node)) |
| 420 | + return [self._scalar(e, Scalar(t.elem), rhs) for e in node[1]] |
| 421 | + |
| 422 | + def deep_equality(self, left, right): |
| 423 | + try: |
| 424 | + return self._case(left.node, right.node) |
| 425 | + except Refused as e: |
| 426 | + self.refusal = e |
| 427 | + raise |
| 428 | + |
| 429 | + def _case(self, call, expect): |
| 430 | + if call[0] != "call" or call[1] != ("var", self.fn): |
| 431 | + raise Refused("tests:not a direct candidate call", _render(call)) |
| 432 | + if len(call[2]) != len(self.params): |
| 433 | + raise Refused("tests:arity", _render(call)) |
| 434 | + k = len(self.cases) |
| 435 | + if k >= MAX_CASES: |
| 436 | + raise Refused("tests:too many cases", f"> {MAX_CASES}") |
| 437 | + texts, body, argv = [], [], [] |
| 438 | + for j, (node, (_, _, t)) in enumerate(zip(call[2], self.params)): |
| 439 | + if isinstance(t, Scalar): |
| 440 | + argv.append(self._scalar(node, t, rhs=False)) |
| 441 | + continue |
| 442 | + elems = self._elements(node, t, rhs=False) |
| 443 | + # An empty string goes through `part a 0 0`, never `text t ""`: the pinned omc |
| 444 | + # takes a zero-length name as an unsized parameter (omc.om arrarg, nm_len 0) |
| 445 | + # and passes a stale register as the count, so `len` is garbage in the callee. |
| 446 | + if t.py == "str" and elems: |
| 447 | + lit = _text_literal(node[1].encode("ascii")) |
| 448 | + if lit is not None: |
| 449 | + texts.append(f"text t{k}_{j} {lit}") |
| 450 | + argv.append(f"t{k}_{j}") |
| 451 | + continue |
| 452 | + zero = "0.0" if t.elem == "f64" else "0" |
| 453 | + body.append(f"a{j} = new {t.elem} {max(1, len(elems))} {zero}") |
| 454 | + body += [f"put a{j} {i} {v}" for i, v in enumerate(elems)] |
| 455 | + argv.append(f"a{j}" if elems else f"part a{j} 0 0") |
| 456 | + if self.res: |
| 457 | + zero = "0.0" if self.ret.elem == "f64" else "0" |
| 458 | + exp = self._elements(expect, self.ret, rhs=True) |
| 459 | + body.append(f"res = new {self.ret.elem} {max(RESULT_CAP, len(exp))} {zero}") |
| 460 | + argv.append("res") |
| 461 | + body.append(f"r = {self.fn} {' '.join(argv)}".rstrip()) |
| 462 | + body += [f"if ne r {len(exp)}", "ret false", "end"] |
| 463 | + for i, v in enumerate(exp): |
| 464 | + body += [f"if ne get res {i} {v}", "ret false", "end"] |
| 465 | + body.append("ret true") |
| 466 | + else: |
| 467 | + exp = self._scalar(expect, self.ret, rhs=True) |
| 468 | + body.append(f"r = {self.fn} {' '.join(argv)}".rstrip()) |
| 469 | + body.append(f"ret eq r {exp}") |
| 470 | + self.cases.append(k) |
| 471 | + return "\n".join(texts + [f"fn tc_{k} to bool"] + body + ["end"]) |
| 472 | diff --git a/dataset_builder/terms.csv b/dataset_builder/terms.csv |
| 473 | index 8b089d4..741f870 100644 |
| 474 | --- a/dataset_builder/terms.csv |
| 475 | +++ b/dataset_builder/terms.csv |
| 476 | @@ -26,3 +26,4 @@ Matlab,m,array,array,array,dictionary,<missing>,true,false |
| 477 | Haskell,hs,list,list,tuple,association list,Nothing,True,False |
| 478 | Clojure,clj,vector,list,vector,map,nil,true,false |
| 479 | Dart,dart,list,list,record,map,null,true,false |
| 480 | +Omega,om,array,array,array,dictionary,none,true,false |
| 481 | diff --git a/evaluation/src/containerized_eval.py b/evaluation/src/containerized_eval.py |
| 482 | index 533fb68..1401c2a 100644 |
| 483 | --- a/evaluation/src/containerized_eval.py |
| 484 | +++ b/evaluation/src/containerized_eval.py |
| 485 | @@ -29,6 +29,7 @@ import eval_clj |
| 486 | import eval_v |
| 487 | import eval_lean |
| 488 | import eval_dart |
| 489 | +import eval_om |
| 490 | import tempfile |
| 491 | |
| 492 | |
| 493 | @@ -65,6 +66,7 @@ EVALUATORS = { |
| 494 | "coq": (eval_v.eval_script, ".v"), |
| 495 | "lean": (eval_lean.eval_script, ".lean"), |
| 496 | "dart": (eval_dart.eval_script, ".dart"), |
| 497 | + "om": (eval_om.eval_script, ".om"), |
| 498 | } |
| 499 | |
| 500 | def eval_string_script(language, program): |
| 501 | diff --git a/evaluation/src/eval_om.py b/evaluation/src/eval_om.py |
| 502 | new file mode 100755 |
| 503 | index 0000000..0645893 |
| 504 | --- /dev/null |
| 505 | +++ b/evaluation/src/eval_om.py |
| 506 | @@ -0,0 +1,143 @@ |
| 507 | +#!/usr/bin/env python3 |
| 508 | +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 509 | +"""MultiPL-E evaluator for Omega programs written by humaneval_to_om.py. |
| 510 | + |
| 511 | +Foreign-harness adapter: MultiPL-E calls ``eval_script(path)`` from |
| 512 | +``evaluation/src/eval_<ext>.py``, so this file is Python. It is not first-party |
| 513 | +Omega and is not part of any Omega product path. Pure standard library. |
| 514 | + |
| 515 | + OMEGA_OMC=/path/to/omc eval_om.py PROGRAM.om [...] # one JSON result per line |
| 516 | + |
| 517 | +Compile protocol (pinned omc): ``omc < p.om > p 2> p.err``. Only when omc exits |
| 518 | +0 with nothing on stderr is ``p`` made executable and run. The omc file must hash |
| 519 | +to OMEGA_OMC_SHA256 (default: the omega-rosetta pin); a mismatch raises before |
| 520 | +anything is compiled, so no result is ever recorded against an unpinned compiler. |
| 521 | + |
| 522 | +Outcome -> MultiPL-E ``status`` (``om_status``, ``om_case``): |
| 523 | + |
| 524 | + omc nonzero / stderr SyntaxError compile_error omc error code |
| 525 | + exit 0 + pass line OK pass - |
| 526 | + exit 0 without pass line Exception no_pass_line - |
| 527 | + exit 1..98 Exception wrong_answer failing test case (exit - 1) |
| 528 | + exit 100..199 Exception trap trap code (exit - 100) |
| 529 | + other exit / signal Exception exit_other exit code |
| 530 | + over the time limit Timeout timeout - |
| 531 | + |
| 532 | +MultiPL-E's containerized_eval keeps only status/exit_code/stdout/stderr; the |
| 533 | +om_* fields are derivable from exit_code by the table above. |
| 534 | +""" |
| 535 | + |
| 536 | +import hashlib |
| 537 | +import json |
| 538 | +import os |
| 539 | +import re |
| 540 | +import shlex |
| 541 | +import signal |
| 542 | +import subprocess |
| 543 | +import sys |
| 544 | +import tempfile |
| 545 | +from pathlib import Path |
| 546 | + |
| 547 | +# Pin of aien-dev/omega-rosetta omega.ref (omega-mv e5b32567a7aff3ce594e3254a622a846a6cd190b). |
| 548 | +PINNED_OMC_SHA256 = "2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f" |
| 549 | +# Must equal humaneval_to_om.MPE_OK_LINE: the line main writes after the last case holds. |
| 550 | +MPE_OK_LINE = "MultiPL-E Omega: all tests passed" |
| 551 | +COMPILE_TIMEOUT = 30 |
| 552 | +MAX_OUTPUT = 2048 |
| 553 | +_ERROR_RE = re.compile(r"omc: line (\d+): error (\d+)") |
| 554 | +_checked = {} |
| 555 | + |
| 556 | + |
| 557 | +def omc_path(omc=None) -> str: |
| 558 | + omc = omc or os.environ.get("OMEGA_OMC") |
| 559 | + if not omc: |
| 560 | + raise RuntimeError("eval_om: set OMEGA_OMC to the pinned omc binary") |
| 561 | + return omc |
| 562 | + |
| 563 | + |
| 564 | +def check_pin(omc: str) -> None: |
| 565 | + """Raise unless the omc file hashes to the pin. Cached by (path, size, mtime).""" |
| 566 | + st = os.stat(omc) |
| 567 | + key = (os.path.realpath(omc), st.st_size, st.st_mtime_ns) |
| 568 | + want = os.environ.get("OMEGA_OMC_SHA256", PINNED_OMC_SHA256) |
| 569 | + if _checked.get(key) == want: |
| 570 | + return |
| 571 | + h = hashlib.sha256() |
| 572 | + with open(omc, "rb") as f: |
| 573 | + for chunk in iter(lambda: f.read(1 << 20), b""): |
| 574 | + h.update(chunk) |
| 575 | + got = h.hexdigest() |
| 576 | + if got != want: |
| 577 | + raise RuntimeError(f"eval_om: {omc} has sha256 {got}, pin is {want}; refusing to evaluate") |
| 578 | + _checked[key] = want |
| 579 | + |
| 580 | + |
| 581 | +def _wrap() -> list: |
| 582 | + """Optional command prefix for omc and the program, e.g. 'nice -n 19 taskset -c 10-14'.""" |
| 583 | + return shlex.split(os.environ.get("OMEGA_EVAL_WRAP", "")) |
| 584 | + |
| 585 | + |
| 586 | +def _run(argv, timeout, stdin=None, stdout=subprocess.PIPE): |
| 587 | + """Run argv in its own process group; kill the group on timeout. |
| 588 | + Returns (exit_code or None on timeout, stdout bytes, stderr bytes).""" |
| 589 | + p = subprocess.Popen( |
| 590 | + argv, stdin=stdin or subprocess.DEVNULL, stdout=stdout, stderr=subprocess.PIPE, start_new_session=True |
| 591 | + ) |
| 592 | + try: |
| 593 | + out, err = p.communicate(timeout=timeout) |
| 594 | + return p.returncode, out or b"", err or b"" |
| 595 | + except subprocess.TimeoutExpired: |
| 596 | + os.killpg(p.pid, signal.SIGKILL) |
| 597 | + out, err = p.communicate() |
| 598 | + return None, out or b"", err or b"" |
| 599 | + |
| 600 | + |
| 601 | +def _text(b: bytes) -> str: |
| 602 | + return b[:MAX_OUTPUT].decode("utf-8", errors="replace") |
| 603 | + |
| 604 | + |
| 605 | +def eval_script(path: Path, omc=None, timeout=None) -> dict: |
| 606 | + omc = omc_path(omc) |
| 607 | + check_pin(omc) |
| 608 | + if timeout is None: |
| 609 | + timeout = float(os.environ.get("OMEGA_EVAL_TIMEOUT", "15")) |
| 610 | + with tempfile.TemporaryDirectory(prefix="eval_om.") as d: |
| 611 | + exe = os.path.join(d, "p") |
| 612 | + with open(path, "rb") as src, open(exe, "wb") as dst: |
| 613 | + rc, _, err = _run(_wrap() + [omc], COMPILE_TIMEOUT, stdin=src, stdout=dst) |
| 614 | + if rc is None: |
| 615 | + return {"status": "Timeout", "exit_code": -1, "stdout": "", "stderr": "omc timeout", |
| 616 | + "om_status": "timeout", "om_case": None} |
| 617 | + if rc != 0 or err: |
| 618 | + m = _ERROR_RE.search(err.decode("utf-8", errors="replace")) |
| 619 | + return {"status": "SyntaxError", "exit_code": rc, "stdout": "", "stderr": _text(err), |
| 620 | + "om_status": "compile_error", "om_case": int(m.group(2)) if m else None} |
| 621 | + os.chmod(exe, 0o700) |
| 622 | + rc, out, err = _run(_wrap() + [exe], timeout) |
| 623 | + result = {"exit_code": rc if rc is not None else -1, "stdout": _text(out), "stderr": _text(err)} |
| 624 | + if rc is None: |
| 625 | + result.update(status="Timeout", om_status="timeout", om_case=None) |
| 626 | + elif rc == 0 and out.endswith((MPE_OK_LINE + "\n").encode()): |
| 627 | + result.update(status="OK", om_status="pass", om_case=None) |
| 628 | + elif rc == 0: |
| 629 | + result.update(status="Exception", om_status="no_pass_line", om_case=None) |
| 630 | + elif 1 <= rc <= 98: |
| 631 | + result.update(status="Exception", om_status="wrong_answer", om_case=rc - 1) |
| 632 | + elif 100 <= rc <= 199: |
| 633 | + result.update(status="Exception", om_status="trap", om_case=rc - 100) |
| 634 | + else: |
| 635 | + result.update(status="Exception", om_status="exit_other", om_case=rc) |
| 636 | + return result |
| 637 | + |
| 638 | + |
| 639 | +def main(argv): |
| 640 | + if not argv or argv[0] in ("-h", "--help"): |
| 641 | + print(__doc__) |
| 642 | + return 0 if argv else 2 |
| 643 | + for p in argv: |
| 644 | + print(json.dumps({"path": p, **eval_script(Path(p))})) |
| 645 | + return 0 |
| 646 | + |
| 647 | + |
| 648 | +if __name__ == "__main__": |
| 649 | + sys.exit(main(sys.argv[1:])) |
| 650 | diff --git a/evaluation/test_inputs/om-hand-0.0-keep-HumanEval53.json b/evaluation/test_inputs/om-hand-0.0-keep-HumanEval53.json |
| 651 | new file mode 100644 |
| 652 | index 0000000..1e3d77f |
| 653 | --- /dev/null |
| 654 | +++ b/evaluation/test_inputs/om-hand-0.0-keep-HumanEval53.json |
| 655 | @@ -0,0 +1,19 @@ |
| 656 | +{ |
| 657 | + "name": "HumanEval_53_add", |
| 658 | + "language": "om", |
| 659 | + "prompt": "om2\nnote Add two numbers x and y\nnote >>> add_ 2 3\nnote 5\nnote >>> add_ 5 7\nnote 12\nnote Omega name: add is add_ here.\nfn add_ x long y long to long\n", |
| 660 | + "tests": "fn tc_0 to bool\nr = add_ 0 1\nret eq r 1\nend\nfn tc_1 to bool\nr = add_ 1 0\nret eq r 1\nend\nfn tc_2 to bool\nr = add_ 2 3\nret eq r 5\nend\nfn tc_3 to bool\nr = add_ 5 7\nret eq r 12\nend\nfn tc_4 to bool\nr = add_ 7 5\nret eq r 12\nend\ntext mpe_ok \"MultiPL-E Omega: all tests passed\\n\"\nfn main to int\nif not tc_0\nret 1\nend\nif not tc_1\nret 2\nend\nif not tc_2\nret 3\nend\nif not tc_3\nret 4\nend\nif not tc_4\nret 5\nend\nw = write 1 mpe_ok 0 len mpe_ok\nret 0\nend", |
| 661 | + "completions": [ |
| 662 | + "ret add x y\nend\n", |
| 663 | + "ret add x\nend\n" |
| 664 | + ], |
| 665 | + "stop_tokens": [ |
| 666 | + "\nfn ", |
| 667 | + "\nstruct ", |
| 668 | + "\nglobal ", |
| 669 | + "\ntext ", |
| 670 | + "\nconst ", |
| 671 | + "\nlayout ", |
| 672 | + "\nabstract " |
| 673 | + ] |
| 674 | +} |
| 675 | -- |
| 676 | 2.43.0 |
| 677 |