hpyproject / hpy

HPy: a better API for Python
https://hpyproject.org
MIT License
1.02k stars 52 forks source link

Add HPy<type>_Check for all fast equivalent type checks in CPython. #386

Open fangerer opened 1 year ago

fangerer commented 1 year ago

There are some very fast Py<type>_Check functions in CPython that just do masking on the type flags (see https://github.com/python/cpython/blob/d460c8ec52716a37080d31fdc0f673edcc98bee8/Include/object.h#L433). HPy has a hard time to compete with that if we don't have dedicated functions that can be mapped to those in CPython ABI mode. We could still have a slightly different API that would then internally use those functions. OTOH, the migration path would be easier if we just introduce similar type checking functions.

fangerer commented 1 year ago

We discussed that in today's dev call and one suggestions (from @hodgestar and @mattip) was to stay with the generic HPy_TypeCheck API for now and try to optimize on the implementation side. In particular, we can have a trampoline for the CPython ABI mode that does something like this:

HPyAPI_FUNC int HPy_TypeCheck(HPyContext *ctx, HPy h_obj, HPy h_type)
{
    PyObject *t = _h2py(h_type);
    if (t == &PyLong_Type)
        return PyLong_Check(_h2py(h_obj));
    // ...
    return ctx_TypeCheck(ctx, h_obj, h_type);
}

If that isn't enough, we can think of introducing more specific APIs.