Debian Codegraph @

lib_pypy/greenlet.py

raw symbols SCIP
1 import sys
2 import __pypy__
3 import _continuation
4 import _contextvars
5
6 __version__ = "0.4.13"
7
8 # ____________________________________________________________
9 # Constants from greenlet 1.0.0
10
11 GREENLET_USE_GC = True
12 GREENLET_USE_TRACING = True
13 GREENLET_USE_CONTEXT_VARS = True # added in py3.7
14
15 # ____________________________________________________________
16 # Exceptions
17
18 class GreenletExit(BaseException):
19 """This special exception does not propagate to the parent greenlet; it
20 can be used to kill a single greenlet."""
21
22 error = _continuation.error
23
24 # ____________________________________________________________
25 # Helper function
26
27 def getcurrent():
28 "Returns the current greenlet (i.e. the one which called this function)."
29 try:
30 return _tls.current
31 except AttributeError:
32 # first call in this thread: current == main
33 _green_create_main()
34 return _tls.current
35
36 # ____________________________________________________________
37 # The 'greenlet' class
38
39 _continulet = _continuation.continulet
40
41 class greenlet(_continulet):
42 getcurrent = staticmethod(getcurrent)
43 error = error
44 GreenletExit = GreenletExit
45 __main = False
46 __started = False
47 __context = None
48
49 def __new__(cls, *args, **kwds):
50 self = _continulet.__new__(cls)
51 self.parent = getcurrent()
52 return self
53
54 def __init__(self, run=None, parent=None):
55 if run is not None:
56 self.run = run
57 if parent is not None:
58 self.parent = parent
59
60 def switch(self, *args, **kwds):
61 "Switch execution to this greenlet, optionally passing the values "
62 "given as argument(s). Returns the value passed when switching back."
63 return self.__switch('switch', (args, kwds))
64
65 def throw(self, typ=GreenletExit, val=None, tb=None):
66 "raise exception in greenlet, return value passed when switching back"
67 return self.__switch('throw', typ, val, tb)
68
69 def __switch(target, methodname, *baseargs):
70 current = getcurrent()
71 #
72 while not (target.__main or _continulet.is_pending(target)):
73 # inlined __nonzero__ ^^^ in case it's overridden
74 if not target.__started:
75 # check that 'target.parent' runs in the current thread,
76 # at least. It can be changed arbitrarily afterwards in
77 # pypy greenlets, but too bad
78 parent1 = target.parent
79 while not parent1.__started:
80 parent1 = parent1.parent
81 if parent1.__thread_id is not _tls.thread_id:
82 raise error("cannot start greenlet because its 'parent'"
83 " is running on a different thread")
84
85 if methodname == 'switch':
86 greenlet_func = _greenlet_start
87 else:
88 greenlet_func = _greenlet_throw
89 _continulet.__init__(target, greenlet_func, *baseargs)
90 methodname = 'switch'
91 baseargs = ()
92 target.__thread_id = _tls.thread_id
93 target.__started = True
94 break
95 # already done, go to the parent instead
96 # (NB. infinite loop possible, but unlikely, unless you mess
97 # up the 'parent' explicitly. Good enough, because a Ctrl-C
98 # will show that the program is caught in this loop here.)
99 target = target.parent
100 # convert a "raise GreenletExit" into "return GreenletExit"
101 if methodname == 'throw':
102 try:
103 raise __pypy__.normalize_exc(baseargs[0], baseargs[1])
104 except GreenletExit as e:
105 methodname = 'switch'
106 baseargs = (((e,), {}),)
107 except:
108 baseargs = sys.exc_info()[:2] + baseargs[2:]
109 else:
110 if target.__thread_id is not _tls.thread_id:
111 raise error("cannot switch to greenlet running in a"
112 " different thread")
113 #
114 try:
115 unbound_method = getattr(_continulet, methodname)
116 current.__context = __pypy__.get_contextvar_context()
117 _tls.leaving = current
118 args, kwds = unbound_method(current, *baseargs, to=target)
119 _tls.current = current
120 __pypy__.set_contextvar_context(current.__context)
121 current.__context = None
122 except:
123 _tls.current = current
124 __pypy__.set_contextvar_context(current.__context)
125 current.__context = None
126 if hasattr(_tls, 'trace'):
127 _run_trace_callback('throw')
128 _tls.leaving = None
129 raise
130 else:
131 if hasattr(_tls, 'trace'):
132 _run_trace_callback('switch')
133 _tls.leaving = None
134 #
135 if kwds:
136 if args:
137 return args, kwds
138 return kwds
139 elif len(args) == 1:
140 return args[0]
141 else:
142 return args
143
144 def __bool__(self):
145 return self.__main or _continulet.is_pending(self)
146
147 @property
148 def dead(self):
149 return self.__started and not self
150
151 @property
152 def gr_frame(self):
153 # xxx this doesn't work when called on either the current or
154 # the main greenlet of another thread
155 if self is getcurrent():
156 return None
157 if self.__main:
158 self = getcurrent()
159 f = self._get_frame()
160 if not f:
161 return None
162 return f.f_back.f_back.f_back # go past start(), __switch(), switch()
163
164 def __get_context(self):
165 if self is getcurrent():
166 return __pypy__.get_contextvar_context()
167 else:
168 # can't reliably detect if 'self' is the current greenlet running
169 # in another thread. We might have race conditions between knowing
170 # if it is the case and actually reading 'self.__context'. So we
171 # just ignore that case and return 'self.__context'.
172 return self.__context
173
174 def __set_context(self, nctx):
175 if nctx is not None and not isinstance(nctx, _contextvars.Context):
176 raise TypeError("greenlet context must be a "
177 "contextvars.Context or None")
178 if self is getcurrent():
179 __pypy__.set_contextvar_context(nctx)
180 else:
181 self.__context = nctx # same issue as __get_context()
182 gr_context = property(__get_context, __set_context)
183
184 # ____________________________________________________________
185 # Recent additions
186
187 GREENLET_USE_GC = True
188 GREENLET_USE_TRACING = True
189
190 def gettrace():
191 return getattr(_tls, 'trace', None)
192
193 def settrace(callback):
194 try:
195 prev = _tls.trace
196 del _tls.trace
197 except AttributeError:
198 prev = None
199 if callback is not None:
200 _tls.trace = callback
201 return prev
202
203 def _run_trace_callback(event):
204 try:
205 _tls.trace(event, (_tls.leaving, _tls.current))
206 except:
207 # In case of exceptions trace function is removed
208 if hasattr(_tls, 'trace'):
209 del _tls.trace
210 raise
211
212 # ____________________________________________________________
213 # Internal stuff
214
215 try:
216 from threading import local as _local
217 except ImportError:
218 class _local(object): # assume no threads
219 pass
220
221 _tls = _local()
222
223 def _green_create_main():
224 # create the main greenlet for this thread
225 _tls.current = None
226 _tls.thread_id = object()
227 gmain = greenlet.__new__(greenlet)
228 gmain._greenlet__thread_id = _tls.thread_id
229 gmain._greenlet__main = True
230 gmain._greenlet__started = True
231 assert gmain.parent is None
232 _tls.main = gmain
233 _tls.current = gmain
234
235 def _greenlet_start(greenlet, args):
236 try:
237 args, kwds = args
238 _tls.current = greenlet
239 try:
240 __pypy__.set_contextvar_context(greenlet._greenlet__context)
241 greenlet._greenlet__context = None
242 if hasattr(_tls, 'trace'):
243 _run_trace_callback('switch')
244 res = greenlet.run(*args, **kwds)
245 except GreenletExit as e:
246 res = e
247 finally:
248 _continuation.permute(greenlet, greenlet.parent)
249 return ((res,), None)
250 finally:
251 greenlet._greenlet__context = __pypy__.get_contextvar_context()
252 _tls.leaving = greenlet
253
254 def _greenlet_throw(greenlet, exc, value, tb):
255 try:
256 _tls.current = greenlet
257 try:
258 __pypy__.set_contextvar_context(greenlet._greenlet__context)
259 greenlet._greenlet__context = None
260 if hasattr(_tls, 'trace'):
261 _run_trace_callback('throw')
262 raise __pypy__.normalize_exc(exc, value, tb)
263 except GreenletExit as e:
264 res = e
265 finally:
266 _continuation.permute(greenlet, greenlet.parent)
267 return ((res,), None)
268 finally:
269 greenlet._greenlet__context = __pypy__.get_contextvar_context()
270 _tls.leaving = greenlet