muapitolibmupy.py 9.21 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1 2 3 4 5 6 7 8 9 10 11 12 13
"""
Inject things in muapi.h to ../pythonbinding/libmu.py

USAGE: python3 muapitolibmupy.py
"""

import sys
import os, os.path
import re
import tempfile
from typing import Tuple

import muapiparser
14
from refimpl2injectablefiles import injectable_files, muapi_h_path
Kunshan Wang's avatar
Kunshan Wang committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

# C types to ctypes types

_primitive_types = {
        "void"      : "None",
        "int"       : "ctypes.c_int",
        "long"      : "ctypes.c_long",
        "int8_t"    : "ctypes.c_int8",
        "uint8_t"   : "ctypes.c_uint8",
        "int16_t"   : "ctypes.c_int16",
        "uint16_t"  : "ctypes.c_uint16",
        "int32_t"   : "ctypes.c_int32",
        "uint32_t"  : "ctypes.c_uint32",
        "int64_t"   : "ctypes.c_int64",
        "uint64_t"  : "ctypes.c_uint64",
        "intptr_t"  : "ctypes.c_int64",
        "uintptr_t" : "ctypes.c_uint64",
        "float"     : "ctypes.c_float",
        "double"    : "ctypes.c_double",
        "char*"     : "ctypes.c_char_p",
        "void*"     : "ctypes.c_void_p",
        }

def type_is_explicit_ptr(ty):
    return ty.endswith("*")

Kunshan Wang's avatar
Kunshan Wang committed
41
r_handle_ty = re.compile(r'^Mu\w*Value$')
Kunshan Wang's avatar
Kunshan Wang committed
42 43 44 45

def type_is_handle(ty):
    return r_handle_ty.match(ty) is not None

Kunshan Wang's avatar
Kunshan Wang committed
46 47 48 49 50
r_node_ty = re.compile(r'^Mu\w*(Node|Clause)$')

def type_is_node(ty):
    return r_node_ty.match(ty) is not None

Kunshan Wang's avatar
Kunshan Wang committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
def type_is_ptr(ty):
    return type_is_explicit_ptr(ty) or type_is_handle(ty)

def type_is_handle_array(ty):
    return type_is_ptr(ty) and type_is_handle(ty[:-1])

def to_basic_type(typedefs, name):
    while name in typedefs:
        name = typedefs[name]
    return name

_manually_defined_types = [
        "MuCFP",
        "MuValuesFreer",
        "MuTrapHandler",
        ]

def generate_ctypes(ast):
    typedefs = ast["typedefs_order"]

    lines = []

    for f, t in typedefs:
        if f in _manually_defined_types:
            continue
        elif t in _primitive_types:
            nex = _primitive_types[t]
        else:
            nex = "C" + t
        fro = "C" + f
        lines.append("{} = {}".format(fro, nex))

    return "\n".join(lines)

_enums = [
        ("MuTrapHandlerResult", 'MU_'),
Kunshan Wang's avatar
Kunshan Wang committed
87
        #("MuDestKind",          'MU_DEST_'),   # removed
Kunshan Wang's avatar
Kunshan Wang committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        ("MuBinOptr",           'MU_BINOP_'),
        ("MuCmpOptr",           'MU_CMP_'),
        ("MuConvOptr",          'MU_CONV_'),
        ("MuMemOrd",            'MU_ORD_'),
        ("MuAtomicRMWOptr",     'MU_ARMW_'),
        ("MuCallConv",          'MU_CC_'),
        #("MuCommInst",          'MU_CI_'), # Generate a dictionary instead.
        ]

def generate_cenums(ast):
    enums_map = {e["name"]:e["defs"] for e in ast["enums"]}

    lines = []

    for ty, prefix in _enums:
        defs = enums_map[ty]

        lines.append("class {}:".format(ty))
        for d in defs:
            dn, dv = d["name"], d["value"]
            assert dn.startswith(prefix)
            pn = dn[len(prefix):]
            lines.append("    {} = {}".format(pn, dv))

        lines.append("")

    comminst_defs = enums_map["MuCommInst"]
    lines.append("common_instruction_opcodes = {")
    for d in comminst_defs:
Kunshan Wang's avatar
Kunshan Wang committed
117
        muname, dv = d["muname"], d["value"]
