You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pyclbr.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. """Parse a Python file and retrieve classes and methods.
  2. Parse enough of a Python file to recognize class and method
  3. definitions and to find out the superclasses of a class.
  4. The interface consists of a single function:
  5. readmodule(module, path)
  6. module is the name of a Python module, path is an optional list of
  7. directories where the module is to be searched. If present, path is
  8. prepended to the system search path sys.path.
  9. The return value is a dictionary. The keys of the dictionary are
  10. the names of the classes defined in the module (including classes
  11. that are defined via the from XXX import YYY construct). The values
  12. are class instances of the class Class defined here.
  13. A class is described by the class Class in this module. Instances
  14. of this class have the following instance variables:
  15. name -- the name of the class
  16. super -- a list of super classes (Class instances)
  17. methods -- a dictionary of methods
  18. file -- the file in which the class was defined
  19. lineno -- the line in the file on which the class statement occurred
  20. The dictionary of methods uses the method names as keys and the line
  21. numbers on which the method was defined as values.
  22. If the name of a super class is not recognized, the corresponding
  23. entry in the list of super classes is not a class instance but a
  24. string giving the name of the super class. Since import statements
  25. are recognized and imported modules are scanned as well, this
  26. shouldn't happen often.
  27. BUGS
  28. - Continuation lines are not dealt with at all.
  29. - While triple-quoted strings won't confuse it, lines that look like
  30. def, class, import or "from ... import" stmts inside backslash-continued
  31. single-quoted strings are treated like code. The expense of stopping
  32. that isn't worth it.
  33. - Code that doesn't pass tabnanny or python -t will confuse it, unless
  34. you set the module TABWIDTH vrbl (default 8) to the correct tab width
  35. for the file.
  36. PACKAGE RELATED BUGS
  37. - If you have a package and a module inside that or another package
  38. with the same name, module caching doesn't work properly since the
  39. key is the base name of the module/package.
  40. - The only entry that is returned when you readmodule a package is a
  41. __path__ whose value is a list which confuses certain class browsers.
  42. - When code does:
  43. from package import subpackage
  44. class MyClass(subpackage.SuperClass):
  45. ...
  46. It can't locate the parent. It probably needs to have the same
  47. hairy logic that the import locator already does. (This logic
  48. exists coded in Python in the freeze package.)
  49. """
  50. import os
  51. import sys
  52. import imp
  53. import re
  54. import string
  55. __all__ = ["readmodule"]
  56. TABWIDTH = 8
  57. _getnext = re.compile(r"""
  58. (?P<String>
  59. \""" [^"\\]* (?:
  60. (?: \\. | "(?!"") )
  61. [^"\\]*
  62. )*
  63. \"""
  64. | ''' [^'\\]* (?:
  65. (?: \\. | '(?!'') )
  66. [^'\\]*
  67. )*
  68. '''
  69. )
  70. | (?P<Method>
  71. ^
  72. (?P<MethodIndent> [ \t]* )
  73. def [ \t]+
  74. (?P<MethodName> [a-zA-Z_] \w* )
  75. [ \t]* \(
  76. )
  77. | (?P<Class>
  78. ^
  79. (?P<ClassIndent> [ \t]* )
  80. class [ \t]+
  81. (?P<ClassName> [a-zA-Z_] \w* )
  82. [ \t]*
  83. (?P<ClassSupers> \( [^)\n]* \) )?
  84. [ \t]* :
  85. )
  86. | (?P<Import>
  87. ^ import [ \t]+
  88. (?P<ImportList> [^#;\n]+ )
  89. )
  90. | (?P<ImportFrom>
  91. ^ from [ \t]+
  92. (?P<ImportFromPath>
  93. [a-zA-Z_] \w*
  94. (?:
  95. [ \t]* \. [ \t]* [a-zA-Z_] \w*
  96. )*
  97. )
  98. [ \t]+
  99. import [ \t]+
  100. (?P<ImportFromList> [^#;\n]+ )
  101. )
  102. """, re.VERBOSE | re.DOTALL | re.MULTILINE).search
  103. _modules = {} # cache of modules we've seen
  104. # each Python class is represented by an instance of this class
  105. class Class:
  106. '''Class to represent a Python class.'''
  107. def __init__(self, module, name, super, file, lineno):
  108. self.module = module
  109. self.name = name
  110. if super is None:
  111. super = []
  112. self.super = super
  113. self.methods = {}
  114. self.file = file
  115. self.lineno = lineno
  116. def _addmethod(self, name, lineno):
  117. self.methods[name] = lineno
  118. class Function(Class):
  119. '''Class to represent a top-level Python function'''
  120. def __init__(self, module, name, file, lineno):
  121. Class.__init__(self, module, name, None, file, lineno)
  122. def _addmethod(self, name, lineno):
  123. assert 0, "Function._addmethod() shouldn't be called"
  124. def readmodule(module, path=[], inpackage=0):
  125. '''Backwards compatible interface.
  126. Like readmodule_ex() but strips Function objects from the
  127. resulting dictionary.'''
  128. dict = readmodule_ex(module, path, inpackage)
  129. res = {}
  130. for key, value in dict.items():
  131. if not isinstance(value, Function):
  132. res[key] = value
  133. return res
  134. def readmodule_ex(module, path=[], inpackage=0):
  135. '''Read a module file and return a dictionary of classes.
  136. Search for MODULE in PATH and sys.path, read and parse the
  137. module and return a dictionary with one entry for each class
  138. found in the module.'''
  139. dict = {}
  140. i = module.rfind('.')
  141. if i >= 0:
  142. # Dotted module name
  143. package = module[:i].strip()
  144. submodule = module[i+1:].strip()
  145. parent = readmodule(package, path, inpackage)
  146. child = readmodule(submodule, parent['__path__'], 1)
  147. return child
  148. if _modules.has_key(module):
  149. # we've seen this module before...
  150. return _modules[module]
  151. if module in sys.builtin_module_names:
  152. # this is a built-in module
  153. _modules[module] = dict
  154. return dict
  155. # search the path for the module
  156. f = None
  157. if inpackage:
  158. try:
  159. f, file, (suff, mode, type) = \
  160. imp.find_module(module, path)
  161. except ImportError:
  162. f = None
  163. if f is None:
  164. fullpath = list(path) + sys.path
  165. f, file, (suff, mode, type) = imp.find_module(module, fullpath)
  166. if type == imp.PKG_DIRECTORY:
  167. dict['__path__'] = [file]
  168. _modules[module] = dict
  169. path = [file] + path
  170. f, file, (suff, mode, type) = \
  171. imp.find_module('__init__', [file])
  172. if type != imp.PY_SOURCE:
  173. # not Python source, can't do anything with this module
  174. f.close()
  175. _modules[module] = dict
  176. return dict
  177. _modules[module] = dict
  178. imports = []
  179. classstack = [] # stack of (class, indent) pairs
  180. src = f.read()
  181. f.close()
  182. # To avoid having to stop the regexp at each newline, instead
  183. # when we need a line number we simply string.count the number of
  184. # newlines in the string since the last time we did this; i.e.,
  185. # lineno = lineno + \
  186. # string.count(src, '\n', last_lineno_pos, here)
  187. # last_lineno_pos = here
  188. countnl = string.count
  189. lineno, last_lineno_pos = 1, 0
  190. i = 0
  191. while 1:
  192. m = _getnext(src, i)
  193. if not m:
  194. break
  195. start, i = m.span()
  196. if m.start("Method") >= 0:
  197. # found a method definition or function
  198. thisindent = _indent(m.group("MethodIndent"))
  199. meth_name = m.group("MethodName")
  200. lineno = lineno + \
  201. countnl(src, '\n',
  202. last_lineno_pos, start)
  203. last_lineno_pos = start
  204. # close all classes indented at least as much
  205. while classstack and \
  206. classstack[-1][1] >= thisindent:
  207. del classstack[-1]
  208. if classstack:
  209. # it's a class method
  210. cur_class = classstack[-1][0]
  211. cur_class._addmethod(meth_name, lineno)
  212. else:
  213. # it's a function
  214. f = Function(module, meth_name,
  215. file, lineno)
  216. dict[meth_name] = f
  217. elif m.start("String") >= 0:
  218. pass
  219. elif m.start("Class") >= 0:
  220. # we found a class definition
  221. thisindent = _indent(m.group("ClassIndent"))
  222. # close all classes indented at least as much
  223. while classstack and \
  224. classstack[-1][1] >= thisindent:
  225. del classstack[-1]
  226. lineno = lineno + \
  227. countnl(src, '\n', last_lineno_pos, start)
  228. last_lineno_pos = start
  229. class_name = m.group("ClassName")
  230. inherit = m.group("ClassSupers")
  231. if inherit:
  232. # the class inherits from other classes
  233. inherit = inherit[1:-1].strip()
  234. names = []
  235. for n in inherit.split(','):
  236. n = n.strip()
  237. if dict.has_key(n):
  238. # we know this super class
  239. n = dict[n]
  240. else:
  241. c = n.split('.')
  242. if len(c) > 1:
  243. # super class
  244. # is of the
  245. # form module.class:
  246. # look in
  247. # module for class
  248. m = c[-2]
  249. c = c[-1]
  250. if _modules.has_key(m):
  251. d = _modules[m]
  252. if d.has_key(c):
  253. n = d[c]
  254. names.append(n)
  255. inherit = names
  256. # remember this class
  257. cur_class = Class(module, class_name, inherit,
  258. file, lineno)
  259. dict[class_name] = cur_class
  260. classstack.append((cur_class, thisindent))
  261. elif m.start("Import") >= 0:
  262. # import module
  263. for n in m.group("ImportList").split(','):
  264. n = n.strip()
  265. try:
  266. # recursively read the imported module
  267. d = readmodule(n, path, inpackage)
  268. except:
  269. ##print 'module', n, 'not found'
  270. pass
  271. elif m.start("ImportFrom") >= 0:
  272. # from module import stuff
  273. mod = m.group("ImportFromPath")
  274. names = m.group("ImportFromList").split(',')
  275. try:
  276. # recursively read the imported module
  277. d = readmodule(mod, path, inpackage)
  278. except:
  279. ##print 'module', mod, 'not found'
  280. continue
  281. # add any classes that were defined in the
  282. # imported module to our name space if they
  283. # were mentioned in the list
  284. for n in names:
  285. n = n.strip()
  286. if d.has_key(n):
  287. dict[n] = d[n]
  288. elif n == '*':
  289. # only add a name if not
  290. # already there (to mimic what
  291. # Python does internally)
  292. # also don't add names that
  293. # start with _
  294. for n in d.keys():
  295. if n[0] != '_' and \
  296. not dict.has_key(n):
  297. dict[n] = d[n]
  298. else:
  299. assert 0, "regexp _getnext found something unexpected"
  300. return dict
  301. def _indent(ws, _expandtabs=string.expandtabs):
  302. return len(_expandtabs(ws, TABWIDTH))