Debian Codegraph @

src/tools/ClassGraph.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 # Copyright (c) 2010 Anil Kumar
4 # All rights reserved.
5 #
6 # License: BSD
7
8 import sys
9 import subprocess
10 import os
11 import re
12
13 class CtagsInhCache:
14 def __init__(self, is_base, is_fq, is_debug):
15 self.cit_cache = {}
16 self.is_base = is_base
17 self.is_fq = is_fq
18 self.is_debug = False
19
20 self.ct_opt_I_file = os.getenv('SEASCOPE_CTAGS_OPT_I_FILE')
21 if self.ct_opt_I_file:
22 if not os.path.isfile(self.ct_opt_I_file):
23 self.ct_opt_I_file = None
24
25 map = os.getenv('SEASCOPE_CTAGS_SUFFIX_CMD_MAP', 0)
26 if map:
27 try:
28 map = eval(map)
29 except:
30 print('SEASCOPE_CTAGS_SUFFIX_CMD_MAP has errors')
31 map = None
32 self.ct_custom_map = map
33
34
35 def _filterCtInherits(self, data, sym=None):
36 res = {}
37 for line in data:
38 if line == '':
39 continue
40 line = line.split('\t', 4)
41 if len(line) == 4:
42 continue
43 _sd = dict([ x.split(':', 1) for x in line[4].split('\t')])
44 if 'inherits' not in _sd:
45 continue
46 sd = _sd['inherits'].strip()
47 if sd == '':
48 continue
49 if 'class' in _sd:
50 cls = _sd['class'].strip()
51 else:
52 cls = None
53 if line[1] not in res:
54 res[line[1]] = []
55 res[line[1]].append([line[0], sd, cls])
56 if self.is_debug:
57 print(line[0], line[1], sd, cls)
58 return res
59
60 def _runCtagsCustom(self, fl):
61 if not self.ct_custom_map:
62 return []
63 cmd_list = []
64 for (suffix, cmd) in self.ct_custom_map:
65 _fl = [ f for f in fl if f.endswith(suffix) ]
66 args = cmd.split()
67 args += _fl
68 cmd_list.append(args)
69
70 if not len(cmd_list):
71 return []
72
73 out_data_all = []
74 for args in cmd_list:
75 proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
76 (out_data, err_data) = proc.communicate('\n'.join(fl).encode())
77 out_data = out_data.decode()
78 out_data = re.split(r'\r?\n', out_data)
79 out_data_all += out_data
80 return out_data_all
81
82 def _runCtags(self, fl):
83 cmd = 'ctags -n -u --fields=+i -L - -f -'
84 if self.ct_opt_I_file:
85 cmd += ' -I ' + self.ct_opt_I_file
86 args = cmd.split()
87 proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
88 (out_data, err_data) = proc.communicate('\n'.join(fl).encode())
89 out_data = out_data.decode()
90 out_data = re.split(r'\r?\n', out_data)
91 out_data += self._runCtagsCustom(fl)
92 return out_data
93
94 def runCtagsInh(self, fl):
95 data = self._runCtags(fl)
96 ct_dict = self._filterCtInherits(data, None)
97 for f in fl:
98 if f not in ct_dict:
99 ct_dict[f] = []
100 return ct_dict
101
102 def ctInhInfo(self, flist):
103 fl = [ f for f in flist if f not in self.cit_cache ]
104 #print len(fl), len(flist), len(self.cit_cache)
105 if len(fl):
106 ct_dict = self.runCtagsInh(fl)
107 self.cit_cache.update(ct_dict)
108 res = []
109 for f in flist:
110 res += self.cit_cache[f]
111 return res
112
113 class ClassGraphGenerator:
114 def __init__(self, d, pcmd=None, wlimit=5000, is_base=False):
115 self.wdir = d;
116 self.pcmd = pcmd
117 self.width_limit = wlimit;
118 self.dname = None
119 self.dirCtInhInfo = None
120 self.graphRules = []
121 self.visitedRules = {}
122 self.visitedSym = {}
123 if is_base:
124 self.visitedSym = {'object' : 1}
125 if os.getenv('SEASCOPE_CTAGS_SUFFIX_CMD_MAP', 0):
126 for c in [ 'Entity', 'Type', 'PtrInterFace','Enum','Nominal' ]:
127 self.visitedSym[c] = 1
128 self.visitedSym['Tac::' + c] = 1
129 self.is_base = is_base
130 self.is_fq = False
131 self.is_debug = os.getenv('SEASCOPE_CLASS_GRAPH_DEBUG', 0)
132 self.cic = CtagsInhCache(self.is_base, self.is_fq, self.is_debug)
133
134 def addGraphRule(self, sym, d):
135 if (sym, d) in self.visitedRules:
136 return
137 self.visitedRules[(sym, d)] = True
138 self.graphRules.append([sym, d])
139
140 def refFiles(self, sym):
141 args = list(self.pcmd) + [sym]
142 try:
143 # In python >= 2.7 can use subprocess.check_output
144 # output = subprocess.check_output(args, cwd=self.wdir)
145 proc = subprocess.Popen(args, cwd=self.wdir, stdout=subprocess.PIPE)
146 (output, err_data) = proc.communicate()
147 output = output.decode()
148 output = re.split(r'\r?\n', output)
149 except Exception as e:
150 print('dir:', self.wdir, ':cmd:', args, ':', e, '\n', file=sys.stderr)
151 sys.exit(-1)
152 res = set()
153 for line in output:
154 if line == '':
155 continue
156 f = line.split(':', 1)[0]
157 f = os.path.normpath(os.path.join(self.wdir, f))
158 res.add(f)
159 return res
160
161 def parseCtagsInherits(self, data, sym=None):
162 res = []
163 for line in data:
164 sd = line[1]
165 if sd == '':
166 continue
167 sd = sd.split(',')
168 if self.is_fq:
169 dd = [ x.strip() for x in sd ]
170 cls = line[2]
171 else:
172 dd = [ re.split(r'::|\.', x.strip())[-1] for x in sd ]
173 cls = None
174 if not sym:
175 res.append([line[0], dd])
176 continue
177 if self.is_base:
178 if cls:
179 if sym == cls + "::" + line[0]:
180 res += dd
181 if sym == cls + "." + line[0]:
182 res += dd
183 else:
184 if sym == line[0]:
185 res += dd
186 else:
187 if sym in dd:
188 if cls:
189 sep = '::'
190 if '.' in cls:
191 sep = '.'
192 res.append(cls + sep + line[0])
193 else:
194 res.append(line[0])
195 if self.is_debug:
196 if sym:
197 print(sym, res)
198 return res
199
200
201 def classHierarchy(self, sym):
202 if self.is_fq:
203 subSym = re.split(r'::|\.', sym)[-1]
204 else:
205 subSym = sym
206
207 if self.pcmd:
208 fl = self.refFiles(subSym)
209 data = self.cic.ctInhInfo(fl)
210 else:
211 data = self.dirCtInhInfo
212
213 res = self.parseCtagsInherits(data, sym)
214 return res
215
216 def runCtInhForDir(self, dname):
217 self.dname = dname
218 fl = []
219 for root, dirs, files in os.walk(dname, followlinks=True):
220 fl += [os.path.join(root, f) for f in files]
221 self.dirCtInhInfo = self.cic.ctInhInfo(fl)
222
223 def classHierarchyRecursive(self, symList):
224 for sym in symList:
225 if sym in self.visitedSym:
226 continue
227 self.visitedSym[sym] = 1
228
229 dclasses = self.classHierarchy(sym)
230 if len(dclasses):
231 if len(dclasses) > self.width_limit:
232 if is_base:
233 s = 'base'
234 else:
235 s= 'derived'
236 print('num %s classes(%s) = %d, truncating to %d.\n' % (s, sym, len(dclasses), self.width_limit), file=sys.stderr)
237 dclasses = dclasses[0:self.width_limit]
238 self.addGraphRule(sym, '...(%s)' % sym)
239 for d in dclasses:
240 self.addGraphRule(sym, d)
241 self.classHierarchyRecursive(dclasses)
242
243 def classHierarchyForDir(self, dname):
244 res = self.parseCtagsInherits(self.dirCtInhInfo)
245 for (d, blist) in res:
246 for b in blist:
247 self.addGraphRule(b, d)
248
249 def prepareDotInput(self, sym_or_dname):
250 if len(self.graphRules) == 0:
251 if is_base:
252 s = 'base'
253 else:
254 s= 'derived'
255 print('No %s classes for %s\n' % (s, sym_or_dname), file=sys.stderr)
256 sys.exit(0)
257 dotInput = 'digraph "%s" {\n' % sym_or_dname
258 if not sym_or_dname:
259 dotInput += '\t"%s" [style=bold];\n' % sym_or_dname
260 for r in self.graphRules:
261 if not self.is_base:
262 dotInput += '\t"%s" -> "%s";\n' % (r[0], r[1])
263 else:
264 dotInput += '\t"%s" -> "%s";\n' % (r[1], r[0])
265 dotInput += '}\n'
266 return dotInput
267
268 def saveDotFile(self, sym, dotInput):
269 f = open(sym + '.dot', 'w')
270 f.write(dotInput)
271 f.close()
272
273 def saveSvgFile(sym, svg_data):
274 dot_svg = sym + '.svg'
275 f = open(dot_svg, 'w')
276 f.write(svg_data)
277 f.close()
278
279 print('saved', dot_svg, '\n', file=sys.stderr)
280
281 def generateGraph(self, dname, sym=None):
282 if not self.pcmd:
283 self.runCtInhForDir(dname)
284 if sym:
285 if sym == '::' or sym == '.':
286 return
287 if re.search(r'::|\.', sym):
288 self.is_fq = True
289 if sym.startswith('::') or sym.startswith('.'):
290 sym = re.split(r'::|\.', sym, maxsplit=1)[-1]
291 self.classHierarchyRecursive([sym])
292 dotInput = self.prepareDotInput(sym)
293 else:
294 self.classHierarchyForDir(dname)
295 dotInput = self.prepareDotInput(dname)
296
297 if self.is_debug:
298 print(dotInput)
299 return ''
300 #self.saveDotFile(sym, dotInput)
301
302 args = ['dot', '-Tsvg']
303 try:
304 p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
305 (svg_data, err_data) = p.communicate(dotInput.encode())
306 svg_data = svg_data.decode()
307 if err_data and err_data.decode() != '':
308 print(err_data, '\n', file=sys.stderr)
309 #self.saveSvgFile(sym, svg_data)
310 return svg_data
311 except Exception as e:
312 print('Failed to run:', ' '.join(args), '\n', file=sys.stderr)
313 print(e, '\n', file=sys.stderr)
314
315
316 if __name__ == '__main__':
317 import optparse
318 usage = "usage: %prog [options] (-d <code_dir/file> | -t <prj_type>) [symbol]"
319 op = optparse.OptionParser(usage=usage)
320 op.add_option("-b", action="store_true", dest="is_base", help="Show base classes")
321 op.add_option("-d", "--codedir", dest="code_dir", help="Code dir", metavar="CODE_DIR")
322 op.add_option("-t", "--type", dest="prj_type", help="project type: idutils|gtags|cscope", metavar="PRJ_TYPE")
323 (options, args) = op.parse_args()
324
325 # dname
326 if not options.code_dir:
327 print('Specify -d', file=sys.stderr)
328 sys.exit(-1)
329 dname = options.code_dir
330 if not os.path.exists(dname):
331 print('"%s": does not exist' % dname, file=sys.stderr)
332 sys.exit(-2)
333 wdir = dname
334 if not os.path.isdir(wdir):
335 wdir = os.path.dirname(wdir)
336
337 # sym
338 sym = None
339 if len(args):
340 if len(args) != 1:
341 print('Please specify only one symbol', file=sys.stderr)
342 sys.exit(-3)
343 sym = args[0]
344
345 # ptype
346 ptype = options.prj_type
347 if ptype:
348 if not sym:
349 print('-t option needs sepficfying symbol', file=sys.stderr)
350 sys.exit(-4)
351 if not os.path.isdir(dname):
352 print('-t option needs codedir to be a directory', file=sys.stderr)
353 sys.exit(-5)
354 pcmd = None
355 if ptype and os.path.isdir(dname):
356 prj_list = [
357 ['idutils', 'ID', ['lid', '-R', 'grep', '--'] ],
358 ['gtags', 'GRTAGS', ['global', '-a', '--result=grep', '-x', '-r', '--'] ],
359 ['cscope', 'cscope.out', ['cscope', '-L', '-d', '-0', '--'] ],
360 ['grep', '', ['grep', '-R', '-n', '-I', '--',] ],
361 ]
362 for p in prj_list:
363 if p[0] == ptype:
364 if os.path.exists(os.path.join(dname, p[1])):
365 pcmd = p[2]
366 break
367 # is_base
368 is_base = options.is_base
369
370 # run
371 cgg = ClassGraphGenerator(wdir, pcmd=pcmd, is_base=is_base)
372 svg_data = cgg.generateGraph(dname, sym)
373
374 print(svg_data)