Debian Codegraph @

rpython/translator/tool/make_dot.py

raw symbols SCIP
1 import os
2 import inspect, linecache
3 from rpython.flowspace.model import *
4 from rpython.tool.udir import udir
5 from py.process import cmdexec
6 from rpython.tool.error import offset2lineno
7
8 class DotGen:
9
10 def __init__(self, graphname, rankdir=None):
11 self.graphname = safename(graphname)
12 self.lines = []
13 self.source = None
14 self.emit("digraph %s {" % self.graphname)
15 if rankdir:
16 self.emit('rankdir="%s"' % rankdir)
17
18 def generate(self, storedir=None, target='ps'):
19 source = self.get_source()
20 if target is None:
21 return source # unprocessed
22 if storedir is None:
23 storedir = udir
24 pdot = storedir.join('%s.dot' % self.graphname)
25 pdot.write(source)
26 ptarget = pdot.new(ext=target)
27 cmdexec('dot -T%s %s>%s' % (target, str(pdot),str(ptarget)))
28 return ptarget
29
30 def get_source(self):
31 if self.source is None:
32 self.emit("}")
33 self.source = '\n'.join(self.lines)
34 del self.lines
35 return self.source
36
37 def emit(self, line):
38 self.lines.append(line)
39
40 def enter_subgraph(self, name):
41 self.emit("subgraph %s {" % (safename(name),))
42
43 def leave_subgraph(self):
44 self.emit("}")
45
46 def emit_edge(self, name1, name2, label="",
47 style="dashed",
48 color="black",
49 dir="forward",
50 weight="5",
51 ports=None,
52 ):
53 d = locals()
54 attrs = [('%s="%s"' % (x, d[x].replace('"', '\\"').replace('\n', '\\n')))
55 for x in ['label', 'style', 'color', 'dir', 'weight']]
56 self.emit('edge [%s];' % ", ".join(attrs))
57 if ports:
58 self.emit('%s:%s -> %s:%s' % (safename(name1), ports[0],
59 safename(name2), ports[1]))
60 else:
61 self.emit('%s -> %s' % (safename(name1), safename(name2)))
62
63 def emit_node(self, name,
64 shape="diamond",
65 label="",
66 color="black",
67 fillcolor="white",
68 style="filled",
69 width="0.75",
70 ):
71 d = locals()
72 attrs = [('%s="%s"' % (x, d[x].replace('"', '\\"').replace('\n', '\\n')))
73 for x in ['shape', 'label', 'color', 'fillcolor', 'style', 'width']]
74 self.emit('%s [%s];' % (safename(name), ", ".join(attrs)))
75
76
77 TAG_TO_COLORS = {
78 "timeshifted": "#cfa5f0",
79 "portal": "#cfa5f0",
80 "PortalEntry": "#84abf0",
81 "PortalReentry": "#f084c2",
82 }
83 DEFAULT_TAG_COLOR = "#a5e6f0"
84 RETURN_COLOR = "green"
85 EXCEPT_COLOR = "#ffa000"
86
87 class FlowGraphDotGen(DotGen):
88 VERBOSE = False
89
90 def __init__(self, graphname, rankdir=None):
91 DotGen.__init__(self, graphname.replace('.', '_'), rankdir)
92
93 def emit_subgraph(self, name, node):
94 name = name.replace('.', '_') + '_'
95 self.blocks = {id(None): '(None)'}
96 self.func = None
97 self.prefix = name
98 self.enter_subgraph(name)
99 tagcolor = TAG_TO_COLORS.get(node.tag, DEFAULT_TAG_COLOR)
100 self.visit_FunctionGraph(node, tagcolor)
101 for block in safe_iterblocks(node):
102 self.visit_Block(block, tagcolor)
103 self.leave_subgraph()
104
105 def blockname(self, block):
106 i = id(block)
107 try:
108 return self.blocks[i]
109 except KeyError:
110 self.blocks[i] = name = "%s_%d" % (self.prefix, len(self.blocks))
111 return name
112
113 def visit_FunctionGraph(self, funcgraph, tagcolor):
114 name = self.prefix # +'_'+funcgraph.name
115 data = funcgraph.name
116 if getattr(funcgraph, 'source', None) is not None:
117 source = funcgraph.source
118 if self.VERBOSE:
119 data += "\\n"
120 else:
121 data = ""
122 data += "\\l".join(source.split('\n'))
123 if hasattr(funcgraph, 'func'):
124 self.func = funcgraph.func
125 self.emit_node(name, label=data, shape="box", fillcolor=tagcolor, style="filled")
126 if hasattr(funcgraph, 'startblock'):
127 self.emit_edge(name, self.blockname(funcgraph.startblock), 'startblock')
128
129 def visit_Block(self, block, tagcolor):
130 # do the block itself
131 name = self.blockname(block)
132 if not isinstance(block, Block):
133 data = "BROKEN BLOCK\\n%r" % (block,)
134 self.emit_node(name, label=data)
135 return
136
137 lines = []
138 for op in block.operations:
139 lines.extend(repr(op).split('\n'))
140 lines.append("")
141 numblocks = len(block.exits)
142 color = "black"
143 fillcolor = getattr(block, "blockcolor", "white")
144 if not numblocks:
145 shape = "box"
146 if len(block.inputargs) == 1:
147 lines[-1] += 'return %s' % tuple(block.inputargs)
148 fillcolor = RETURN_COLOR
149 elif len(block.inputargs) == 2:
150 lines[-1] += 'raise %s, %s' % tuple(block.inputargs)
151 fillcolor = EXCEPT_COLOR
152 elif numblocks == 1:
153 shape = "box"
154 else:
155 color = "red"
156 shape = "octagon"
157
158 if block.exitswitch is not None:
159 lines.append("exitswitch: %s" % (block.exitswitch,))
160
161 iargs = " ".join(map(repr, block.inputargs))
162 if self.VERBOSE:
163 if block.exc_handler:
164 eh = ' (EH)'
165 else:
166 eh = ''
167 data = "%s%s%s\\n" % (name, block.at(), eh)
168 else:
169 data = "%s\\n" % (name,)
170 data += "inputargs: %s\\n\\n" % (iargs,)
171 if self.VERBOSE and block.operations and self.func:
172 maxoffs = max([op.offset for op in block.operations])
173 if maxoffs >= 0:
174 minoffs = min([op.offset for op in block.operations
175 if op.offset >= 0])
176 minlineno = offset2lineno(self.func.__code__, minoffs)
177 maxlineno = offset2lineno(self.func.__code__, maxoffs)
178 filename = inspect.getsourcefile(self.func)
179 source = "\l".join([linecache.getline(filename, line).rstrip()
180 for line in range(minlineno, maxlineno+1)])
181 if minlineno == maxlineno:
182 data = data + r"line %d:\n%s\l\n" % (minlineno, source)
183 else:
184 data = data + r"lines %d-%d:\n%s\l\n" % (minlineno,
185 maxlineno, source)
186
187 data = data + "\l".join(lines)
188
189 self.emit_node(name, label=data, shape=shape, color=color, style="filled", fillcolor=fillcolor)
190
191 # do links/exits
192 for link in block.exits:
193 name2 = self.blockname(link.target)
194 label = " ".join(map(repr, link.args))
195 if link.exitcase is not None:
196 label = "%s: %s" %(repr(link.exitcase).replace('\\', '\\\\'), label)
197 self.emit_edge(name, name2, label, style="dotted", color="red")
198 else:
199 self.emit_edge(name, name2, label, style="solid")
200
201
202 def make_dot(graphname, graph, storedir=None, target='ps'):
203 return make_dot_graphs(graph.name, [(graphname, graph)], storedir, target)
204
205 def show_dot(graph, storedir = None, target = 'ps'):
206 name = graph.name
207 fn = make_dot(name, graph, storedir, target)
208 os.system('gv %s' % fn)
209
210 def make_dot_graphs(basefilename, graphs, storedir=None, target='ps'):
211 dotgen = FlowGraphDotGen(basefilename)
212 names = {basefilename: True}
213 for graphname, graph in graphs:
214 if graphname in names:
215 i = 2
216 while graphname + str(i) in names:
217 i += 1
218 graphname = graphname + str(i)
219 names[graphname] = True
220 dotgen.emit_subgraph(graphname, graph)
221 return dotgen.generate(storedir, target)
222
223 def _makecharmap():
224 result = {}
225 for i in range(256):
226 result[chr(i)] = '_%02X' % i
227 for c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789':
228 result[c] = c
229 result['_'] = '__'
230 return result
231 CHAR_MAP = _makecharmap()
232 del _makecharmap
233
234 def safename(name):
235 # turn a random string into something that is a valid dot identifier,
236 # avoiding invalid characters and prepending '_' to make sure it is
237 # not a keyword
238 name = ''.join([CHAR_MAP[c] for c in name])
239 return '_' + name