Debian Codegraph @

pypy/module/_continuation/interp_continuation.py

raw symbols SCIP
1 from rpython.rlib.rstacklet import StackletThread
2 from rpython.rlib import jit
3 from rpython.rlib import rvmprof
4 from pypy.interpreter.error import OperationError
5 from pypy.interpreter.error import oefmt
6 from pypy.interpreter.executioncontext import ExecutionContext
7 from pypy.interpreter.baseobjspace import W_Root
8 from pypy.interpreter.typedef import TypeDef
9 from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
10 from pypy.interpreter.pycode import PyCode
11 from pypy.interpreter.pyframe import PyFrame
12
13
14 class W_Continulet(W_Root):
15 sthread = None
16
17 def __init__(self, space):
18 self.space = space
19 # states:
20 # - not init'ed: self.sthread == None
21 # - normal: self.sthread != None, not is_empty_handle(self.h)
22 # - finished: self.sthread != None, is_empty_handle(self.h)
23
24 def check_sthread(self):
25 ec = self.space.getexecutioncontext()
26 if ec.stacklet_thread is not self.sthread:
27 global_state.clear()
28 raise geterror(self.space, "cannot switch to a different thread")
29
30 def descr_init(self, w_callable, __args__):
31 if self.sthread is not None:
32 raise geterror(self.space, "continulet already __init__ialized")
33 sthread = build_sthread(self.space)
34 #
35 # hackish: build the frame "by hand", passing it the correct arguments
36 space = self.space
37 w_args, w_kwds = __args__.topacked()
38 bottomframe = space.createframe(get_entrypoint_pycode(space),
39 get_w_module_dict(space), None)
40 bottomframe.locals_cells_stack_w[0] = self
41 bottomframe.locals_cells_stack_w[1] = w_callable
42 bottomframe.locals_cells_stack_w[2] = w_args
43 bottomframe.locals_cells_stack_w[3] = w_kwds
44 self.bottomframe = bottomframe
45 #
46 global_state.origin = self
47 self.sthread = sthread
48 saved_exception = pre_switch(sthread)
49 h = sthread.new(new_stacklet_callback)
50 post_switch(sthread, h, saved_exception)
51
52 def switch(self, w_to):
53 sthread = self.sthread
54 to = self.space.interp_w(W_Continulet, w_to, can_be_None=True)
55 if to is not None and to.sthread is None:
56 to = None
57 if sthread is None: # if self is non-initialized:
58 if to is not None: # if we are given a 'to'
59 self = to # then just use it and ignore 'self'
60 sthread = self.sthread
61 to = None
62 else:
63 return get_result() # else: no-op
64 if sthread is not None and sthread.is_empty_handle(self.h):
65 global_state.clear()
66 raise geterror(self.space, "continulet already finished")
67 if to is not None:
68 if to.sthread is not sthread:
69 global_state.clear()
70 raise geterror(self.space, "cross-thread double switch")
71 if self is to: # double-switch to myself: no-op
72 return get_result()
73 if sthread.is_empty_handle(to.h):
74 global_state.clear()
75 raise geterror(self.space, "continulet already finished")
76 self.check_sthread()
77
78 global_state.origin = self
79 if to is None:
80 # simple switch: going to self.h
81 global_state.destination = self
82 else:
83 # double switch: the final destination is to.h
84 global_state.destination = to
85 #
86 saved_exception = pre_switch(sthread)
87 h = sthread.switch(global_state.destination.h)
88 return post_switch(sthread, h, saved_exception)
89
90 @unwrap_spec(w_value = WrappedDefault(None),
91 w_to = WrappedDefault(None))
92 def descr_switch(self, w_value=None, w_to=None):
93 global_state.w_value = w_value
94 return self.switch(w_to)
95
96 @unwrap_spec(w_val = WrappedDefault(None),
97 w_tb = WrappedDefault(None),
98 w_to = WrappedDefault(None))
99 def descr_throw(self, w_type, w_val=None, w_tb=None, w_to=None):
100 from pypy.interpreter.pytraceback import check_traceback
101 space = self.space
102 #
103 msg = "throw() third argument must be a traceback object"
104 if space.is_none(w_tb):
105 tb = None
106 else:
107 tb = check_traceback(space, w_tb, msg)
108 #
109 operr = OperationError(w_type, w_val, tb)
110 operr.normalize_exception(space)
111 global_state.w_value = None
112 global_state.propagate_exception = operr
113 return self.switch(w_to)
114
115 def descr_is_pending(self):
116 valid = (self.sthread is not None
117 and not self.sthread.is_empty_handle(self.h))
118 return self.space.newbool(valid)
119
120 def descr__reduce__(self):
121 raise oefmt(self.space.w_NotImplementedError,
122 "continulet's pickle support is currently disabled")
123 from pypy.module._continuation import interp_pickle
124 return interp_pickle.reduce(self)
125
126 def descr__setstate__(self, w_args):
127 # XXX: review direct calls to frame.run(), notably when
128 # unpickling generators (or coroutines!)
129 raise oefmt(self.space.w_NotImplementedError,
130 "continulet's pickle support is currently disabled")
131 from pypy.module._continuation import interp_pickle
132 interp_pickle.setstate(self, w_args)
133
134 def descr_get_frame(self, space):
135 if self.sthread is None:
136 w_frame = space.w_False
137 elif self.sthread.is_empty_handle(self.h):
138 w_frame = space.w_None
139 else:
140 w_frame = self.bottomframe
141 return w_frame
142
143
144 def W_Continulet___new__(space, w_subtype, __args__):
145 r = space.allocate_instance(W_Continulet, w_subtype)
146 r.__init__(space)
147 return r
148
149 def unpickle(space, w_subtype):
150 """Pickle support."""
151 r = space.allocate_instance(W_Continulet, w_subtype)
152 r.__init__(space)
153 return r
154
155
156 W_Continulet.typedef = TypeDef(
157 '_continuation.continulet',
158 __new__ = interp2app(W_Continulet___new__),
159 __init__ = interp2app(W_Continulet.descr_init),
160 switch = interp2app(W_Continulet.descr_switch),
161 throw = interp2app(W_Continulet.descr_throw),
162 is_pending = interp2app(W_Continulet.descr_is_pending),
163 __reduce__ = interp2app(W_Continulet.descr__reduce__),
164 __setstate__= interp2app(W_Continulet.descr__setstate__),
165 _get_frame=interp2app(W_Continulet.descr_get_frame)
166 )
167
168 # ____________________________________________________________
169
170 # Continulet objects maintain a dummy frame object in order to ensure
171 # that the 'f_back' chain is consistent. We hide this dummy frame
172 # object by giving it a dummy code object with hidden_applevel=True.
173
174 class State:
175 def __init__(self, space):
176 self.space = space
177 w_module = space.getbuiltinmodule('_continuation')
178 self.w_error = space.getattr(w_module, space.newtext('error'))
179 # the following function switches away immediately, so that
180 # continulet.__init__() doesn't immediately run func(), but it
181 # also has the hidden purpose of making sure we have a single
182 # bottomframe for the whole duration of the continulet's run.
183 # Hackish: only the func_code is used, and used in the context
184 # of w_globals == this module, so we can access the name
185 # 'continulet' directly.
186 w_code = space.appexec([], '''():
187 def start(c, func, args, kwds):
188 if continulet.switch(c) is not None:
189 raise TypeError(
190 "can\'t send non-None value to a just-started continulet")
191 return func(c, *args, **kwds)
192 return start.__code__
193 ''')
194 self.entrypoint_pycode = space.interp_w(PyCode, w_code)
195 self.entrypoint_pycode.hidden_applevel = True
196 self.w_unpickle = w_module.get('_p')
197 self.w_module_dict = w_module.getdict(space)
198
199 def geterror(space, message):
200 cs = space.fromcache(State)
201 return OperationError(cs.w_error, space.newtext(message))
202
203 def get_entrypoint_pycode(space):
204 cs = space.fromcache(State)
205 return cs.entrypoint_pycode
206
207 def get_w_module_dict(space):
208 cs = space.fromcache(State)
209 return cs.w_module_dict
210
211 # ____________________________________________________________
212
213
214 class SThread(StackletThread):
215
216 def __init__(self, space, ec):
217 StackletThread.__init__(self)
218 self.space = space
219 self.ec = ec
220 # for unpickling
221 from rpython.rlib.rweakref import RWeakKeyDictionary
222 self.frame2continulet = RWeakKeyDictionary(PyFrame, W_Continulet)
223
224 ExecutionContext.stacklet_thread = None
225
226 # ____________________________________________________________
227
228
229 class GlobalState:
230 def clear(self):
231 self.origin = None
232 self.destination = None
233 self.w_value = None
234 self.propagate_exception = None
235 global_state = GlobalState()
236 global_state.clear()
237
238
239 def new_stacklet_callback(h, arg):
240 self = global_state.origin
241 self.h = h
242 global_state.clear()
243 try:
244 rvmprof.start_sampling()
245 frame = self.bottomframe
246 w_result = frame.execute_frame()
247 except Exception as e:
248 global_state.propagate_exception = e
249 else:
250 global_state.w_value = w_result
251 finally:
252 rvmprof.stop_sampling()
253 self.sthread.ec.topframeref = jit.vref_None
254 global_state.origin = self
255 global_state.destination = self
256 return self.h
257
258 def pre_switch(sthread):
259 saved_exception = sthread.ec.save_and_reset_exc_info_state()
260 return saved_exception
261
262 def post_switch(sthread, h, saved_exception):
263 origin = global_state.origin
264 self = global_state.destination
265 global_state.origin = None
266 global_state.destination = None
267 self.h, origin.h = origin.h, h
268 #
269 current = sthread.ec.topframeref
270 sthread.ec.topframeref = self.bottomframe.f_backref
271 sthread.ec.restore_save_exc_info_state(saved_exception)
272 self.bottomframe.f_backref = origin.bottomframe.f_backref
273 origin.bottomframe.f_backref = current
274 #
275 return get_result()
276
277 def get_result():
278 if global_state.propagate_exception:
279 e = global_state.propagate_exception
280 global_state.propagate_exception = None
281 raise e
282 w_value = global_state.w_value
283 global_state.w_value = None
284 return w_value
285
286 def build_sthread(space):
287 ec = space.getexecutioncontext()
288 sthread = ec.stacklet_thread
289 if not sthread:
290 sthread = ec.stacklet_thread = SThread(space, ec)
291 return sthread
292
293 # ____________________________________________________________
294
295 def permute(space, args_w):
296 sthread = build_sthread(space)
297 #
298 contlist = []
299 for w_cont in args_w:
300 cont = space.interp_w(W_Continulet, w_cont)
301 if cont.sthread is not sthread:
302 if cont.sthread is None:
303 continue # ignore non-initialized continulets
304 else:
305 raise geterror(space, "inter-thread support is missing")
306 elif sthread.is_empty_handle(cont.h):
307 raise geterror(space, "got an already-finished continulet")
308 contlist.append(cont)
309 #
310 if len(contlist) > 1:
311 otherh = contlist[-1].h
312 otherb = contlist[-1].bottomframe.f_backref
313 for cont in contlist:
314 otherh, cont.h = cont.h, otherh
315 b = cont.bottomframe
316 otherb, b.f_backref = b.f_backref, otherb