|
| 1 | +# This script translates problems from the OpenAI HumanEval dataset into Elm. |
| 2 | +import re |
| 3 | +import ast |
| 4 | +from typing import List |
| 5 | + |
| 6 | + |
| 7 | +class Translator: |
| 8 | + |
| 9 | + stop = ["\n\n", "\n--", "\ntype", "\nmodule"] |
| 10 | + |
| 11 | + def __init__(self): |
| 12 | + self.type = None |
| 13 | + |
| 14 | + def translate_identifier(self, name: str) -> str: |
| 15 | + parts = name.lower().split("_") |
| 16 | + return parts[0] + "".join(p.capitalize() for p in parts[1:]) |
| 17 | + |
| 18 | + def file_ext(self): |
| 19 | + return "elm" |
| 20 | + |
| 21 | + def translate_type(self, t): |
| 22 | + match t: |
| 23 | + case ast.Subscript(ast.Name(id), slice, _ctx): |
| 24 | + match id: |
| 25 | + case "List": |
| 26 | + inner = self.translate_type(slice) |
| 27 | + return f"List {inner}" if " " not in inner else f"List ({inner})" |
| 28 | + case "Tuple": |
| 29 | + match slice: |
| 30 | + case ast.Tuple(elts, _ctx): |
| 31 | + tys = [self.translate_type(e) for e in elts] |
| 32 | + return "(" + ", ".join(tys) + ")" |
| 33 | + case _other: |
| 34 | + raise Exception(f"Bad tuple: {slice}") |
| 35 | + case "Dict": |
| 36 | + match slice: |
| 37 | + case ast.Tuple([k, v], _ctx): |
| 38 | + kt = self.translate_type(k) |
| 39 | + vt = self.translate_type(v) |
| 40 | + return f"Dict.Dict {kt} {vt}" |
| 41 | + case _other: |
| 42 | + raise Exception(f"Bad dict: {slice}") |
| 43 | + case "Optional": |
| 44 | + inner = self.translate_type(slice) |
| 45 | + return f"Maybe {inner}" if " " not in inner else f"Maybe ({inner})" |
| 46 | + case "Union": |
| 47 | + raise Exception("Union is not supported") |
| 48 | + case other: |
| 49 | + raise Exception(f"Bad generic {other}") |
| 50 | + case ast.Name("int") | "int": |
| 51 | + return "Int" |
| 52 | + case ast.Name("float") | "float": |
| 53 | + return "Float" |
| 54 | + case ast.Name("bool"): |
| 55 | + return "Bool" |
| 56 | + case ast.Name("str") | "str": |
| 57 | + return "String" |
| 58 | + case None: |
| 59 | + raise Exception("implicitly untyped argument") |
| 60 | + case ast.Name("Any"): |
| 61 | + raise Exception("Any is not supported") |
| 62 | + case ast.Name(x): |
| 63 | + raise Exception(f"unknown name {x}") |
| 64 | + case ast.Constant(Ellipsis): |
| 65 | + raise Exception("no ellipsis") |
| 66 | + case _other: |
| 67 | + raise Exception(f"unknown annotation: {t}") |
| 68 | + |
| 69 | + def translate_prompt(self, name: str, args: List[ast.arg], returns, description: str): |
| 70 | + self.type = [[arg.annotation for arg in args], returns] |
| 71 | + elm_name = self.translate_identifier(name) |
| 72 | + comment = "-- " + re.sub(r"\n(\s*)", "\n-- ", description.strip()) + "\n" |
| 73 | + try: |
| 74 | + arg_types = [self.translate_type(arg.annotation) for arg in args] |
| 75 | + ret_type = self.translate_type(returns) |
| 76 | + except Exception as e: |
| 77 | + print(e) |
| 78 | + return None |
| 79 | + type_parts = arg_types + [ret_type] |
| 80 | + type_sig = elm_name + " : " + " -> ".join(type_parts) |
| 81 | + arg_names = [arg.arg for arg in args] |
| 82 | + func_decl = elm_name + " " + " ".join(arg_names) + " =" |
| 83 | + imports = "import Platform\n" |
| 84 | + all_types = " ".join(type_parts) |
| 85 | + if "Dict.Dict" in all_types: |
| 86 | + imports += "import Dict\n" |
| 87 | + return f"module Main exposing (..)\n\n{imports}\n{comment}{type_sig}\n{func_decl}\n" |
| 88 | + |
| 89 | + def test_suite_prefix_lines(self, entry_point) -> List[str]: |
| 90 | + return [ |
| 91 | + "", |
| 92 | + "assert : Bool -> ()", |
| 93 | + "assert b = if b then () else Debug.todo \"assertion failed\"", |
| 94 | + "", |
| 95 | + "main : Program () () ()", |
| 96 | + "main =", |
| 97 | + " Platform.worker", |
| 98 | + " { init = \\_ ->", |
| 99 | + f" let", |
| 100 | + f" candidate = {self.translate_identifier(entry_point)}", |
| 101 | + ] |
| 102 | + |
| 103 | + def test_suite_suffix_lines(self) -> List[str]: |
| 104 | + return [ |
| 105 | + " in", |
| 106 | + " ((), Cmd.none)", |
| 107 | + " , update = \\_ _ -> ((), Cmd.none)", |
| 108 | + " , subscriptions = \\_ -> Sub.none", |
| 109 | + " }", |
| 110 | + ] |
| 111 | + |
| 112 | + def deep_equality(self, left: str, right: str) -> str: |
| 113 | + return f" _ = assert ({left} == {right})" |
| 114 | + |
| 115 | + def gen_literal(self, c: bool | str | int | float | None): |
| 116 | + if type(c) == bool: |
| 117 | + return str(c) |
| 118 | + if type(c) == str: |
| 119 | + escaped = c.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") |
| 120 | + return f'"{escaped}"' |
| 121 | + if c is None: |
| 122 | + return "Nothing" |
| 123 | + if type(c) == int: |
| 124 | + if c < 0: |
| 125 | + return f"({repr(c)})" |
| 126 | + return repr(c) |
| 127 | + if type(c) == float: |
| 128 | + return repr(c) |
| 129 | + return repr(c) |
| 130 | + |
| 131 | + def gen_var(self, v: str): |
| 132 | + return self.translate_identifier(v) |
| 133 | + |
| 134 | + def gen_list(self, l: List[str]): |
| 135 | + return "[" + ", ".join(l) + "]" |
| 136 | + |
| 137 | + def gen_tuple(self, t: List[str]): |
| 138 | + return "(" + ", ".join(t) + ")" |
| 139 | + |
| 140 | + def gen_dict(self, keys: List[str], values: List[str]): |
| 141 | + pairs = ", ".join(f"({k}, {v})" for k, v in zip(keys, values)) |
| 142 | + return f"Dict.fromList [{pairs}]" |
| 143 | + |
| 144 | + def gen_call(self, func: str, args: List[str]): |
| 145 | + if func == "candidate": |
| 146 | + args = [self._coerce(arg, self.type[0][i]) for i, arg in enumerate(args)] |
| 147 | + return "(" + func + " " + " ".join(args) + ")" |
| 148 | + |
| 149 | + def _coerce(self, expr: str, ann) -> str: |
| 150 | + match expr, ann: |
| 151 | + case expr, ast.Subscript(ast.Name("Optional"), _): |
| 152 | + if expr == "Nothing": |
| 153 | + return expr |
| 154 | + return f"(Just {expr})" |
| 155 | + case expr, ast.Name("float") | "float" if "." not in expr and expr not in ("Nothing",): |
| 156 | + return f"(toFloat {expr})" |
| 157 | + case _: |
| 158 | + return expr |
| 159 | + |
| 160 | + def finalize(self, result, context) -> str: |
| 161 | + match context: |
| 162 | + case "lhs": |
| 163 | + return result |
| 164 | + case "rhs": |
| 165 | + return self._coerce(result, self.type[1]) |
| 166 | + case _other: |
| 167 | + raise Exception("bad context to finalize") |
0 commit comments