Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions mypyc/codegen/emitwrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ def generate_get_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
def generate_hash_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
"""Generates a wrapper for native __hash__ methods."""
name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}"
emitter.emit_line(f"static Py_ssize_t {name}(PyObject *self) {{")
emitter.emit_line(f"static Py_hash_t {name}(PyObject *self) {{")
emitter.emit_line(
"{}retval = {}{}{}(self);".format(
emitter.ctype_spaced(fn.ret_type),
Expand All @@ -618,13 +618,20 @@ def generate_hash_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
)
emitter.emit_error_check("retval", fn.ret_type, "return -1;")
if is_int_rprimitive(fn.ret_type):
emitter.emit_line("Py_ssize_t val = CPyTagged_AsSsize_t(retval);")
emitter.emit_line("if (likely(CPyTagged_CheckShort(retval))) {")
# A short int always fits in Py_hash_t, but -1 is reserved for errors
emitter.emit_line("Py_hash_t val = CPyTagged_ShortAsSsize_t(retval);")
emitter.emit_line("return val == -1 ? -2 : val;")
emitter.emit_line("}")
emitter.emit_line("Py_hash_t val = CPy_HashFromResult(CPyTagged_LongAsObject(retval));")
emitter.emit_dec_ref("retval", fn.ret_type)
else:
emitter.emit_line("Py_ssize_t val = PyLong_AsSsize_t(retval);")
emitter.emit_dec_ref("retval", fn.ret_type)
emitter.emit_line("if (PyErr_Occurred()) return -1;")
# We can't return -1 from a hash function..
emitter.emit_line("if (val == -1) return -2;")
# CPy_HashFromResult() takes an object, so box other unboxed types such as i64
emitter.emit_box("retval", "retbox", fn.ret_type, declare_dest=True)
if fn.ret_type.is_unboxed:
emitter.emit_line("if (unlikely(retbox == NULL)) return -1;")
emitter.emit_line("Py_hash_t val = CPy_HashFromResult(retbox);")
emitter.emit_dec_ref("retbox", object_rprimitive)
emitter.emit_line("return val;")
emitter.emit_line("}")

Expand Down
1 change: 1 addition & 0 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,7 @@ static void CPy_LogGetAttr(const char *method, PyObject *obj, PyObject *attr) {
PyObject_GetAttr((obj), (attr)))

CPyTagged CPyObject_Hash(PyObject *o);
Py_hash_t CPy_HashFromResult(PyObject *res);

// Default identity-based hash (same as object.__hash__), used as tp_hash
static inline Py_hash_t CPy_DefaultHash(PyObject *o) {
Expand Down
17 changes: 17 additions & 0 deletions mypyc/lib-rt/generic_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ CPyTagged CPyObject_Hash(PyObject *o) {
}
}

// Convert the result of a __hash__ method to a hash value like slot_tp_hash in
// CPython: an int that doesn't fit in Py_hash_t is hashed again, so any int is a
// valid result. Return -1 with an exception set if res isn't an int.
Py_hash_t CPy_HashFromResult(PyObject *res) {
if (unlikely(!PyLong_Check(res))) {
PyErr_SetString(PyExc_TypeError, "__hash__ method should return an integer");
return -1;
}
Py_hash_t h = PyLong_AsSsize_t(res);
if (h == -1 && PyErr_Occurred()) {
PyErr_Clear();
h = PyLong_Type.tp_hash(res);
}
// -1 is reserved for errors
return h == -1 ? -2 : h;
}

PyObject *CPyObject_GetAttr3(PyObject *v, PyObject *name, PyObject *defl)
{
PyObject *result;
Expand Down
46 changes: 46 additions & 0 deletions mypyc/test-data/run-dunders.test
Original file line number Diff line number Diff line change
Expand Up @@ -1477,6 +1477,52 @@ def test_explicit_hash() -> None:
assert hash(EqHash()) == 5
assert hash(EqHashSub()) == 5

[case testDundersHashResult]
# hash() converts the value returned by __hash__ like in Python
from typing import Any

from mypy_extensions import i64
from testutil import assertRaises

class Hash:
def __init__(self, h: int) -> None:
self.h = h

def __hash__(self) -> int:
return self.h

class HashAny:
def __init__(self, h: Any) -> None:
self.h = h

def __hash__(self) -> Any:
return self.h

class HashI64:
def __hash__(self) -> i64:
return -1

def test_hash_result() -> None:
# These fit in Py_hash_t on 32-bit and 64-bit platforms
for h in [0, 7, -2, 2**30, -(2**31)]:
assert hash(Hash(h)) == h
assert hash(HashAny(h)) == h
# -1 is reserved for errors
assert hash(Hash(-1)) == -2
assert hash(HashAny(-1)) == -2
assert hash(HashI64()) == -2
# These don't fit in Py_hash_t on any platform, so they are hashed again
for h in [2**63, -(2**63) - 1, 2**64 + 5, -(2**100)]:
assert hash(Hash(h)) == hash(h)
assert hash(HashAny(h)) == hash(h)
# A long int that fits in Py_hash_t on 64-bit platforms, but not on 32-bit ones
assert hash(Hash(2**62)) in (2**62, hash(2**62))
assert hash(HashAny(2**62)) in (2**62, hash(2**62))
assert hash(HashAny(True)) == 1
for x in ["x", 1.0, None]:
with assertRaises(TypeError, "__hash__ method should return an integer"):
hash(HashAny(x))

[case testDundersImplicitNeWithNarrowRhs]
class Accepted:
pass
Expand Down
Loading