Debian Codegraph @

rpython/translator/tool/pdbplus.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import pdb, bdb
4 import types
5 import code
6 import sys
7 from rpython.flowspace.model import FunctionGraph
8
9 class NoTTY(Exception):
10 pass
11
12 class PdbPlusShow(pdb.Pdb):
13
14 def __init__(self, translator):
15 pdb.Pdb.__init__(self)
16 if self.prompt == "(Pdb) ":
17 self.prompt = "(Pdb+) "
18 else:
19 self.prompt = self.prompt.replace("(", "(Pdb+ on ", 1)
20 self.translator = translator
21 self.exposed = {}
22
23 def post_mortem(self, t):
24 self.reset()
25 while t.tb_next is not None:
26 t = t.tb_next
27 self.interaction(t.tb_frame, t)
28
29 def preloop(self):
30 if not hasattr(sys.stdout, 'isatty') or not sys.stdout.isatty():
31 raise NoTTY("Cannot start the debugger when stdout is captured.")
32 pdb.Pdb.preloop(self)
33
34 def expose(self, d):
35 self.exposed.update(d)
36
37 def _show(self, page):
38 page.display_background()
39
40 def _importobj(self, fullname):
41 obj = None
42 name = ''
43 for comp in fullname.split('.'):
44 name += comp
45 obj = getattr(obj, comp, None)
46 if obj is None:
47 try:
48 obj = __import__(name, {}, {}, ['*'])
49 except ImportError:
50 raise NameError
51 name += '.'
52 return obj
53
54 TRYPREFIXES = ['','pypy.','pypy.objspace.','pypy.interpreter.', 'pypy.objspace.std.' ]
55
56 def _mygetval(self, arg, errmsg):
57 try:
58 return eval(arg, self.curframe.f_globals,
59 self.curframe.f_locals)
60 except:
61 t, v = sys.exc_info()[:2]
62 if isinstance(t, str):
63 exc_type_name = t
64 else: exc_type_name = t.__name__
65 if not isinstance(arg, str):
66 print('*** %s' % errmsg, "\t[%s: %s]" % (exc_type_name, v))
67 else:
68 print('*** %s:' % errmsg, arg, "\t[%s: %s]" % (exc_type_name, v))
69 raise
70
71 def _getobj(self, name):
72 if '.' in name:
73 for pfx in self.TRYPREFIXES:
74 try:
75 return self._importobj(pfx+name)
76 except NameError:
77 pass
78 try:
79 return self._mygetval(name, "Not found")
80 except (KeyboardInterrupt, SystemExit, MemoryError):
81 raise
82 except:
83 pass
84 return None
85
86 def do_find(self, arg):
87 """find obj [as var]
88 find dotted named obj, possibly using prefixing with some packages
89 in pypy (see help pypyprefixes); the result is assigned to var or _."""
90 objarg, var = self._parse_modif(arg)
91 obj = self._getobj(objarg)
92 if obj is None:
93 return
94 print(obj)
95 self._setvar(var, obj)
96
97 def _parse_modif(self, arg, modif='as'):
98 var = '_'
99 aspos = arg.rfind(modif+' ')
100 if aspos != -1:
101 objarg = arg[:aspos].strip()
102 var = arg[aspos+(1+len(modif)):].strip()
103 else:
104 objarg = arg
105 return objarg, var
106
107 def _setvar(self, var, obj):
108 self.curframe.f_locals[var] = obj
109
110 class GiveUp(Exception):
111 pass
112
113 def _getcdef(self, cls):
114 try:
115 return self.translator.annotator.bookkeeper.getuniqueclassdef(cls)
116 except Exception:
117 print("*** cannot get classdef: %s" % cls)
118 return None
119
120 def _make_flt(self, expr):
121 try:
122 expr = compile(expr, '<filter>', 'eval')
123 except SyntaxError:
124 print("*** syntax: %s" % expr)
125 return None
126 def flt(c):
127 marker = object()
128 try:
129 old = self.curframe.f_locals.get('cand', marker)
130 self.curframe.f_locals['cand'] = c
131 try:
132 return self._mygetval(expr, "oops")
133 except (KeyboardInterrupt, SystemExit, MemoryError):
134 raise
135 except:
136 raise self.GiveUp
137 finally:
138 if old is not marker:
139 self.curframe.f_locals['cand'] = old
140 else:
141 del self.curframe.f_locals['cand']
142 return flt
143
144 def do_finddescs(self, arg):
145 """finddescs kind expr [as var]
146 find annotation descs of kind (ClassDesc|FuncionDesc|...)
147 for which expr is true, cand in it referes to
148 the candidate desc; the result list is assigned to var or _."""
149 expr, var = self._parse_modif(arg)
150 kind, expr = expr.split(None, 1)
151 flt = self._make_flt(expr)
152 if flt is None:
153 return
154 from rpython.annotator import description
155 kind_cls = getattr(description, kind, None)
156 if kind_cls is None:
157 kind = kind.title()+'Desc'
158 kind_cls = getattr(description, kind, None)
159 if kind_cls is None:
160 return
161
162 descs = []
163 try:
164 for c in self.translator.annotator.bookkeeper.descs.itervalues():
165 if isinstance(c, kind_cls) and flt(c):
166 descs.append(c)
167 except self.GiveUp:
168 return
169 self._setvar(var, descs)
170
171 def do_showg(self, arg):
172 """showg obj
173 show graph for obj, obj can be an expression or a dotted name
174 (in which case prefixing with some packages in pypy is tried (see help pypyprefixes)).
175 if obj is a function or method, the localized call graph is shown;
176 if obj is a class or ClassDef the class definition graph is shown"""
177 from rpython.annotator.classdesc import ClassDef
178 from rpython.translator.tool import graphpage
179 translator = self.translator
180 obj = self._getobj(arg)
181 if obj is None:
182 return
183 if hasattr(obj, 'im_func'):
184 obj = obj.im_func
185 if isinstance(obj, types.FunctionType):
186 page = graphpage.LocalizedCallGraphPage(translator, self._allgraphs(obj))
187 elif isinstance(obj, FunctionGraph):
188 page = graphpage.FlowGraphPage(translator, [obj])
189 elif isinstance(obj, (type, types.ClassType)):
190 classdef = self._getcdef(obj)
191 if classdef is None:
192 return
193 page = graphpage.ClassDefPage(translator, classdef)
194 elif isinstance(obj, ClassDef):
195 page = graphpage.ClassDefPage(translator, obj)
196 else:
197 print("*** Nothing to do")
198 return
199 self._show(page)
200
201 def do_findv(self, varname):
202 """ findv [varname]
203 find a stack frame that has a certain variable (the default is "graph")
204 """
205 if not varname:
206 varname = "graph"
207 printfr = self.print_stack_entry
208 self.print_stack_entry = lambda *args: None
209 try:
210 num = 0
211 while self.curindex:
212 frame = self.curframe
213 if varname in frame.f_locals:
214 printfr(self.stack[self.curindex])
215 print("%s = %s" % (varname, frame.f_locals[varname]))
216 return
217 num += 1
218 self.do_up(None)
219 print("no %s found" % (varname, ))
220 for i in range(num):
221 self.do_down(None)
222 finally:
223 del self.print_stack_entry
224
225 def _attrs(self, arg, pr):
226 arg, expr = self._parse_modif(arg, 'match')
227 if expr == '_':
228 expr = 'True'
229 obj = self._getobj(arg)
230 if obj is None:
231 return
232 try:
233 obj = list(obj)
234 except:
235 obj = [obj]
236 clsdefs = []
237 for x in obj:
238 if isinstance(x, (type, types.ClassType)):
239 cdef = self._getcdef(x)
240 if cdef is None:
241 continue
242 clsdefs.append(cdef)
243 else:
244 clsdefs.append(x)
245
246 def longname(c):
247 return c.name
248 clsdefs.sort(lambda x,y: cmp(longname(x), longname(y)))
249 flt = self._make_flt(expr)
250 if flt is None:
251 return
252 for cdef in clsdefs:
253 try:
254 attrs = [a for a in cdef.attrs.itervalues() if flt(a)]
255 except self.GiveUp:
256 return
257 if attrs:
258 print("%s:" % cdef.name)
259 pr(attrs)
260
261 def do_attrs(self, arg):
262 """attrs obj [match expr]
263 list annotated attrs of class|def obj or list of classe(def)s obj,
264 obj can be an expression or a dotted name
265 (in which case prefixing with some packages in pypy is tried (see help pypyprefixes));
266 expr is an optional filtering expression; cand in it refer to the candidate Attribute
267 information object, which has a .name and .s_value."""
268 def pr(attrs):
269 print(" " + ' '.join([a.name for a in attrs]))
270 self._attrs(arg, pr)
271
272 def do_attrsann(self, arg):
273 """attrsann obj [match expr]
274 list with their annotation annotated attrs of class|def obj or list of classe(def)s obj,
275 obj can be an expression or a dotted name
276 (in which case prefixing with some packages in pypy is tried (see help pypyprefixes));
277 expr is an optional filtering expression; cand in it refer to the candidate Attribute
278 information object, which has a .name and .s_value."""
279 def pr(attrs):
280 for a in attrs:
281 print(' %s %s' % (a.name, a.s_value))
282 self._attrs(arg, pr)
283
284 def do_readpos(self, arg):
285 """readpos obj attrname [match expr] [as var]
286 list the read positions of annotated attr with attrname of class or classdef obj,
287 obj can be an expression or a dotted name
288 (in which case prefixing with some packages in pypy is tried (see help pypyprefixes));
289 expr is an optional filtering expression; cand in it refer to the candidate read
290 position information, which has a .func (which can be None), a .graph and .block and .i;
291 the list of the read positions functions is set to var or _."""
292 class Pos:
293 def __init__(self, graph, func, block, i):
294 self.graph = graph
295 self.func = func
296 self.block = block
297 self.i = i
298 arg, var = self._parse_modif(arg, 'as')
299 arg, expr = self._parse_modif(arg, 'match')
300 if expr == '_':
301 expr = 'True'
302 args = arg.split()
303 if len(args) != 2:
304 print("*** expected obj attrname:", arg)
305 return
306 arg, attrname = args
307 # allow quotes around attrname
308 if (attrname.startswith("'") and attrname.endswith("'")
309 or attrname.startswith('"') and attrname.endswith('"')):
310 attrname = attrname[1:-1]
311
312 obj = self._getobj(arg)
313 if obj is None:
314 return
315 if isinstance(obj, (type, types.ClassType)):
316 obj = self._getcdef(obj)
317 if obj is None:
318 return
319 bk = self.translator.annotator.bookkeeper
320 attrs = obj.attrs
321 if attrname not in attrs:
322 print("*** bogus:", attrname)
323 return
324 pos = bk.getattr_locations(obj.classdesc, attrname)
325 if not pos:
326 return
327 flt = self._make_flt(expr)
328 if flt is None:
329 return
330 r = {}
331 try:
332 for p in pos:
333 graph, block, i = p
334 if hasattr(graph, 'func'):
335 func = graph.func
336 else:
337 func = None
338 if flt(Pos(graph, func, block, i)):
339 if func is not None:
340 print(func.__module__ or '?', func.__name__, block, i)
341 else:
342 print(graph, block, i)
343 if i >= 0:
344 op = block.operations[i]
345 print(" ", op)
346 print(" ", end=" ")
347 for arg in op.args:
348 print("%s: %s" % (arg, self.translator.annotator.binding(arg)), end=" ")
349 print()
350
351 r[func] = True
352 except self.GiveUp:
353 return
354 self._setvar(var, r.keys())
355
356
357 def do_flowg(self, arg):
358 """flowg obj
359 show flow graph for function obj, obj can be an expression or a dotted name
360 (in which case prefixing with some packages in pypy is tried (see help pypyprefixes))"""
361 from rpython.translator.tool import graphpage
362 obj = self._getobj(arg)
363 if obj is None:
364 return
365 if hasattr(obj, 'im_func'):
366 obj = obj.im_func
367 if isinstance(obj, types.FunctionType):
368 graphs = self._allgraphs(obj)
369 elif isinstance(obj, FunctionGraph):
370 graphs = [obj]
371 else:
372 print("*** Not a function")
373 return
374 self._show(graphpage.FlowGraphPage(self.translator, graphs))
375
376 def _allgraphs(self, func):
377 graphs = {}
378 funcdesc = self.translator.annotator.bookkeeper.getdesc(func)
379 for graph in funcdesc._cache.itervalues():
380 graphs[graph] = True
381 for graph in self.translator.graphs:
382 if getattr(graph, 'func', None) is func:
383 graphs[graph] = True
384 return graphs.keys()
385
386
387 def do_callg(self, arg):
388 """callg obj
389 show localized call-graph for function obj, obj can be an expression or a dotted name
390 (in which case prefixing with some packages in pypy is tried (see help pypyprefixes))"""
391 from rpython.translator.tool import graphpage
392 obj = self._getobj(arg)
393 if obj is None:
394 return
395 if hasattr(obj, 'im_func'):
396 obj = obj.im_func
397 if isinstance(obj, types.FunctionType):
398 graphs = self._allgraphs(obj)
399 elif isinstance(obj, FunctionGraph):
400 graphs = [obj]
401 else:
402 print("*** Not a function")
403 return
404 self._show(graphpage.LocalizedCallGraphPage(self.translator, graphs))
405
406 def do_classhier(self, arg):
407 """classhier
408 show class hierarchy graph"""
409 from rpython.translator.tool import graphpage
410 self._show(graphpage.ClassHierarchyPage(self.translator))
411
412 def do_callgraph(self, arg):
413 """callgraph
414 show the program's call graph"""
415 from rpython.translator.tool import graphpage
416 self._show(graphpage.TranslatorPage(self.translator, 100))
417
418 def do_interact(self, arg):
419 """invoke a code.py sub prompt"""
420 ns = self.curframe.f_globals.copy()
421 ns.update(self.curframe.f_locals)
422 code.interact("*interactive*", local=ns)
423
424 def help_graphs(self):
425 print("graph commands are: callgraph, showg, flowg, callg, classhier")
426
427 def help_ann_other(self):
428 print("other annotation related commands are: find, finddescs, attrs, attrsann, readpos")
429
430 def help_pypyprefixes(self):
431 print("these prefixes are tried for dotted names in graph commands:")
432 print(self.TRYPREFIXES)
433
434 # start helpers
435 def start(self, tb):
436 if tb is None:
437 fn, args = self.set_trace, ()
438 else:
439 fn, args = self.post_mortem, (tb,)
440 try:
441 t = self.translator # define enviroments, xxx more stuff
442 exec("")
443 locals().update(self.exposed)
444 fn(*args)
445 pass # for debugger to land
446 except bdb.BdbQuit:
447 pass
448
449
450 def pdbcatch(f):
451 "A decorator that throws you in a pdbplus if the given function raises."
452 from rpython.tool.sourcetools import func_with_new_name
453 def wrapper(*args, **kwds):
454 try:
455 return f(*args, **kwds)
456 except:
457 import sys
458 PdbPlusShow(None).post_mortem(sys.exc_info()[2])
459 raise
460 wrapper = func_with_new_name(wrapper, f.__name__)
461 return wrapper