Debian Codegraph @

pypy/tool/importfun.py

raw symbols SCIP
1 import sys
2 import opcode
3 import dis
4 import imp
5 import os
6 import __builtin__
7 import time
8
9 """
10 so design goal:
11
12 i want to take a pile of source code and analyze each module for the
13 names it defines and the modules it imports and the names it uses from
14 them.
15
16 then i can find things like:
17
18 - things which are just plain not used anywhere
19 - things which are defined in one module and only used in another
20 - importing of names from modules where they are just imported from
21 somewhere else
22 - cycles in the import graph
23 - unecessary imports
24
25 finding imports at top level is fairly easy, although the variety of
26 types of import statement can be baffling. a mini reference:
27
28 import foo
29
30 ->
31
32 LOAD_CONST None
33 IMPORT_NAME foo
34 STORE_NAME foo
35
36
37 import foo as bar
38
39 ->
40
41 LOAD_CONST None
42 IMPORT_NAME foo
43 STORE_NAME bar
44
45 from foo import bar
46
47 ->
48
49 LOAD_CONST ('bar',)
50 IMPORT_NAME foo
51 IMPORT_FROM bar
52 STORE_NAME bar
53 POP_TOP
54
55 from foo import bar, baz
56
57 ->
58
59 LOAD_CONST ('bar','baz')
60 IMPORT_NAME foo
61 IMPORT_FROM bar
62 STORE_NAME bar
63 IMPORT_FROM baz
64 STORE_NAME baz
65 POP_TOP
66
67 from foo.baz import bar
68
69 ->
70
71 LOAD_CONST ('bar',)
72 IMPORT_NAME foo.baz
73 IMPORT_FROM bar
74 STORE_NAME bar
75 POP_TOP
76
77
78 import foo.bar
79
80 ->
81
82 LOAD_CONST None
83 IMPORT_NAME foo.bar
84 STORE_NAME foo
85
86 (I hate this style)
87
88 there are other forms, but i don't support them (should hit an
89 assertion rather than silently fail).
90
91 """
92
93 class System:
94 def __init__(self):
95 self.modules = {}
96 self.pendingmodules = {}
97
98 class Scope(object):
99 def __init__(self, parent=None):
100 self.modvars = {} # varname -> absolute module name
101 self.parent = parent
102 self.varsources = {}
103
104 def mod_for_name(self, name):
105 if name in self.modvars:
106 return self.modvars[name]
107 elif self.parent is not None:
108 return self.parent.mod_for_name(name)
109 else:
110 return None
111
112 def var_source(self, name):
113 if name in self.varsources:
114 return self.varsources[name]
115 elif self.parent is not None:
116 return self.parent.var_source(name)
117 else:
118 return None, None
119
120
121 class Module(object):
122 def __init__(self, name, system):
123 self.name = name
124 self.system = system
125 self._imports = {} # {modname:{name:was-it-used?}}
126 self.definitions = ['__file__']
127 if name == 'pypy.objspace.std.objspace':
128 self.definitions.extend([
129 'W_NoneObject', 'W_BoolObject', 'W_BoolObject', 'W_TypeObject',
130 'W_TypeObject', 'W_TypeObject', 'W_IntObject',
131 'W_StringObject', 'W_UnicodeObject', 'W_FloatObject',
132 'W_TupleObject', 'W_ListObject', 'W_LongObject', 'W_SliceObject',
133 'W_IntObject', 'W_FloatObject', 'W_LongObject', 'W_TupleObject',
134 'W_ListObject', 'W_DictObject', 'W_SliceObject',
135 'W_StringObject', 'W_UnicodeObject', 'W_SeqIterObject',
136 'W_TupleObject', 'W_DictObject', 'W_DictObject'])
137 self.toplevelscope = Scope()
138 self.importers = []
139 def import_(self, modname):
140 # should probably handle relative imports here.
141 if modname not in self._imports:
142 if recursive and modname not in self.system.modules:
143 self.system.pendingmodules[modname] = None
144 self._imports[modname] = {}
145 return self._imports[modname]
146
147 def iteropcodes(codestring):
148 n = len(codestring)
149 i = 0
150 while i < n:
151 op = ord(codestring[i])
152 i += 1
153 oparg = None
154 assert op != opcode.EXTENDED_ARG, 'EXTENDED_ARG'
155 if op >= opcode.HAVE_ARGUMENT:
156 oparg = ord(codestring[i]) + ord(codestring[i+1])*256
157 i += 2
158 yield op, oparg
159
160
161 class _Op(object):
162 def __getattr__(self, name):
163 if name in opcode.opmap:
164 return opcode.opmap[name]
165 else:
166 raise AttributeError(name)
167
168 _op_ = _Op()
169
170
171 loadops = [_op_.LOAD_NAME, _op_.LOAD_GLOBAL, _op_.LOAD_FAST, _op_.LOAD_DEREF]
172 storeops = [_op_.STORE_NAME, _op_.STORE_FAST, _op_.STORE_DEREF, _op_.STORE_GLOBAL]
173
174 def name_for_op(code, op, oparg):
175 if op in [_op_.LOAD_GLOBAL, _op_.STORE_GLOBAL, _op_.LOAD_NAME, _op_.STORE_NAME]:
176 return code.co_names[oparg]
177 elif op in [_op_.LOAD_FAST, _op_.STORE_FAST]:
178 return code.co_varnames[oparg]
179 elif op in [_op_.LOAD_DEREF, _op_.STORE_DEREF]:
180 if oparg < len(code.co_cellvars):
181 return code.co_cellvars[oparg]
182 else:
183 return code.co_freevars[oparg - len(code.co_cellvars)]
184 else:
185 assert 0, "%s is not an opcode with a name!"%(opcode.opname[op],)
186
187 def process(r, codeob, scope, toplevel=False):
188 opcodes = list(iteropcodes(codeob.co_code))
189
190 i = 0
191
192 codeobjs = []
193
194 while i < len(opcodes):
195 op, oparg = opcodes[i]
196
197 if op == _op_.IMPORT_NAME:
198 preop, preoparg = opcodes[i-1]
199 assert preop == _op_.LOAD_CONST, 'LOAD_CONST'
200
201 fromlist = codeob.co_consts[preoparg]
202
203 modname = codeob.co_names[oparg]
204
205 if fromlist is None:
206 # this is the 'import foo' case
207 r.import_(modname)
208
209 seenloadattr = False
210 while 1:
211 postop, postoparg = opcodes[i+1]
212 i += 1
213 if postop != _op_.LOAD_ATTR:
214 break
215 seenloadattr = True
216
217 assert postop in storeops, 'postop'
218
219 storename = name_for_op(codeob, postop, postoparg)
220 if seenloadattr:
221 scope.modvars[storename] = modname
222 else:
223 scope.modvars[storename] = modname.split('.')[0]
224 elif fromlist == ('*',):
225 assert toplevel, 'toplevel'
226 if modname.startswith('pypy.'):
227 if modname not in r.system.modules:
228 if modname in r.system.pendingmodules:
229 del r.system.pendingmodules[modname]
230 process_module(modname, r.system)
231 M = r.system.modules[modname]
232 for d in M.definitions + list(M.toplevelscope.modvars) + \
233 [a[1] for a in M.toplevelscope.varsources.itervalues()]:
234 if d[0] != '_':
235 #print '* got ', d
236 scope.varsources[d] = modname, d
237 r.import_(modname)[d] = -1
238 r.import_(modname)['*'] = True
239 else:
240 # ok, this is from foo import bar
241 path = None
242 try:
243 for part in modname.split('.'):
244 path = [imp.find_module(part, path)[1]]
245 except ImportError:
246 path = -1
247 i += 1
248 for f in fromlist:
249 op, oparg = opcodes[i]
250 assert op == _op_.IMPORT_FROM, 'IMPORT_FROM'
251 assert codeob.co_names[oparg] == f, 'f'
252 i += 1
253
254 if path == -1:
255 i += 1
256 continue
257
258 op, oparg = opcodes[i]
259 i += 1
260
261 assert op in storeops, 'opstore'
262 storename = name_for_op(codeob, op, oparg)
263
264 try:
265 imp.find_module(f, path)
266 except ImportError:
267 r.import_(modname)[f] = False
268 scope.varsources[storename] = modname, f
269 else:
270 submod = modname + '.' + f
271 r.import_(submod)
272 scope.modvars[storename] = submod
273
274 op, oparg = opcodes[i]
275 assert op == _op_.POP_TOP, 'POP_TOP'
276 elif op == _op_.STORE_NAME and toplevel or op == _op_.STORE_GLOBAL:
277 r.definitions.append(codeob.co_names[oparg])
278 elif op == _op_.LOAD_ATTR:
279 preop, preoparg = opcodes[i-1]
280 if preop in loadops:
281 name = name_for_op(codeob, preop, preoparg)
282 m = scope.mod_for_name(name)
283 if m:
284 r.import_(m)[codeob.co_names[oparg]] = True
285 elif op in loadops:
286 name = name_for_op(codeob, op, oparg)
287 m, a = scope.var_source(name)
288 if m:
289 assert a in r.import_(m), 'a'
290 r.import_(m)[a] = True
291 ## else:
292 ## if name not in r.definitions \
293 ## and scope.mod_for_name(name) is None \
294 ## and scope.var_source(name) == (None, None) \
295 ## and name not in __builtin__.__dict__ \
296 ## and (op == LOAD_GLOBAL or toplevel):
297 ## print 'where did', name, 'come from?'
298 elif op in [_op_.MAKE_FUNCTION, _op_.MAKE_CLOSURE]:
299 preop, preoparg = opcodes[i-1]
300 assert preop == _op_.LOAD_CONST, 'preop'
301 codeobjs.append(codeob.co_consts[preoparg])
302
303 i += 1
304 for c in codeobjs:
305 process(r, c, Scope(scope))
306
307 def find_from_dotted_name(modname):
308 path = None
309 for part in modname.split('.'):
310 try:
311 path = [imp.find_module(part, path)[1]]
312 except ImportError:
313 print modname
314 raise
315 return path[0]
316
317 def process_module(dottedname, system):
318 if dottedname.endswith('.py'):
319 path = dottedname
320 dottedname = path.lstrip('./').rstrip()[:-3].replace('/', '.')
321 else:
322 path = find_from_dotted_name(dottedname)
323
324 ispackage = False
325 if os.path.isdir(path):
326 ispackage = True
327 path += '/__init__.py'
328 r = Module(dottedname, system)
329 r.ispackage = ispackage
330
331 if dottedname in system.modules:
332 return system.modules[dottedname]
333
334 try:
335 code = compile(open(path, "r").read(), path, 'exec')
336 process(r, code, r.toplevelscope, True)
337 except (ImportError, SyntaxError) as e:
338 print "failed!", e
339 #raise
340 else:
341 if dottedname in system.pendingmodules:
342 print
343 del system.pendingmodules[dottedname]
344
345 system.modules[dottedname] = r
346
347 return r
348
349 # --- stuff that uses the processed data ---
350
351 def report_unused_symbols(system):
352 for name, mod in sorted(system.modules.iteritems()):
353 printed = False
354 if not 'pypy.' in name or '_cache' in name:
355 continue
356 u = {}
357 for n in mod._imports:
358 if n in ('autopath', '__future__'):
359 continue
360 usedany = False
361 for field, used in mod._imports[n].iteritems():
362 if n in system.modules:
363 M = system.modules[n]
364 if not M.ispackage and field != '*' and field not in M.definitions \
365 and used != -1:
366 if not printed:
367 print '*', name
368 printed = True
369 sourcemod, nam = M.toplevelscope.var_source(field)
370 print ' ', field, 'used from', n, 'but came from', sourcemod
371 if not used:
372 u.setdefault(n, []).append(field)
373 else:
374 usedany = True
375 if not usedany:
376 if n in u:
377 u[n].append('(i.e. entirely)')
378 else:
379 u[n] = 'entirely'
380 if u:
381 if not printed:
382 print '*', name
383 printed = True
384 for k, v in u.iteritems():
385 print ' ', k, v
386
387 def find_cycles(system):
388 from rpython.tool.algo import graphlib
389 vertices = dict.fromkeys(system.modules)
390 edges = {}
391 for m in system.modules:
392 edges[m] = []
393 for n in system.modules[m]._imports:
394 edges[m].append(graphlib.Edge(m, n))
395 cycles = []
396 for component in graphlib.strong_components(vertices, edges):
397 random_vertex = component.iterkeys().next()
398 cycles.extend(graphlib.all_cycles(random_vertex, component, edges))
399
400 ncycles = []
401 for cycle in cycles:
402 packs = {}
403 for edge in cycle:
404 package = edge.source.rsplit('.', 1)[0]
405 packs[package] = True
406 if len(packs) > 1:
407 ncycles.append(cycle)
408 cycles = ncycles
409
410 for cycle in cycles:
411 l = len(cycle[0].source)
412 print cycle[0].source, '->', cycle[0].target
413 for edge in cycle[1:]:
414 print ' '*l, '->', edge.target
415 print len(cycles), 'inter-package cycles'
416
417 def summary(system):
418 mcount = float(len(system.modules))
419 importcount = 0
420 importstars = 0
421 importstarusage = 0
422 defcount = 0
423 importedcount = 0
424 for m in system.modules:
425 m = system.modules[m]
426 defcount += len(m.definitions)
427 importedcount += len(m.importers)
428 importcount += len(m._imports)
429 for n in m._imports:
430 if '*' in m._imports[n]:
431 importstars += 1
432 importstarusage += len([o for (o, v) in m._imports[n].iteritems() if v == True])
433 print
434 print 'the average module'
435 print 'was imported %.2f times'%(importedcount/mcount)
436 print 'imported %.2f other modules'%(importcount/mcount)
437 print 'defined %.2f names'%(defcount/mcount)
438 print
439 print 'there were %d import *s'%(importstars)
440 print 'the average one produced %.2f names that were actually used'\
441 %((1.0*importstarusage)/importstars)
442
443 def not_imported(system):
444 for m, M in sorted(system.modules.iteritems()):
445 if not M.importers and 'test' not in m and '__init__' not in m:
446 print m
447
448 def import_stars(system):
449 for m in sorted(system.modules):
450 m = system.modules[m]
451 for n in sorted(m._imports):
452 if '*' in m._imports[n]:
453 print m.name, 'imports * from', n
454 used = [o for (o, v) in m._imports[n].iteritems() if v == True and o != '*']
455 print len(used), 'out of', len(m._imports[n]) - 1, 'names are used'
456 print ' ', ', '.join(sorted(used))
457
458 def find_varargs_users(system):
459 for m in sorted(system.modules):
460 m = system.modules[m]
461 if 'pypy.interpreter.pycode' in m._imports:
462 if m._imports['pypy.interpreter.pycode'].get('CO_VARARGS') == True:
463 print m.name
464
465 # --- HTML generation stuff ---
466
467 def file_for_module(module):
468 fname = os.path.join('importfunhtml', *module.name.split('.')) + '.html'
469 dname = os.path.dirname(fname)
470 if not os.path.isdir(dname):
471 os.makedirs(dname)
472 return open(fname, 'w')
473
474 def link_for_module(fromlink, module):
475 link = '/'.join(module.name.split('.')) + '.html'
476 prefix = '/'.join(['..']*fromlink.count('/'))
477 if prefix:
478 return prefix + '/' + link
479 else:
480 return link
481
482 def file_for_name(module, name):
483 fname = os.path.join('importfunhtml', *(module.name.split('.') + [name])) + '.html'
484 dname = os.path.dirname(fname)
485 if not os.path.isdir(dname):
486 os.makedirs(dname)
487 return open(fname, 'w')
488
489 def link_for_name(fromlink, module, name):
490 link = '/'.join(module.name.split('.') + [name]) + '.html'
491 prefix = '/'.join(['..']*fromlink.count('/'))
492 if prefix:
493 return prefix + '/' + link
494 else:
495 return link
496
497 def html_for_module(module):
498 from py.xml import html
499 out = file_for_module(module)
500 ourlink = link_for_module('', module)
501 head = [html.title(module.name)]
502 body = [html.h1(module.name)]
503 body.append(html.p('This module defines these names:'))
504 listbody = []
505 defuses = {}
506 for d in module.definitions:
507 uses = []
508 for n in sorted(module.importers):
509 N = module.system.modules[n]
510 if N._imports[module.name].get(d) == True:
511 uses.append(n)
512
513 if not d.startswith('_'):
514 if uses:
515 listbody.append(html.li(
516 html.a(d, href=link_for_name(ourlink, module, d))))
517 defuses[d] = uses
518 else:
519 listbody.append(html.li(d))
520
521 body.append(html.ul(listbody))
522 body.append(html.p('This module imports the following:'))
523 listbody1 = []
524 for n in sorted(module._imports):
525 if n in ('autopath', '__future__'):
526 continue
527 if n in module.system.modules:
528 listbody2 = [html.a(
529 n, href=link_for_module(ourlink, module.system.modules[n]))]
530 else:
531 listbody2 = [n]
532 listbody3 = []
533 for o in sorted(module._imports[n]):
534 if module._imports[n][o] == True:
535 if n in module.system.modules:
536 listbody3.append(
537 html.li(html.a(
538 o, href=link_for_name(ourlink, module.system.modules[n], o))))
539 else:
540 listbody3.append(html.li(o))
541 if listbody3:
542 listbody2.append(html.ul(listbody3))
543 listbody1.append(html.li(listbody2))
544 body.append(html.ul(listbody1))
545 body.append(html.p('This module is imported by the following:'))
546 listbody1 = []
547 for n in module.importers:
548 licontents = [html.a(n, href=link_for_module(ourlink, module.system.modules[n]))]
549 contents = []
550 for o in sorted(module.system.modules[n]._imports[module.name]):
551 contents.append(html.li(html.a(o, href=link_for_name(ourlink, module, o))))
552 if contents:
553 licontents.append(html.ul(contents))
554 listbody1.append(html.li(licontents))
555 body.append(html.ul(listbody1))
556
557 out.write(html.html(head, body).unicode())
558
559 for d in defuses:
560 out = file_for_name(module, d)
561 ourlink = link_for_name('', module, d)
562 head = [html.title(module.name + '.' + d)]
563 body = [html.h1([html.a(module.name, href=link_for_module(ourlink, module)), '.' + d])]
564
565 contents = []
566
567 for n in defuses[d]:
568 N = module.system.modules[n]
569 contents.append(html.li(html.a(n, href=link_for_module(ourlink, N))))
570
571 body.append(html.p('This name is used in'))
572 body.append(html.ul(contents))
573
574 out.write(html.html(head, body).unicode())
575
576 def make_html_report(system):
577 if os.path.isdir('importfunhtml'):
578 os.system('rm -rf importfunhtml')
579 os.mkdir('importfunhtml')
580 for m in system.modules.itervalues():
581 html_for_module(m)
582
583 # --- the driver stuff! ---
584
585 def main(*paths):
586 system = System()
587
588 for path in paths:
589 system.pendingmodules[path] = None
590
591 T = time.time()
592
593 while system.pendingmodules:
594 path, d = system.pendingmodules.popitem()
595 if sys.stdout.isatty():
596 print '\r\033[K', len(system.modules), '/', len(system.pendingmodules), path,
597 sys.stdout.flush()
598 if '._cache' in path or '/_cache' in path:
599 continue
600 if '/' not in path and not path.startswith('pypy.'):
601 continue
602 process_module(path, system)
603
604 print
605 print 'analysed', len(system.modules), 'modules in %.2f seconds'%(time.time() - T)
606 print '------'
607
608 # record importer information
609 for name, mod in system.modules.iteritems():
610 for n in mod._imports:
611 if n in system.modules:
612 system.modules[n].importers.append(name)
613
614 make_html_report(system)
615
616 if interactive:
617 import pdb
618 pdb.set_trace()
619
620 recursive = False
621 interactive = False
622
623 if __name__=='__main__':
624 if '-r' in sys.argv:
625 recursive = True
626 sys.argv.remove('-r')
627 if '-i' in sys.argv:
628 interactive = True
629 sys.argv.remove('-i')
630 if len(sys.argv) > 1:
631 main(*sys.argv[1:])
632 else:
633 paths = []
634 for line in os.popen("find pypy -name '*.py'"):
635 paths.append(line[:-1])
636 main(*paths)