pyclbr.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. """Parse a Python module and describe its classes and functions.
  2. Parse enough of a Python file to recognize imports and class and
  3. function definitions, and to find out the superclasses of a class.
  4. The interface consists of a single function:
  5. readmodule_ex(module, path=None)
  6. where module is the name of a Python module, and path is an optional
  7. list of directories where the module is to be searched. If present,
  8. path is prepended to the system search path sys.path. The return value
  9. is a dictionary. The keys of the dictionary are the names of the
  10. classes and functions defined in the module (including classes that are
  11. defined via the from XXX import YYY construct). The values are
  12. instances of classes Class and Function. One special key/value pair is
  13. present for packages: the key '__path__' has a list as its value which
  14. contains the package search path.
  15. Classes and Functions have a common superclass: _Object. Every instance
  16. has the following attributes:
  17. module -- name of the module;
  18. name -- name of the object;
  19. file -- file in which the object is defined;
  20. lineno -- line in the file where the object's definition starts;
  21. parent -- parent of this object, if any;
  22. children -- nested objects contained in this object.
  23. The 'children' attribute is a dictionary mapping names to objects.
  24. Instances of Function describe functions with the attributes from _Object.
  25. Instances of Class describe classes with the attributes from _Object,
  26. plus the following:
  27. super -- list of super classes (Class instances if possible);
  28. methods -- mapping of method names to beginning line numbers.
  29. If the name of a super class is not recognized, the corresponding
  30. entry in the list of super classes is not a class instance but a
  31. string giving the name of the super class. Since import statements
  32. are recognized and imported modules are scanned as well, this
  33. shouldn't happen often.
  34. """
  35. import io
  36. import sys
  37. import importlib.util
  38. import tokenize
  39. from token import NAME, DEDENT, OP
  40. __all__ = ["readmodule", "readmodule_ex", "Class", "Function"]
  41. _modules = {} # Initialize cache of modules we've seen.
  42. class _Object:
  43. "Information about Python class or function."
  44. def __init__(self, module, name, file, lineno, parent):
  45. self.module = module
  46. self.name = name
  47. self.file = file
  48. self.lineno = lineno
  49. self.parent = parent
  50. self.children = {}
  51. def _addchild(self, name, obj):
  52. self.children[name] = obj
  53. class Function(_Object):
  54. "Information about a Python function, including methods."
  55. def __init__(self, module, name, file, lineno, parent=None):
  56. _Object.__init__(self, module, name, file, lineno, parent)
  57. class Class(_Object):
  58. "Information about a Python class."
  59. def __init__(self, module, name, super, file, lineno, parent=None):
  60. _Object.__init__(self, module, name, file, lineno, parent)
  61. self.super = [] if super is None else super
  62. self.methods = {}
  63. def _addmethod(self, name, lineno):
  64. self.methods[name] = lineno
  65. def _nest_function(ob, func_name, lineno):
  66. "Return a Function after nesting within ob."
  67. newfunc = Function(ob.module, func_name, ob.file, lineno, ob)
  68. ob._addchild(func_name, newfunc)
  69. if isinstance(ob, Class):
  70. ob._addmethod(func_name, lineno)
  71. return newfunc
  72. def _nest_class(ob, class_name, lineno, super=None):
  73. "Return a Class after nesting within ob."
  74. newclass = Class(ob.module, class_name, super, ob.file, lineno, ob)
  75. ob._addchild(class_name, newclass)
  76. return newclass
  77. def readmodule(module, path=None):
  78. """Return Class objects for the top-level classes in module.
  79. This is the original interface, before Functions were added.
  80. """
  81. res = {}
  82. for key, value in _readmodule(module, path or []).items():
  83. if isinstance(value, Class):
  84. res[key] = value
  85. return res
  86. def readmodule_ex(module, path=None):
  87. """Return a dictionary with all functions and classes in module.
  88. Search for module in PATH + sys.path.
  89. If possible, include imported superclasses.
  90. Do this by reading source, without importing (and executing) it.
  91. """
  92. return _readmodule(module, path or [])
  93. def _readmodule(module, path, inpackage=None):
  94. """Do the hard work for readmodule[_ex].
  95. If inpackage is given, it must be the dotted name of the package in
  96. which we are searching for a submodule, and then PATH must be the
  97. package search path; otherwise, we are searching for a top-level
  98. module, and path is combined with sys.path.
  99. """
  100. # Compute the full module name (prepending inpackage if set).
  101. if inpackage is not None:
  102. fullmodule = "%s.%s" % (inpackage, module)
  103. else:
  104. fullmodule = module
  105. # Check in the cache.
  106. if fullmodule in _modules:
  107. return _modules[fullmodule]
  108. # Initialize the dict for this module's contents.
  109. tree = {}
  110. # Check if it is a built-in module; we don't do much for these.
  111. if module in sys.builtin_module_names and inpackage is None:
  112. _modules[module] = tree
  113. return tree
  114. # Check for a dotted module name.
  115. i = module.rfind('.')
  116. if i >= 0:
  117. package = module[:i]
  118. submodule = module[i+1:]
  119. parent = _readmodule(package, path, inpackage)
  120. if inpackage is not None:
  121. package = "%s.%s" % (inpackage, package)
  122. if not '__path__' in parent:
  123. raise ImportError('No package named {}'.format(package))
  124. return _readmodule(submodule, parent['__path__'], package)
  125. # Search the path for the module.
  126. f = None
  127. if inpackage is not None:
  128. search_path = path
  129. else:
  130. search_path = path + sys.path
  131. spec = importlib.util._find_spec_from_path(fullmodule, search_path)
  132. if spec is None:
  133. raise ModuleNotFoundError(f"no module named {fullmodule!r}", name=fullmodule)
  134. _modules[fullmodule] = tree
  135. # Is module a package?
  136. if spec.submodule_search_locations is not None:
  137. tree['__path__'] = spec.submodule_search_locations
  138. try:
  139. source = spec.loader.get_source(fullmodule)
  140. except (AttributeError, ImportError):
  141. # If module is not Python source, we cannot do anything.
  142. return tree
  143. else:
  144. if source is None:
  145. return tree
  146. fname = spec.loader.get_filename(fullmodule)
  147. return _create_tree(fullmodule, path, fname, source, tree, inpackage)
  148. def _create_tree(fullmodule, path, fname, source, tree, inpackage):
  149. """Return the tree for a particular module.
  150. fullmodule (full module name), inpackage+module, becomes o.module.
  151. path is passed to recursive calls of _readmodule.
  152. fname becomes o.file.
  153. source is tokenized. Imports cause recursive calls to _readmodule.
  154. tree is {} or {'__path__': <submodule search locations>}.
  155. inpackage, None or string, is passed to recursive calls of _readmodule.
  156. The effect of recursive calls is mutation of global _modules.
  157. """
  158. f = io.StringIO(source)
  159. stack = [] # Initialize stack of (class, indent) pairs.
  160. g = tokenize.generate_tokens(f.readline)
  161. try:
  162. for tokentype, token, start, _end, _line in g:
  163. if tokentype == DEDENT:
  164. lineno, thisindent = start
  165. # Close previous nested classes and defs.
  166. while stack and stack[-1][1] >= thisindent:
  167. del stack[-1]
  168. elif token == 'def':
  169. lineno, thisindent = start
  170. # Close previous nested classes and defs.
  171. while stack and stack[-1][1] >= thisindent:
  172. del stack[-1]
  173. tokentype, func_name, start = next(g)[0:3]
  174. if tokentype != NAME:
  175. continue # Skip def with syntax error.
  176. cur_func = None
  177. if stack:
  178. cur_obj = stack[-1][0]
  179. cur_func = _nest_function(cur_obj, func_name, lineno)
  180. else:
  181. # It is just a function.
  182. cur_func = Function(fullmodule, func_name, fname, lineno)
  183. tree[func_name] = cur_func
  184. stack.append((cur_func, thisindent))
  185. elif token == 'class':
  186. lineno, thisindent = start
  187. # Close previous nested classes and defs.
  188. while stack and stack[-1][1] >= thisindent:
  189. del stack[-1]
  190. tokentype, class_name, start = next(g)[0:3]
  191. if tokentype != NAME:
  192. continue # Skip class with syntax error.
  193. # Parse what follows the class name.
  194. tokentype, token, start = next(g)[0:3]
  195. inherit = None
  196. if token == '(':
  197. names = [] # Initialize list of superclasses.
  198. level = 1
  199. super = [] # Tokens making up current superclass.
  200. while True:
  201. tokentype, token, start = next(g)[0:3]
  202. if token in (')', ',') and level == 1:
  203. n = "".join(super)
  204. if n in tree:
  205. # We know this super class.
  206. n = tree[n]
  207. else:
  208. c = n.split('.')
  209. if len(c) > 1:
  210. # Super class form is module.class:
  211. # look in module for class.
  212. m = c[-2]
  213. c = c[-1]
  214. if m in _modules:
  215. d = _modules[m]
  216. if c in d:
  217. n = d[c]
  218. names.append(n)
  219. super = []
  220. if token == '(':
  221. level += 1
  222. elif token == ')':
  223. level -= 1
  224. if level == 0:
  225. break
  226. elif token == ',' and level == 1:
  227. pass
  228. # Only use NAME and OP (== dot) tokens for type name.
  229. elif tokentype in (NAME, OP) and level == 1:
  230. super.append(token)
  231. # Expressions in the base list are not supported.
  232. inherit = names
  233. if stack:
  234. cur_obj = stack[-1][0]
  235. cur_class = _nest_class(
  236. cur_obj, class_name, lineno, inherit)
  237. else:
  238. cur_class = Class(fullmodule, class_name, inherit,
  239. fname, lineno)
  240. tree[class_name] = cur_class
  241. stack.append((cur_class, thisindent))
  242. elif token == 'import' and start[1] == 0:
  243. modules = _getnamelist(g)
  244. for mod, _mod2 in modules:
  245. try:
  246. # Recursively read the imported module.
  247. if inpackage is None:
  248. _readmodule(mod, path)
  249. else:
  250. try:
  251. _readmodule(mod, path, inpackage)
  252. except ImportError:
  253. _readmodule(mod, [])
  254. except:
  255. # If we can't find or parse the imported module,
  256. # too bad -- don't die here.
  257. pass
  258. elif token == 'from' and start[1] == 0:
  259. mod, token = _getname(g)
  260. if not mod or token != "import":
  261. continue
  262. names = _getnamelist(g)
  263. try:
  264. # Recursively read the imported module.
  265. d = _readmodule(mod, path, inpackage)
  266. except:
  267. # If we can't find or parse the imported module,
  268. # too bad -- don't die here.
  269. continue
  270. # Add any classes that were defined in the imported module
  271. # to our name space if they were mentioned in the list.
  272. for n, n2 in names:
  273. if n in d:
  274. tree[n2 or n] = d[n]
  275. elif n == '*':
  276. # Don't add names that start with _.
  277. for n in d:
  278. if n[0] != '_':
  279. tree[n] = d[n]
  280. except StopIteration:
  281. pass
  282. f.close()
  283. return tree
  284. def _getnamelist(g):
  285. """Return list of (dotted-name, as-name or None) tuples for token source g.
  286. An as-name is the name that follows 'as' in an as clause.
  287. """
  288. names = []
  289. while True:
  290. name, token = _getname(g)
  291. if not name:
  292. break
  293. if token == 'as':
  294. name2, token = _getname(g)
  295. else:
  296. name2 = None
  297. names.append((name, name2))
  298. while token != "," and "\n" not in token:
  299. token = next(g)[1]
  300. if token != ",":
  301. break
  302. return names
  303. def _getname(g):
  304. "Return (dotted-name or None, next-token) tuple for token source g."
  305. parts = []
  306. tokentype, token = next(g)[0:2]
  307. if tokentype != NAME and token != '*':
  308. return (None, token)
  309. parts.append(token)
  310. while True:
  311. tokentype, token = next(g)[0:2]
  312. if token != '.':
  313. break
  314. tokentype, token = next(g)[0:2]
  315. if tokentype != NAME:
  316. break
  317. parts.append(token)
  318. return (".".join(parts), token)
  319. def _main():
  320. "Print module output (default this file) for quick visual check."
  321. import os
  322. try:
  323. mod = sys.argv[1]
  324. except:
  325. mod = __file__
  326. if os.path.exists(mod):
  327. path = [os.path.dirname(mod)]
  328. mod = os.path.basename(mod)
  329. if mod.lower().endswith(".py"):
  330. mod = mod[:-3]
  331. else:
  332. path = []
  333. tree = readmodule_ex(mod, path)
  334. lineno_key = lambda a: getattr(a, 'lineno', 0)
  335. objs = sorted(tree.values(), key=lineno_key, reverse=True)
  336. indent_level = 2
  337. while objs:
  338. obj = objs.pop()
  339. if isinstance(obj, list):
  340. # Value is a __path__ key.
  341. continue
  342. if not hasattr(obj, 'indent'):
  343. obj.indent = 0
  344. if isinstance(obj, _Object):
  345. new_objs = sorted(obj.children.values(),
  346. key=lineno_key, reverse=True)
  347. for ob in new_objs:
  348. ob.indent = obj.indent + indent_level
  349. objs.extend(new_objs)
  350. if isinstance(obj, Class):
  351. print("{}class {} {} {}"
  352. .format(' ' * obj.indent, obj.name, obj.super, obj.lineno))
  353. elif isinstance(obj, Function):
  354. print("{}def {} {}".format(' ' * obj.indent, obj.name, obj.lineno))
  355. if __name__ == "__main__":
  356. _main()