Debian Codegraph @

pypy/module/_hpy_universal/handlemanager.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import lltype, rffi
2 from rpython.rtyper.annlowlevel import llhelper
3 from rpython.rlib.objectmodel import specialize, always_inline
4 from rpython.rlib.unroll import unrolling_iterable
5 from rpython.rlib.debug import ll_assert
6 from pypy.interpreter.error import OperationError
7 from pypy.module._hpy_universal import llapi
8 from pypy.module._hpy_universal.apiset import API, DEBUG, TRACE
9 from pypy.objspace.std.capsuleobject import W_Capsule
10 from .buffer import setup_hpybuffer
11
12
13 @specialize.memo()
14 def make_missing_function(space, name):
15 def missing_function():
16 print ("oops! calling the slot '%s', "
17 "which is not implemented" % (name,))
18 raise OperationError(space.w_NotImplementedError, space.newtext(name))
19 return missing_function
20
21 CONSTANTS = [
22 ('NULL', lambda space: None),
23 # Constants
24 ('None', lambda space: space.w_None),
25 ('True', lambda space: space.w_True),
26 ('False', lambda space: space.w_False),
27 ('NotImplemented', lambda space: space.w_NotImplemented),
28 ('Ellipsis', lambda space: space.w_Ellipsis),
29 # Exceptions
30 ('BaseException', lambda space: space.w_BaseException),
31 ('Exception', lambda space: space.w_Exception),
32 ('StopAsyncIteration', lambda space: space.w_StopAsyncIteration),
33 ('StopIteration', lambda space: space.w_StopIteration),
34 ('GeneratorExit', lambda space: space.w_GeneratorExit),
35 ('ArithmeticError', lambda space: space.w_ArithmeticError),
36 ('LookupError', lambda space: space.w_LookupError),
37 ('AssertionError', lambda space: space.w_AssertionError),
38 ('AttributeError', lambda space: space.w_AttributeError),
39 ('BufferError', lambda space: space.w_BufferError),
40 ('EOFError', lambda space: space.w_EOFError),
41 ('FloatingPointError', lambda space: space.w_FloatingPointError),
42 ('OSError', lambda space: space.w_OSError),
43 ('ImportError', lambda space: space.w_ImportError),
44 ('ModuleNotFoundError', lambda space: space.w_ModuleNotFoundError),
45 ('IndexError', lambda space: space.w_IndexError),
46 ('KeyError', lambda space: space.w_KeyError),
47 ('KeyboardInterrupt', lambda space: space.w_KeyboardInterrupt),
48 ('MemoryError', lambda space: space.w_MemoryError),
49 ('NameError', lambda space: space.w_NameError),
50 ('OverflowError', lambda space: space.w_OverflowError),
51 ('RuntimeError', lambda space: space.w_RuntimeError),
52 ('RecursionError', lambda space: space.w_RecursionError),
53 ('NotImplementedError', lambda space: space.w_NotImplementedError),
54 ('SyntaxError', lambda space: space.w_SyntaxError),
55 ('IndentationError', lambda space: space.w_IndentationError),
56 ('TabError', lambda space: space.w_TabError),
57 ('ReferenceError', lambda space: space.w_ReferenceError),
58 ('SystemError', lambda space: space.w_SystemError),
59 ('SystemExit', lambda space: space.w_SystemExit),
60 ('TypeError', lambda space: space.w_TypeError),
61 ('UnboundLocalError', lambda space: space.w_UnboundLocalError),
62 ('UnicodeError', lambda space: space.w_UnicodeError),
63 ('UnicodeEncodeError', lambda space: space.w_UnicodeEncodeError),
64 ('UnicodeDecodeError', lambda space: space.w_UnicodeDecodeError),
65 ('UnicodeTranslateError', lambda space: space.w_UnicodeTranslateError),
66 ('ValueError', lambda space: space.w_ValueError),
67 ('ZeroDivisionError', lambda space: space.w_ZeroDivisionError),
68 ('BlockingIOError', lambda space: space.w_BlockingIOError),
69 ('BrokenPipeError', lambda space: space.w_BrokenPipeError),
70 ('ChildProcessError', lambda space: space.w_ChildProcessError),
71 ('ConnectionError', lambda space: space.w_ConnectionError),
72 ('ConnectionAbortedError', lambda space: space.w_ConnectionAbortedError),
73 ('ConnectionRefusedError', lambda space: space.w_ConnectionRefusedError),
74 ('ConnectionResetError', lambda space: space.w_ConnectionResetError),
75 ('FileExistsError', lambda space: space.w_FileExistsError),
76 ('FileNotFoundError', lambda space: space.w_FileNotFoundError),
77 ('InterruptedError', lambda space: space.w_InterruptedError),
78 ('IsADirectoryError', lambda space: space.w_IsADirectoryError),
79 ('NotADirectoryError', lambda space: space.w_NotADirectoryError),
80 ('PermissionError', lambda space: space.w_PermissionError),
81 ('ProcessLookupError', lambda space: space.w_ProcessLookupError),
82 ('TimeoutError', lambda space: space.w_TimeoutError),
83 # Warnings
84 ('Warning', lambda space: space.w_Warning),
85 ('UserWarning', lambda space: space.w_UserWarning),
86 ('DeprecationWarning', lambda space: space.w_DeprecationWarning),
87 ('PendingDeprecationWarning', lambda space: space.w_PendingDeprecationWarning),
88 ('SyntaxWarning', lambda space: space.w_SyntaxWarning),
89 ('RuntimeWarning', lambda space: space.w_RuntimeWarning),
90 ('FutureWarning', lambda space: space.w_FutureWarning),
91 ('ImportWarning', lambda space: space.w_ImportWarning),
92 ('UnicodeWarning', lambda space: space.w_UnicodeWarning),
93 ('BytesWarning', lambda space: space.w_BytesWarning),
94 ('ResourceWarning', lambda space: space.w_ResourceWarning),
95 # Types
96 ('BaseObjectType', lambda space: space.w_object),
97 ('TypeType', lambda space: space.w_type),
98 ('BoolType', lambda space: space.w_bool),
99 ('LongType', lambda space: space.w_int),
100 ('FloatType', lambda space: space.w_float),
101 ('UnicodeType', lambda space: space.w_unicode),
102 ('TupleType', lambda space: space.w_tuple),
103 ('ListType', lambda space: space.w_list),
104 ('ComplexType', lambda space: space.w_complex),
105 ('BytesType', lambda space: space.w_bytes),
106 ('MemoryViewType', lambda space: space.w_memoryview),
107 ('SliceType', lambda space: space.w_slice),
108 ('Builtins', lambda space: space.getattr(space.builtin, space.newtext("__dict__"))),
109 ('DictType', lambda space: space.w_dict),
110 ('CapsuleType', lambda space: space.gettypeobject(W_Capsule.typedef)),
111 ]
112
113 CONTEXT_FIELDS = unrolling_iterable(llapi.HPyContext.TO._names)
114 CONSTANT_NAMES = unrolling_iterable([name for name, _ in CONSTANTS])
115 DUMMY_FUNC = lltype.FuncType([], lltype.Void)
116
117 class AbstractHandleManager(object):
118 NULL = 0
119
120 def __init__(self, space, is_debug):
121 self.space = space
122 self.is_debug = is_debug
123 # setup a helper class for creating views in the bf_getbuffer slot
124 setup_hpybuffer(self)
125
126 def new(self, w_object):
127 raise NotImplementedError
128
129 def close(self, index):
130 raise NotImplementedError
131
132 def deref(self, index):
133 raise NotImplementedError
134
135 def consume(self, index):
136 raise NotImplementedError
137
138 def dup(self, index):
139 raise NotImplementedError
140
141 def attach_release_callback(self, index, cb):
142 raise NotImplementedError
143
144 def get_ctx(self):
145 raise NotImplementedError
146
147 def get_ctx_for_handles(self):
148 """Return the context that is consistent with handles created by new().
149
150 For DebugHandleManager, get_ctx() tracks the currently-valid debug
151 context (which may be next_dctx during before_call/after_call), but
152 new() always uses self.ctx. Callers that create handles and then pass
153 both the handle and the context to a C function must use the same
154 context for both; get_ctx_for_handles() satisfies that requirement.
155 """
156 return self.get_ctx()
157
158 def debug_before_call(self):
159 raise NotImplementedError
160
161 def debug_after_call(self, next_ctx):
162 raise NotImplementedError
163
164 @specialize.arg(0)
165 def using(self, *w_objs):
166 """
167 context-manager to new/close one or more handles
168 """
169 # Here we are using some RPython trickery to create different classes
170 # depending on the number of w_objs. The idea is that the whole class is
171 # optimized away and what's left is a series of calls to handles.new() and
172 # handles.close()
173 UsingContextManager = make_UsingContextManager(self, len(w_objs))
174 return UsingContextManager(w_objs)
175
176 def _freeze_(self):
177 return True
178
179
180 class HandleManager(AbstractHandleManager):
181 cls_suffix = '_u'
182
183 def __init__(self, space, uctx):
184 from .interp_extfunc import W_ExtensionFunction_u, W_ExtensionMethod_u
185 AbstractHandleManager.__init__(self, space, is_debug=False)
186 self.ctx = uctx
187 self.handles_w = [build_value(space) for name, build_value in CONSTANTS]
188 self.release_callbacks = [None] * len(self.handles_w)
189 self.free_list = []
190 self.w_ExtensionFunction = W_ExtensionFunction_u
191 self.w_ExtensionMethod = W_ExtensionMethod_u
192
193 @staticmethod
194 @specialize.memo()
195 def ctx_name():
196 # by using specialize.memo() this becomes a statically allocated
197 # charp, like a C string literal
198 return rffi.str2constcharp("HPy Universal ABI (PyPy backend)",
199 track_allocation=False)
200
201 def setup_universal_ctx(self):
202 space = self.space
203 self.ctx.c_name = self.ctx_name()
204
205 for name in CONTEXT_FIELDS:
206 if name == 'c_abi_version':
207 continue
208 if name.startswith('c_ctx_'):
209 # this is a function pointer: assign a default value so we get
210 # a reasonable error message if it's called without being
211 # assigned to something else
212 missing_function = make_missing_function(space, name)
213 funcptr = llhelper(lltype.Ptr(DUMMY_FUNC), missing_function)
214 setattr(self.ctx, name, rffi.cast(rffi.VOIDP, funcptr))
215 i = 0
216 for name in CONSTANT_NAMES:
217 if name != 'NULL':
218 h_struct = getattr(self.ctx, 'c_h_' + name)
219 h_struct.c__i = i
220 i = i + 1
221
222 for func in API.all_functions:
223 if func.cpyext and not space.config.objspace.hpy_cpyext_API:
224 # ignore cpyext functions if hpy_cpyext_API is False
225 continue
226 if func.is_helper:
227 # helper functions don't go into the context
228 continue
229 funcptr = rffi.cast(rffi.VOIDP, func.get_llhelper(space))
230 ctx_field = 'c_ctx_' + func.basename
231 setattr(self.ctx, ctx_field, funcptr)
232
233 self.ctx.c_ctx_FatalError = rffi.cast(rffi.VOIDP, llapi.pypy_HPy_FatalError)
234
235 def get_ctx(self):
236 return self.ctx
237
238 def debug_before_call(self):
239 return self.get_ctx()
240
241 def debug_after_call(self, next_ctx):
242 pass
243
244 def new(self, w_object):
245 if len(self.free_list) == 0:
246 index = len(self.handles_w)
247 self.handles_w.append(w_object)
248 self.release_callbacks.append(None)
249 else:
250 index = self.free_list.pop()
251 self.handles_w[index] = w_object
252 return index
253
254 def close(self, index):
255 ll_assert(index > 0, 'HandleManager.close: index > 0')
256 if self.release_callbacks[index] is not None:
257 self._call_release_callbacks(index)
258 self.handles_w[index] = None
259 self.free_list.append(index)
260
261 def _call_release_callbacks(self, index):
262 w_obj = self.deref(index)
263 for f in self.release_callbacks[index]:
264 f.release(index, w_obj)
265 self.release_callbacks[index] = None
266
267 def deref(self, index):
268 assert index > 0
269 return self.handles_w[index]
270
271 def consume(self, index):
272 """
273 Like close, but also return the w_object which was pointed by the handled
274 """
275 assert index > 0
276 w_object = self.handles_w[index]
277 self.close(index)
278 return w_object
279
280 def dup(self, index):
281 assert index > 0
282 w_object = self.handles_w[index]
283 return self.new(w_object)
284
285 def attach_release_callback(self, index, cb):
286 assert index > 0
287 if self.release_callbacks[index] is None:
288 self.release_callbacks[index] = [cb]
289 else:
290 self.release_callbacks[index].append(cb)
291
292 def str2ownedptr(self, s, owner):
293 # Used in converting a string to a `const char *` via a non-moving buffer
294 llbuf, llstring, flag = rffi.get_nonmovingbuffer_ll_final_null(s)
295 cb = FreeNonMovingBuffer(llbuf, llstring, flag)
296 self.attach_release_callback(owner, cb)
297 return llbuf
298
299
300 class DebugHandleManager(AbstractHandleManager):
301 cls_suffix = '_d'
302
303 def __init__(self, space, dctx, u_handles):
304 from .interp_extfunc import W_ExtensionFunction_d, W_ExtensionMethod_d
305 AbstractHandleManager.__init__(self, space, is_debug=True)
306 self.ctx = dctx
307 self.u_handles = u_handles
308 self.w_ExtensionFunction = W_ExtensionFunction_d
309 self.w_ExtensionMethod = W_ExtensionMethod_d
310
311 @staticmethod
312 @specialize.memo()
313 def ctx_name():
314 # by using specialize.memo() this becomes a statically allocated
315 # charp, like a C string literal
316 return rffi.str2constcharp("HPy Debug Mode ABI (PyPy backend)",
317 track_allocation=False)
318
319 def setup_debug_ctx(self):
320 space = self.space
321 self.ctx.c_name = self.ctx_name()
322 rffi.setintfield(self.ctx, 'c_abi_version', 0)
323 self.ctx.c__private = llapi.cts.cast('void*', 0)
324 llapi.hpy_debug_ctx_init(self.ctx, self.u_handles.ctx)
325 for func in DEBUG.all_functions:
326 funcptr = rffi.cast(rffi.VOIDP, func.get_llhelper(space))
327 ctx_field = 'c_ctx_' + func.basename
328 setattr(self.ctx, ctx_field, funcptr)
329 llapi.hpy_debug_set_ctx(self.ctx)
330
331 def get_ctx(self):
332 return llapi.hpy_debug_get_current_ctx()
333
334 def get_ctx_for_handles(self):
335 # new() always opens debug handles with self.ctx, so callers that
336 # pair a freshly-created handle with a context must use self.ctx too.
337 # get_ctx() may return next_dctx during a before_call/after_call cycle
338 # (e.g. when the GC finalizer fires inside a C callback), which would
339 # cause hpy_debug_unwrap_handle to return NULL for a handle created
340 # with self.ctx, leading to a segfault.
341 return self.ctx
342
343 def new(self, w_object):
344 uh = self.u_handles.new(w_object)
345 ret = llapi.hpy_debug_open_handle(self.ctx, uh)
346 # print 'debug new', ret, uh
347 return ret
348
349 def close(self, dh):
350 # tricky, we need to deref dh but use index for all self.u_handles interactions
351 index = llapi.hpy_debug_unwrap_handle(self.ctx, dh)
352 ll_assert(index > 0, 'HandleManager.close: index > 0')
353 # print 'debug close', index, dh
354 llapi.hpy_debug_close_handle(self.ctx, dh)
355 self.u_handles.close(index)
356
357 def deref(self, dh):
358 # print 'deref', dh
359 uh = llapi.hpy_debug_unwrap_handle(self.ctx, dh)
360 return self.u_handles.deref(uh)
361
362 def consume(self, dh):
363 uh = llapi.hpy_debug_unwrap_handle(self.ctx, dh)
364 llapi.hpy_debug_close_handle(self.ctx, dh)
365 return self.u_handles.consume(uh)
366
367 def dup(self, dh):
368 uh = llapi.hpy_debug_unwrap_handle(self.ctx, dh)
369 new_uh = self.u_handles.dup(uh)
370 w_object = self.u_handles.deref(new_uh)
371 ret = self.new(w_object)
372 # print 'dup', dh, uh, w_object, 'returning', ret
373 return ret
374
375 def attach_release_callback(self, index, cb):
376 uh = llapi.hpy_debug_unwrap_handle(self.ctx, index)
377 self.u_handles.attach_release_callback(uh, cb)
378
379 def debug_before_call(self):
380 return llapi.hpy_debug_ctx_before_call(self.ctx)
381
382 def debug_after_call(self, next_ctx):
383 llapi.hpy_debug_ctx_after_call(self.ctx, next_ctx)
384
385 def str2ownedptr(self, s, owner):
386 return self.u_handles.str2ownedptr(s, owner)
387
388 class TraceHandleManager(AbstractHandleManager):
389 cls_suffix = '_t'
390
391 def __init__(self, space, u_handles):
392 from .interp_extfunc import W_ExtensionFunction_t, W_ExtensionMethod_t
393 AbstractHandleManager.__init__(self, space, is_debug=False)
394 self.u_handles = u_handles
395 self.w_ExtensionFunction = W_ExtensionFunction_t
396 self.w_ExtensionMethod = W_ExtensionMethod_t
397
398 @staticmethod
399 @specialize.memo()
400 def ctx_name():
401 # by using specialize.memo() this becomes a statically allocated
402 # charp, like a C string literal
403 return rffi.str2constcharp("HPy Trace Mode ABI (PyPy backend)",
404 track_allocation=False)
405
406 def setup_trace_ctx(self):
407 space = self.space
408 ctx = llapi.hpy_trace_get_ctx(self.u_handles.ctx)
409 ctx.c_name = self.ctx_name()
410 rffi.setintfield(ctx, 'c_abi_version', 0)
411 ctx.c__private = llapi.cts.cast('void*', 0)
412 llapi.hpy_trace_ctx_init(ctx, self.u_handles.ctx)
413 for func in TRACE.all_functions:
414 funcptr = rffi.cast(rffi.VOIDP, func.get_llhelper(space))
415 ctx_field = 'c_ctx_' + func.basename
416 setattr(ctx, ctx_field, funcptr)
417
418 def get_ctx(self):
419 return llapi.hpy_trace_get_stored_ctx()
420
421 def debug_before_call(self):
422 return self.get_ctx()
423
424 def debug_after_call(self, next_ctx):
425 pass
426
427 def new(self, w_object):
428 return self.u_handles.new(w_object)
429
430 def close(self, index):
431 return self.u_handles.close(index)
432
433 def consume(self, index):
434 return self.u_handles.consume(index)
435
436
437 class HandleReleaseCallback(object):
438
439 def release(self, h, w_obj):
440 ll_assert(False, 'HandleReleaseCallback.release: not implemented')
441
442
443 class FreeNonMovingBuffer(HandleReleaseCallback):
444 """
445 Callback to call rffi.free_nonmovingbuffer_ll
446 """
447
448 def __init__(self, llbuf, llstring, flag):
449 self.llbuf = llbuf
450 self.llstring = llstring
451 self.flag = flag
452
453 def release(self, h, w_obj):
454 rffi.free_nonmovingbuffer_ll(self.llbuf, self.llstring, self.flag)
455
456
457 @specialize.memo()
458 def make_UsingContextManager(mgr, N):
459 INDICES = unrolling_iterable(range(N))
460 class UsingContextManager(object):
461
462 @always_inline
463 def __init__(self, w_objects):
464 self.w_objects = w_objects
465 self.handles = (0,) * N
466
467 #@always_inline
468 def __enter__(self):
469 handles = ()
470 for i in INDICES:
471 h = mgr.new(self.w_objects[i])
472 handles += (h,)
473 self.handles = handles
474
475 # if we have only one handle, return it directly. This makes it
476 # possible to write this:
477 # with handles.using(w1) as h1:
478 # ...
479 # AND this
480 # with handles.using(w1, w2) as (h1, h2):
481 # ...
482 if N == 1:
483 return self.handles[0]
484 else:
485 return handles
486
487 #@always_inline
488 def __exit__(self, etype, evalue, tb):
489 for i in INDICES:
490 mgr.close(self.handles[i])
491
492 return UsingContextManager