PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/cpyext/test/test_translate.py

https://bitbucket.org/pypy/pypy/
Python | 71 lines | 61 code | 9 blank | 1 comment | 6 complexity | 59da0692dfb5827415490e763367a2c8 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from rpython.translator.c.test.test_genc import compile
  2. import pypy.module.cpyext.api
  3. from pypy.module.cpyext.api import cpython_api
  4. from rpython.rtyper.annlowlevel import llhelper
  5. from rpython.rtyper.lltypesystem import lltype
  6. from rpython.rlib.objectmodel import specialize
  7. from rpython.rlib.nonconst import NonConstant
  8. def test_llhelper(monkeypatch):
  9. """Show how to get function pointers used in type slots"""
  10. FT = lltype.FuncType([], lltype.Signed)
  11. FTPTR = lltype.Ptr(FT)
  12. def make_wrapper(self, space):
  13. def wrapper():
  14. return self.callable(space)
  15. return wrapper
  16. monkeypatch.setattr(pypy.module.cpyext.api.ApiFunction, '_make_wrapper', make_wrapper)
  17. @specialize.memo()
  18. def get_tp_function(space, typedef):
  19. @cpython_api([], lltype.Signed, error=-1, header=None)
  20. def slot_tp_function(space):
  21. return typedef.value
  22. api_func = slot_tp_function.api_func
  23. return lambda: llhelper(api_func.functype, api_func.get_wrapper(space))
  24. class Space:
  25. _cache = {}
  26. @specialize.memo()
  27. def fromcache(self, key):
  28. try:
  29. return self._cache[key]
  30. except KeyError:
  31. result = self._cache[key] = self.build(key)
  32. return result
  33. def _freeze_(self):
  34. return True
  35. class TypeDef:
  36. def __init__(self, value):
  37. self.value = value
  38. def _freeze_(self):
  39. return True
  40. class W_Type:
  41. def __init__(self, typedef):
  42. self.instancetypedef = typedef
  43. def _freeze(self):
  44. try:
  45. del self.funcptr
  46. except AttributeError:
  47. pass
  48. return False
  49. w_type1 = W_Type(TypeDef(123))
  50. w_type2 = W_Type(TypeDef(456))
  51. space = Space()
  52. def run(x):
  53. if x:
  54. w_type = w_type1
  55. else:
  56. w_type = w_type2
  57. typedef = w_type.instancetypedef
  58. w_type.funcptr = get_tp_function(space, typedef)()
  59. return w_type.funcptr()
  60. fn = compile(run, [bool])
  61. assert fn(True) == 123
  62. assert fn(False) == 456