Kunshan Wang's avatar
Kunshan Wang committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
        lines.append("    '{}': {},".format(muname, dv))
    lines.append("}")
    
    return "\n".join(lines)

def c_is_subtype_of(typedefs, lhs, rhs):
    cur = lhs

    while cur != rhs:
        if cur not in typedefs:
            return False
        cur = typedefs[cur]

    return True


def generate_muvalues(ast):
    typedefs = ast["typedefs"]
    typedefs_order = ast["typedefs_order"]

    mu_value_derived = [k for k,v in typedefs_order
            if k != "MuValue" and c_is_subtype_of(typedefs, k, "MuValue")]
    abstract_mu_value = {t for t in mu_value_derived if not any(
        u for u in mu_value_derived if u != t and c_is_subtype_of(typedefs, u, t))}

    namesz = max(len(t) for t in mu_value_derived)

    lines = []

    for t in mu_value_derived:
        sup = typedefs[t]
        body = "pass" if t not in abstract_mu_value else "_ctypes_ = C{}".format(t)
        lines.append('class {} ({}): {}'.format( t.ljust(namesz), sup.ljust(namesz), body))

    return "\n".join(lines)

_special_convertions = {
        "MuBool": "bool",
        }

_defined_in_python = {k for k,v in _enums} | {
        "MuCFP",
        } 

_mu_structs = {
        "MuVM*": "MuVM",
        "MuCtx*": "MuCtx",
Kunshan Wang's avatar
Kunshan Wang committed
165
        "MuIRBuilder*": "MuIRBuilder",
Kunshan Wang's avatar
Kunshan Wang committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        }

def to_python_ty(cty):
    if cty is None:
        return None
    elif cty in _primitive_types:
        return _primitive_types[cty]
    elif cty in _special_convertions:
        return _special_convertions[cty]
    elif cty in _mu_structs:
        return _mu_structs[cty]
    elif type_is_handle(cty):
        return cty
    elif type_is_ptr(cty):
        return "ctypes.c_void_p"
    else:
        pty = "C" + cty
        # print("{} probably converts to {}".format(cty, pty))
        return pty

# These methods are not very pythonic. Append _ after their names.
_method_blacklist = {
        "MuVM": {
            "set_trap_handler",
            },
        "MuCtx": {
            "load_bundle",
            "load_hail",
            "handle_from_sint8",
            "handle_from_uint8",
            "handle_from_sint16",
            "handle_from_uint16",
            "handle_from_sint32",
            "handle_from_uint32",
            "handle_from_sint64",
            "handle_from_uint64",
            "handle_from_uint64s",
            "handle_to_sint8",
            "handle_to_uint8",
            "handle_to_sint16",
            "handle_to_uint16",
            "handle_to_sint32",
            "handle_to_uint32",
            "handle_to_sint64",
            "handle_to_uint64",
            "insert_element",
            "load",
            "store",
            "cmpxchg",
            "atomicrmw",
            "fence",
            "new_thread_nor",
            "new_thread_exc",
            "dump_keepalives",
            },
Kunshan Wang's avatar
Kunshan Wang committed
221 222 223
        "MuIRBuilder": {
            "gen_sym",
            },
Kunshan Wang's avatar
Kunshan Wang committed
224 225
        }

Kunshan Wang's avatar
Kunshan Wang committed
226 227 228
def need_array_wrapper(params):
    return any("array_sz_param" in param for param in params)

Kunshan Wang's avatar
Kunshan Wang committed
229 230 231 232 233 234 235 236 237 238
def generate_method(typedefs, strname, meth) -> Tuple[str, str]:
    name    = meth['name']
    params  = meth['params'][1:]
    ret_ty  = meth['ret_ty']

    param_tys = [p["type"] for p in params]

    py_param_tys = [to_python_ty(t) for t in param_tys]
    py_ret_ty    = to_python_ty(ret_ty)

