Debian Codegraph @

pypy/module/cpyext/test/test_translate.py

raw symbols SCIP
1 from rpython.translator.c.test.test_genc import compile
2 import pypy.module.cpyext.api
3 from pypy.module.cpyext.api import slot_function
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
9 def test_llhelper(monkeypatch):
10 """Show how to get function pointers used in type slots"""
11 FT = lltype.FuncType([], lltype.Signed)
12 FTPTR = lltype.Ptr(FT)
13
14 def make_wrapper(self, space):
15 def wrapper():
16 return self.callable(space)
17 return wrapper
18 monkeypatch.setattr(pypy.module.cpyext.api.ApiFunction, '_make_wrapper', make_wrapper)
19
20 @specialize.memo()
21 def get_tp_function(space, typedef):
22 @slot_function([], lltype.Signed, error=-1)
23 def slot_tp_function(space):
24 return typedef.value
25
26 api_func = slot_tp_function.api_func
27 return lambda: llhelper(api_func.functype, api_func.get_wrapper(space))
28
29 class Space:
30 _cache = {}
31 @specialize.memo()
32 def fromcache(self, key):
33 try:
34 return self._cache[key]
35 except KeyError:
36 result = self._cache[key] = self.build(key)
37 return result
38 def _freeze_(self):
39 return True
40 class TypeDef:
41 def __init__(self, value):
42 self.value = value
43 def _freeze_(self):
44 return True
45 class W_Type:
46 def __init__(self, typedef):
47 self.instancetypedef = typedef
48 def _freeze(self):
49 try:
50 del self.funcptr
51 except AttributeError:
52 pass
53 return False
54
55 w_type1 = W_Type(TypeDef(123))
56 w_type2 = W_Type(TypeDef(456))
57 space = Space()
58
59 def run(x):
60 if x:
61 w_type = w_type1
62 else:
63 w_type = w_type2
64 typedef = w_type.instancetypedef
65 w_type.funcptr = get_tp_function(space, typedef)()
66 return w_type.funcptr()
67
68 fn = compile(run, [bool])
69 assert fn(True) == 123
70 assert fn(False) == 456
71