Debian Codegraph @

rpython/translator/tool/graphpage.py

raw symbols SCIP
1 from rpython.flowspace.model import Block, Link, FunctionGraph
2 from rpython.flowspace.model import safe_iterblocks, safe_iterlinks
3 from rpython.translator.tool.make_dot import DotGen, make_dot_graphs
4 from rpython.annotator.model import SomePBC
5 from rpython.annotator.description import MethodDesc
6 from rpython.annotator.classdesc import ClassDef
7 from rpython.tool.uid import uid
8 from rpython.tool.udir import udir
9
10 from dotviewer.graphpage import GraphPage as BaseGraphPage
11
12 class GraphPage(BaseGraphPage):
13 save_tmp_file = str(udir.join('graph.dot'))
14
15 class VariableHistoryGraphPage(GraphPage):
16 """ A GraphPage showing the history of variable bindings. """
17
18 def compute(self, translator, name, info, caused_by, history, func_names):
19 self.linkinfo = {}
20 self.translator = translator
21 self.func_names = func_names
22 dotgen = DotGen('binding')
23 label = "Most recent binding of %s\\n\\n%s" % (name, nottoowide(info))
24 if info.origin is not None:
25 label += "\\n" + self.createlink(info.origin, 'Originated at')
26 if caused_by is not None:
27 label += '\\n' + self.createlink(caused_by)
28
29 dotgen.emit_node('0', shape="box", color="red", label=label)
30 for n, (data, caused_by) in zip(range(len(history)), history):
31 label = nottoowide(data)
32 if data.origin is not None:
33 label += "\\n" + self.createlink(data.origin, 'Originated at')
34 if caused_by is not None:
35 label += '\\n' + self.createlink(caused_by)
36 dotgen.emit_node(str(n+1), shape="box", label=label)
37 dotgen.emit_edge(str(n+1), str(n))
38 self.source = dotgen.generate(target=None)
39
40 def createlink(self, position_key, wording='Caused by a call from'):
41 graph, block, pos = position_key
42 basename = self.func_names.get(graph, graph.name)
43 linkname = basename
44 n = 1
45 while self.linkinfo.get(linkname, position_key) != position_key:
46 n += 1
47 linkname = '%s_%d' % (basename, n)
48 self.linkinfo[linkname] = position_key
49 # It would be nice to get the block name somehow
50 blockname = block.__class__.__name__
51 self.links[linkname] = '%s, %s, position %r:\n%s' % (basename,
52 blockname, pos, block.operations[pos])
53 return '%s %s' % (wording, linkname)
54
55 def followlink(self, funcname):
56 graph, block, pos = self.linkinfo[funcname]
57 # It would be nice to focus on the block
58 return FlowGraphPage(self.translator, [graph], self.func_names)
59
60
61 def graphsof(translator, func):
62 if isinstance(func, (FunctionGraph, IncompleteGraph)):
63 return [func] # already a graph
64 graphs = []
65 if translator.annotator:
66 funcdesc = translator.annotator.bookkeeper.getdesc(func)
67 graphs = funcdesc._cache.values()
68 if not graphs:
69 # build a new graph, mark it as "to be returned to the annotator the
70 # next time it asks for a graph for the same function"
71 # (note that this buildflowgraph() call will return the same graph
72 # if called again, from the _prebuilt_graphs cache)
73 graph = translator.buildflowgraph(func)
74 translator._prebuilt_graphs[func] = graph
75 graphs = [graph]
76 return graphs
77
78
79 class FlowGraphPage(GraphPage):
80 """ A GraphPage showing a Flow Graph (or a few flow graphs).
81 """
82 def compute(self, translator, functions=None, func_names=None):
83 self.translator = translator
84 self.annotator = getattr(translator, 'annotator', None)
85 self.func_names = func_names or {}
86 if functions:
87 graphs = []
88 for func in functions:
89 graphs += graphsof(translator, func)
90 else:
91 graphs = self.translator.graphs
92 if not graphs and hasattr(translator, 'entrypoint'):
93 graphs = list(graphs)
94 graphs += graphsof(translator, translator.entrypoint)
95 gs = [(graph.name, graph) for graph in graphs]
96 gs.sort(lambda (_, g), (__ ,h): cmp(g.tag, h.tag))
97 if self.annotator and self.annotator.blocked_graphs:
98 for block, was_annotated in self.annotator.annotated.items():
99 if not was_annotated:
100 block.blockcolor = "red"
101 if graphs:
102 name = graphs[0].name+"_graph"
103 else:
104 name = 'no_graph'
105 self.source = make_dot_graphs(name, gs, target=None)
106 # make the dictionary of links -- one per annotated variable
107 self.current_value = {}
108
109 #from rpython.jit.hintannotator.annotator import HintAnnotator
110 #if isinstance(self.annotator, HintAnnotator):
111 # return
112
113 vars = {}
114 for graph in graphs:
115 for block in safe_iterblocks(graph):
116 if isinstance(block, Block):
117 for v in block.getvariables():
118 vars[v] = True
119 for link in safe_iterlinks(graph):
120 if isinstance(link, Link):
121 for v in link.getextravars():
122 vars[v] = True
123 for var in vars:
124 s_value = var.annotation
125 if s_value is not None:
126 info = '%s: %s' % (var.name, s_value)
127 annotationcolor = getattr(s_value, 'annotationcolor', None)
128 self.links[var.name] = info, annotationcolor
129 self.current_value[var.name] = s_value
130 if hasattr(var, 'concretetype'):
131 #info = self.links.get(var.name, var.name)
132 #info = '(%s) %s' % (var.concretetype, info)
133 info = str(var.concretetype)
134 if info == 'Void': # gray out Void variables
135 info = info, (160,160,160)
136 self.links[var.name] = info
137
138
139 class SingleGraphPage(FlowGraphPage):
140 """ A GraphPage showing a single precomputed FlowGraph."""
141
142 def compute(self, graph):
143 return FlowGraphPage.compute(self, None, [graph])
144
145
146 def nottoowide(text, width=72):
147 parts = str(text).split(' ')
148 lines = []
149 line = parts.pop(0)
150 for s in parts:
151 if len(line)+len(s) < width:
152 line = line + ' ' + s
153 else:
154 lines.append(line)
155 line = s
156 lines.append(line)
157 return '\\n'.join(lines)
158
159
160 class ClassDefPage(GraphPage):
161 """A GraphPage showing the attributes of a class.
162 """
163 def compute(self, translator, cdef):
164 self.translator = translator
165 dotgen = DotGen(cdef.shortname, rankdir="LR")
166
167 def writecdef(cdef):
168 lines = [cdef.name, '']
169 attrs = cdef.attrs.items()
170 attrs.sort()
171
172 def writeadefs(prefix, classattrs):
173 for name, attrdef in attrs:
174 if bool(attrdef.readonly) == bool(classattrs):
175 s_value = attrdef.s_value
176 linkname = name
177 info = s_value
178 if (classattrs and isinstance(s_value, SomePBC)
179 and s_value.getKind() == MethodDesc):
180 name += '()'
181 info = 'SomePBC(%s)' % ', '.join(
182 ['method %s.%s' % (
183 desc.originclassdef.shortname,
184 desc.name) for desc in s_value.descriptions],)
185 lines.append(name)
186 self.links[linkname] = '%s.%s: %s' % (prefix, name, info)
187
188 prefix = cdef.shortname
189 writeadefs(prefix + '()', False)
190 lines.append('')
191 writeadefs(prefix, True)
192 dotgen.emit_node(nameof(cdef), color="red", shape="box",
193 label='\n'.join(lines))
194
195 prevcdef = None
196 while cdef is not None:
197 writecdef(cdef)
198 if prevcdef:
199 dotgen.emit_edge(nameof(cdef), nameof(prevcdef), color="red")
200 prevcdef = cdef
201 cdef = cdef.basedef
202
203 self.source = dotgen.generate(target=None)
204
205 def followlink(self, name):
206 return self
207
208 class BaseTranslatorPage(GraphPage):
209 """Abstract GraphPage for showing some of the call graph between functions
210 and possibily the class hierarchy."""
211
212 def allgraphs(self):
213 return list(self.translator.graphs)
214
215 def graph_name(self, *args):
216 raise NotImplementedError
217
218 def compute(self, translator, *args, **kwds):
219 self.translator = translator
220 self.object_by_name = {}
221 self.name_by_object = {}
222 dotgen = DotGen(self.graph_name(*args))
223 dotgen.emit('mclimit=15.0')
224
225 self.do_compute(dotgen, *args, **kwds)
226
227 self.source = dotgen.generate(target=None)
228
229 # link the function names to the individual flow graphs
230 for name, obj in self.object_by_name.items():
231 if isinstance(obj, ClassDef):
232 data = repr(obj)
233 elif isinstance(obj, FunctionGraph):
234 graph = obj
235 data = graph.name
236 if hasattr(graph, 'func'):
237 data += ':%d' % graph.func.__code__.co_firstlineno
238 if hasattr(graph, 'source'):
239 data += '\n%s' % graph.source.split('\n', 1)[0]
240 else:
241 continue
242 self.links.setdefault(name, data)
243
244 def get_blocked_graphs(self, graphs):
245 translator = self.translator
246 blocked_graphs = {}
247 if translator.annotator:
248 # don't use translator.annotator.blocked_graphs here because
249 # it is not populated until the annotator finishes.
250 annotated = translator.annotator.annotated
251 for graph in graphs:
252 for block in graph.iterblocks():
253 if annotated.get(block) is False:
254 blocked_graphs[graph] = True
255 return blocked_graphs
256
257 def compute_class_hieararchy(self, dotgen):
258 # show the class hierarchy
259 if self.translator.annotator:
260 dotgen.emit_node(nameof(None), color="red", shape="octagon",
261 label="Root Class\\nobject")
262 for classdef in self.translator.annotator.getuserclassdefinitions():
263 data = self.labelof(classdef, classdef.shortname)
264 dotgen.emit_node(nameof(classdef), label=data, shape="box")
265 dotgen.emit_edge(nameof(classdef.basedef), nameof(classdef))
266
267 def labelof(self, obj, objname):
268 name = objname
269 i = 1
270 while name in self.object_by_name:
271 i += 1
272 name = '%s__%d' % (objname, i)
273 self.object_by_name[name] = obj
274 self.name_by_object[obj] = name
275 return name
276
277 def followlink(self, name):
278 if name.endswith('...'):
279 obj = self.object_by_name[name]
280 return LocalizedCallGraphPage(self.translator, [obj])
281 obj = self.object_by_name[name]
282 if isinstance(obj, ClassDef):
283 return ClassDefPage(self.translator, obj)
284 else:
285 return FlowGraphPage(self.translator, [obj], self.name_by_object)
286
287 class TranslatorPage(BaseTranslatorPage):
288 """A GraphPage showing a the call graph between functions
289 as well as the class hierarchy."""
290
291 def graph_name(self, huge=0):
292 return 'translator'
293
294 def do_compute(self, dotgen, huge=100, center_graph=None):
295 translator = self.translator
296
297 # show the call graph
298 callgraph = translator.callgraph.values()
299 graphs = self.allgraphs()
300
301 if len(graphs) > huge:
302 assert graphs, "no graph to show!"
303 graphs = [center_graph or graphs[0]]
304 LocalizedCallGraphPage.do_compute.im_func(self, dotgen, graphs)
305 return
306
307 blocked_graphs = self.get_blocked_graphs(graphs)
308
309 highlight_graphs = getattr(translator, 'highlight_graphs', {}) # XXX
310 dotgen.emit_node('entry', fillcolor="green", shape="octagon",
311 label="Translator\\nEntry Point")
312 for graph in graphs:
313 data = self.labelof(graph, graph.name)
314 if graph in blocked_graphs:
315 kw = {'fillcolor': 'red'}
316 elif graph in highlight_graphs:
317 kw = {'fillcolor': '#ffcccc'}
318 else:
319 kw = {}
320 dotgen.emit_node(nameof(graph), label=data, shape="box", **kw)
321 if graphs:
322 dotgen.emit_edge('entry', nameof(graphs[0]), color="green")
323 for g1, g2 in callgraph: # captured above (multithreading fun)
324 dotgen.emit_edge(nameof(g1), nameof(g2))
325
326 # show the class hierarchy
327 self.compute_class_hieararchy(dotgen)
328
329
330 class LocalizedCallGraphPage(BaseTranslatorPage):
331 """A GraphPage showing the localized call graph for a function,
332 that means just including direct callers and callees"""
333
334 def graph_name(self, centers):
335 if centers:
336 return 'LCG_%s' % nameof(centers[0])
337 else:
338 return 'EMPTY'
339
340 def do_compute(self, dotgen, centers):
341 centers = dict.fromkeys(centers)
342
343 translator = self.translator
344
345 graphs = {}
346
347 for g1, g2 in translator.callgraph.values():
348 if g1 in centers or g2 in centers:
349 graphs[g1] = True
350 graphs[g2] = True
351
352 # show all edges that exist between these graphs
353 for g1, g2 in translator.callgraph.values():
354 if g1 in graphs and g2 in graphs:
355 dotgen.emit_edge(nameof(g1), nameof(g2))
356
357 graphs = graphs.keys()
358
359 # show the call graph
360 blocked_graphs = self.get_blocked_graphs(graphs)
361
362 highlight_graphs = getattr(translator, 'highlight_graphs', {}) # XXX
363 for graph in graphs:
364 data = self.labelof(graph, graph.name)
365 if graph in blocked_graphs:
366 kw = {'fillcolor': 'red'}
367 elif graph in highlight_graphs:
368 kw = {'fillcolor': '#ffcccc'}
369 else:
370 kw = {}
371 dotgen.emit_node(nameof(graph), label=data, shape="box", **kw)
372
373 if graph not in centers:
374 lcg = 'LCG_%s' % nameof(graph)
375 label = data+'...'
376 dotgen.emit_node(lcg, label=label)
377 dotgen.emit_edge(nameof(graph), lcg)
378 self.links[label] = 'go to its localized call graph'
379 self.object_by_name[label] = graph
380
381 class ClassHierarchyPage(BaseTranslatorPage):
382 """A GraphPage showing the class hierarchy."""
383
384 def graph_name(self):
385 return 'class_hierarchy'
386
387 def do_compute(self, dotgen):
388 # show the class hierarchy
389 self.compute_class_hieararchy(dotgen)
390
391 def nameof(obj, cache={}):
392 # NB. the purpose of the cache is not performance, but to ensure that
393 # two objects that compare equal get the same name
394 try:
395 return cache[obj]
396 except KeyError:
397 result = '%s__0x%x' % (getattr(obj, '__name__', ''), uid(obj))
398 cache[obj] = result
399 return result
400
401 # ____________________________________________________________
402 #
403 # Helpers to try to show a graph when we only have a Block or a Link
404
405 def try_show(obj):
406 if isinstance(obj, FunctionGraph):
407 obj.show()
408 return obj
409 elif isinstance(obj, Link):
410 return try_show(obj.prevblock)
411 elif isinstance(obj, Block):
412 graph = obj._slowly_get_graph()
413 if isinstance(graph, FunctionGraph):
414 graph.show()
415 return graph
416 graph = IncompleteGraph(graph)
417 SingleGraphPage(graph).display()
418 else:
419 raise TypeError("try_show(%r object)" % (type(obj).__name__,))
420
421 def try_get_functiongraph(obj):
422 if isinstance(obj, FunctionGraph):
423 obj.show()
424 elif isinstance(obj, Link):
425 try_show(obj.prevblock)
426 elif isinstance(obj, Block):
427 import gc
428 pending = [obj] # pending blocks
429 seen = {obj: True, None: True}
430 for x in pending:
431 for y in gc.get_referrers(x):
432 if isinstance(y, FunctionGraph):
433 return y
434 elif isinstance(y, Link):
435 block = y.prevblock
436 if block not in seen:
437 pending.append(block)
438 seen[block] = True
439 return pending
440 else:
441 raise TypeError("try_get_functiongraph(%r object)" % (type(obj).__name__,))
442
443 class IncompleteGraph:
444 name = '(incomplete graph)'
445 tag = None
446
447 def __init__(self, bunch_of_blocks):
448 self.bunch_of_blocks = bunch_of_blocks
449
450 def iterblocks(self):
451 return iter(self.bunch_of_blocks)