blob: ea42c30f3d8941920eff2154affb5ef918ef7822 [file] [log] [blame]
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00001"""Parse a Python file and retrieve classes and methods.
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +00002
3Parse enough of a Python file to recognize class and method
4definitions and to find out the superclasses of a class.
5
6The interface consists of a single function:
Tim Peters2344fae2001-01-15 00:50:52 +00007 readmodule(module, path)
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +00008module is the name of a Python module, path is an optional list of
9directories where the module is to be searched. If present, path is
10prepended to the system search path sys.path.
11The return value is a dictionary. The keys of the dictionary are
12the names of the classes defined in the module (including classes
13that are defined via the from XXX import YYY construct). The values
14are class instances of the class Class defined here.
15
16A class is described by the class Class in this module. Instances
17of this class have the following instance variables:
Tim Peters2344fae2001-01-15 00:50:52 +000018 name -- the name of the class
19 super -- a list of super classes (Class instances)
20 methods -- a dictionary of methods
21 file -- the file in which the class was defined
22 lineno -- the line in the file on which the class statement occurred
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000023The dictionary of methods uses the method names as keys and the line
24numbers on which the method was defined as values.
25If the name of a super class is not recognized, the corresponding
26entry in the list of super classes is not a class instance but a
27string giving the name of the super class. Since import statements
28are recognized and imported modules are scanned as well, this
29shouldn't happen often.
30
31BUGS
Guido van Rossumb2693021999-06-10 19:05:54 +000032- Continuation lines are not dealt with at all.
33- While triple-quoted strings won't confuse it, lines that look like
34 def, class, import or "from ... import" stmts inside backslash-continued
35 single-quoted strings are treated like code. The expense of stopping
36 that isn't worth it.
37- Code that doesn't pass tabnanny or python -t will confuse it, unless
38 you set the module TABWIDTH vrbl (default 8) to the correct tab width
39 for the file.
40
41PACKAGE RELATED BUGS
42- If you have a package and a module inside that or another package
43 with the same name, module caching doesn't work properly since the
44 key is the base name of the module/package.
45- The only entry that is returned when you readmodule a package is a
46 __path__ whose value is a list which confuses certain class browsers.
47- When code does:
48 from package import subpackage
49 class MyClass(subpackage.SuperClass):
50 ...
51 It can't locate the parent. It probably needs to have the same
52 hairy logic that the import locator already does. (This logic
53 exists coded in Python in the freeze package.)
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000054"""
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000055
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000056import sys
57import imp
Guido van Rossum31626bc1997-10-24 14:46:16 +000058import re
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000059import string
60
Skip Montanaroc62c81e2001-02-12 02:00:42 +000061__all__ = ["readmodule"]
62
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000063TABWIDTH = 8
64
Guido van Rossumad380551999-06-07 15:25:18 +000065_getnext = re.compile(r"""
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000066 (?P<String>
67 \""" [^"\\]* (?:
Tim Peters2344fae2001-01-15 00:50:52 +000068 (?: \\. | "(?!"") )
69 [^"\\]*
70 )*
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000071 \"""
72
73 | ''' [^'\\]* (?:
Tim Peters2344fae2001-01-15 00:50:52 +000074 (?: \\. | '(?!'') )
75 [^'\\]*
76 )*
77 '''
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000078 )
79
80| (?P<Method>
Tim Peters2344fae2001-01-15 00:50:52 +000081 ^
82 (?P<MethodIndent> [ \t]* )
83 def [ \t]+
84 (?P<MethodName> [a-zA-Z_] \w* )
85 [ \t]* \(
Guido van Rossumad380551999-06-07 15:25:18 +000086 )
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000087
Guido van Rossumad380551999-06-07 15:25:18 +000088| (?P<Class>
Tim Peters2344fae2001-01-15 00:50:52 +000089 ^
90 (?P<ClassIndent> [ \t]* )
91 class [ \t]+
92 (?P<ClassName> [a-zA-Z_] \w* )
93 [ \t]*
94 (?P<ClassSupers> \( [^)\n]* \) )?
95 [ \t]* :
Guido van Rossumad380551999-06-07 15:25:18 +000096 )
97
98| (?P<Import>
Tim Peters2344fae2001-01-15 00:50:52 +000099 ^ import [ \t]+
100 (?P<ImportList> [^#;\n]+ )
Guido van Rossumad380551999-06-07 15:25:18 +0000101 )
102
103| (?P<ImportFrom>
Tim Peters2344fae2001-01-15 00:50:52 +0000104 ^ from [ \t]+
105 (?P<ImportFromPath>
106 [a-zA-Z_] \w*
107 (?:
108 [ \t]* \. [ \t]* [a-zA-Z_] \w*
109 )*
110 )
111 [ \t]+
112 import [ \t]+
113 (?P<ImportFromList> [^#;\n]+ )
Guido van Rossumad380551999-06-07 15:25:18 +0000114 )
Guido van Rossumad380551999-06-07 15:25:18 +0000115""", re.VERBOSE | re.DOTALL | re.MULTILINE).search
116
117_modules = {} # cache of modules we've seen
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000118
119# each Python class is represented by an instance of this class
120class Class:
Tim Peters2344fae2001-01-15 00:50:52 +0000121 '''Class to represent a Python class.'''
122 def __init__(self, module, name, super, file, lineno):
123 self.module = module
124 self.name = name
125 if super is None:
126 super = []
127 self.super = super
128 self.methods = {}
129 self.file = file
130 self.lineno = lineno
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000131
Tim Peters2344fae2001-01-15 00:50:52 +0000132 def _addmethod(self, name, lineno):
133 self.methods[name] = lineno
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000134
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000135class Function(Class):
Tim Peters2344fae2001-01-15 00:50:52 +0000136 '''Class to represent a top-level Python function'''
137 def __init__(self, module, name, file, lineno):
138 Class.__init__(self, module, name, None, file, lineno)
139 def _addmethod(self, name, lineno):
140 assert 0, "Function._addmethod() shouldn't be called"
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000141
Guido van Rossum7a840e81998-10-12 15:21:38 +0000142def readmodule(module, path=[], inpackage=0):
Tim Peters2344fae2001-01-15 00:50:52 +0000143 '''Backwards compatible interface.
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000144
Tim Peters2344fae2001-01-15 00:50:52 +0000145 Like readmodule_ex() but strips Function objects from the
146 resulting dictionary.'''
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000147
Tim Peters2344fae2001-01-15 00:50:52 +0000148 dict = readmodule_ex(module, path, inpackage)
149 res = {}
150 for key, value in dict.items():
151 if not isinstance(value, Function):
152 res[key] = value
153 return res
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000154
155def readmodule_ex(module, path=[], inpackage=0):
Tim Peters2344fae2001-01-15 00:50:52 +0000156 '''Read a module file and return a dictionary of classes.
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000157
Tim Peters2344fae2001-01-15 00:50:52 +0000158 Search for MODULE in PATH and sys.path, read and parse the
159 module and return a dictionary with one entry for each class
160 found in the module.'''
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000161
Tim Peters2344fae2001-01-15 00:50:52 +0000162 dict = {}
Guido van Rossum3d548711999-06-09 15:49:09 +0000163
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000164 i = module.rfind('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000165 if i >= 0:
166 # Dotted module name
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000167 package = module[:i].strip()
168 submodule = module[i+1:].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000169 parent = readmodule(package, path, inpackage)
170 child = readmodule(submodule, parent['__path__'], 1)
171 return child
Guido van Rossum7a840e81998-10-12 15:21:38 +0000172
Tim Peters2344fae2001-01-15 00:50:52 +0000173 if _modules.has_key(module):
174 # we've seen this module before...
175 return _modules[module]
176 if module in sys.builtin_module_names:
177 # this is a built-in module
178 _modules[module] = dict
179 return dict
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000180
Tim Peters2344fae2001-01-15 00:50:52 +0000181 # search the path for the module
182 f = None
183 if inpackage:
184 try:
185 f, file, (suff, mode, type) = \
186 imp.find_module(module, path)
187 except ImportError:
188 f = None
189 if f is None:
190 fullpath = list(path) + sys.path
191 f, file, (suff, mode, type) = imp.find_module(module, fullpath)
192 if type == imp.PKG_DIRECTORY:
193 dict['__path__'] = [file]
194 _modules[module] = dict
195 path = [file] + path
196 f, file, (suff, mode, type) = \
197 imp.find_module('__init__', [file])
198 if type != imp.PY_SOURCE:
199 # not Python source, can't do anything with this module
200 f.close()
201 _modules[module] = dict
202 return dict
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000203
Tim Peters2344fae2001-01-15 00:50:52 +0000204 _modules[module] = dict
205 imports = []
206 classstack = [] # stack of (class, indent) pairs
207 src = f.read()
208 f.close()
Guido van Rossumad380551999-06-07 15:25:18 +0000209
Tim Peters2344fae2001-01-15 00:50:52 +0000210 # To avoid having to stop the regexp at each newline, instead
211 # when we need a line number we simply string.count the number of
212 # newlines in the string since the last time we did this; i.e.,
213 # lineno = lineno + \
214 # string.count(src, '\n', last_lineno_pos, here)
215 # last_lineno_pos = here
216 countnl = string.count
217 lineno, last_lineno_pos = 1, 0
218 i = 0
219 while 1:
220 m = _getnext(src, i)
221 if not m:
222 break
223 start, i = m.span()
Guido van Rossumad380551999-06-07 15:25:18 +0000224
Tim Peters2344fae2001-01-15 00:50:52 +0000225 if m.start("Method") >= 0:
226 # found a method definition or function
227 thisindent = _indent(m.group("MethodIndent"))
228 meth_name = m.group("MethodName")
229 lineno = lineno + \
230 countnl(src, '\n',
231 last_lineno_pos, start)
232 last_lineno_pos = start
233 # close all classes indented at least as much
234 while classstack and \
235 classstack[-1][1] >= thisindent:
236 del classstack[-1]
237 if classstack:
238 # it's a class method
239 cur_class = classstack[-1][0]
240 cur_class._addmethod(meth_name, lineno)
241 else:
242 # it's a function
243 f = Function(module, meth_name,
244 file, lineno)
245 dict[meth_name] = f
Guido van Rossumad380551999-06-07 15:25:18 +0000246
Tim Peters2344fae2001-01-15 00:50:52 +0000247 elif m.start("String") >= 0:
248 pass
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000249
Tim Peters2344fae2001-01-15 00:50:52 +0000250 elif m.start("Class") >= 0:
251 # we found a class definition
252 thisindent = _indent(m.group("ClassIndent"))
253 # close all classes indented at least as much
254 while classstack and \
255 classstack[-1][1] >= thisindent:
256 del classstack[-1]
257 lineno = lineno + \
258 countnl(src, '\n', last_lineno_pos, start)
259 last_lineno_pos = start
260 class_name = m.group("ClassName")
261 inherit = m.group("ClassSupers")
262 if inherit:
263 # the class inherits from other classes
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000264 inherit = inherit[1:-1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000265 names = []
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000266 for n in inherit.split(','):
267 n = n.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000268 if dict.has_key(n):
269 # we know this super class
270 n = dict[n]
271 else:
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000272 c = n.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000273 if len(c) > 1:
274 # super class
275 # is of the
276 # form module.class:
277 # look in
278 # module for class
279 m = c[-2]
280 c = c[-1]
281 if _modules.has_key(m):
282 d = _modules[m]
283 if d.has_key(c):
284 n = d[c]
285 names.append(n)
286 inherit = names
287 # remember this class
288 cur_class = Class(module, class_name, inherit,
289 file, lineno)
290 dict[class_name] = cur_class
291 classstack.append((cur_class, thisindent))
Guido van Rossum31626bc1997-10-24 14:46:16 +0000292
Tim Peters2344fae2001-01-15 00:50:52 +0000293 elif m.start("Import") >= 0:
294 # import module
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000295 for n in m.group("ImportList").split(','):
296 n = n.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000297 try:
298 # recursively read the imported module
299 d = readmodule(n, path, inpackage)
300 except:
301 ##print 'module', n, 'not found'
302 pass
Guido van Rossumad380551999-06-07 15:25:18 +0000303
Tim Peters2344fae2001-01-15 00:50:52 +0000304 elif m.start("ImportFrom") >= 0:
305 # from module import stuff
306 mod = m.group("ImportFromPath")
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000307 names = m.group("ImportFromList").split(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000308 try:
309 # recursively read the imported module
310 d = readmodule(mod, path, inpackage)
311 except:
312 ##print 'module', mod, 'not found'
313 continue
314 # add any classes that were defined in the
315 # imported module to our name space if they
316 # were mentioned in the list
317 for n in names:
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000318 n = n.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000319 if d.has_key(n):
320 dict[n] = d[n]
321 elif n == '*':
322 # only add a name if not
323 # already there (to mimic what
324 # Python does internally)
325 # also don't add names that
326 # start with _
327 for n in d.keys():
328 if n[0] != '_' and \
329 not dict.has_key(n):
330 dict[n] = d[n]
331 else:
332 assert 0, "regexp _getnext found something unexpected"
Guido van Rossumad380551999-06-07 15:25:18 +0000333
Tim Peters2344fae2001-01-15 00:50:52 +0000334 return dict
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000335
336def _indent(ws, _expandtabs=string.expandtabs):
Tim Peters2344fae2001-01-15 00:50:52 +0000337 return len(_expandtabs(ws, TABWIDTH))