Kunshan Wang's avatar
Kunshan Wang committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    naw = need_array_wrapper(params)

    if name in _method_blacklist[strname] or naw:
        stub_name = name + "_"
    else:
        stub_name = name

    stub = """('{}', {}, [{}]),""".format(
            stub_name, py_ret_ty, ", ".join(py_param_tys))

    if naw:
        formals = [p for p in params if not p.get("is_sz_param", False)]
        formal_names = [p["name"] for p in formals]
        actual_names = [p["name"] for p in params]

        asgns = []
        for f in formals:
            fn = f["name"]
            fcty = f["type"]
            ary_ind = f.get("array_sz_param", None)
            is_optional = f.get("is_optional", False)
            if ary_ind != None:
                assert(fcty.endswith("*"))
                fcty_elem = fcty[:-1]
                asgns.append("_actual_{}_ty = C{} * len({})".format(fn, 
                    fcty_elem, fn))
                asgns.append("_actual_{} = _actual_{}_ty()".format(fn, fn))
                asgns.append("for _i,_v in enumerate({}):".format(fn))
                if type_is_handle(fcty):
                    asgns.append("    _actual_{}[_i] = _v.c_mu_value".format(fn))
                else:
                    asgns.append("    _actual_{}[_i] = _v".format(fn))
                asgns.append("_actual_{} = len({})".format(ary_ind, fn))
            elif is_optional and (type_is_node(fcty) or fcty == "MuID"):
                asgns.append("_actual_{} = 0 if {} is None else {}".format(fn, fn, fn))
            else:
                asgns.append("_actual_{} = {}".format(fn, fn))
        wrapper = """\
    def {}(self, {}):
{}
        return self.{}({})
""".format(name, ", ".join(formal_names), "\n".join(" "*8+ln for ln in asgns),
        stub_name, ", ".join("_actual_"+n for n in actual_names))
    else:
        wrapper = None
Kunshan Wang's avatar
Kunshan Wang committed
284

Kunshan Wang's avatar
Kunshan Wang committed
285
    return stub, wrapper
Kunshan Wang's avatar
Kunshan Wang committed
286 287 288 289 290 291 292

def generate_stubs_for_struct(ast, name) -> str:
    st      = [s for s in ast["structs"] if s["name"] == name][0]
    methods = st["methods"]

    typedefs = ast["typedefs"]

Kunshan Wang's avatar
Kunshan Wang committed
293 294
    stubs = []
    wrappers = []
Kunshan Wang's avatar
Kunshan Wang committed
295 296

    for meth in methods:
Kunshan Wang's avatar
Kunshan Wang committed
297 298 299 300
        stub, wrapper = generate_method(typedefs, name, meth)
        stubs.append(stub)
        if wrapper is not None:
            wrappers.append(wrapper)
Kunshan Wang's avatar
Kunshan Wang committed
301

Kunshan Wang's avatar
Kunshan Wang committed
302
    return "\n".join(stubs), "\n".join(wrappers)
Kunshan Wang's avatar
Kunshan Wang committed
303 304

def main():
305
    with open(muapi_h_path) as f:
Kunshan Wang's avatar
Kunshan Wang committed
306 307 308 309 310 311 312
        src_text = f.read()

    ast = muapiparser.parse_muapi(src_text)

    c_types = generate_ctypes(ast)
    c_enums = generate_cenums(ast)
    muvalues = generate_muvalues(ast)
Kunshan Wang's avatar
Kunshan Wang committed
313 314 315
    muvm_stubs, _ = generate_stubs_for_struct(ast, "MuVM")
    muctx_stubs, _ = generate_stubs_for_struct(ast, "MuCtx")
    muirbuilder_stubs, muirbuilder_wrappers = generate_stubs_for_struct(ast, "MuIRBuilder")
Kunshan Wang's avatar
Kunshan Wang committed
316

317 318 319 320 321 322
    injectable_files["libmu.py"].inject_many({
        "CTYPES":  c_types,
        "CENUMS":  c_enums,
        "MUVALUE": muvalues,
        "MuVM":    muvm_stubs,
        "MuCtx":   muctx_stubs,
Kunshan Wang's avatar
Kunshan Wang committed
323 324
        "MuIRBuilder":   muirbuilder_stubs,
        "wrp_MuIRBuilder": muirbuilder_wrappers,
325
        })
Kunshan Wang's avatar
Kunshan Wang committed
326

Kunshan Wang's avatar
Kunshan Wang committed
327 328
if __name__=='__main__':
    main()