blob: a6c210ed1fa7c32ce83dfe881307f0ea74bae4fd [file] [log] [blame]
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +00001'''Parse a Python file and retrieve classes and methods.
2
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:
7 readmodule(module, path)
8module 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:
18 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
23The 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 Rossumdf9f7a31999-06-08 12:53:21 +000032Continuation lines are not dealt with at all.
33While triple-quoted strings won't confuse it, lines that look like
34def, class, import or "from ... import" stmts inside backslash-continued
35single-quoted strings are treated like code. The expense of stopping
36that isn't worth it.
37Code that doesn't pass tabnanny or python -t will confuse it, unless
38you set the module TABWIDTH vrbl (default 8) to the correct tab width
39for the file.''' # ' <-- bow to font lock
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000040
41import os
42import sys
43import imp
Guido van Rossum31626bc1997-10-24 14:46:16 +000044import re
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000045import string
46
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000047TABWIDTH = 8
48
Guido van Rossumad380551999-06-07 15:25:18 +000049_getnext = re.compile(r"""
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000050 (?P<String>
51 \""" [^"\\]* (?:
52 (?: \\. | "(?!"") )
53 [^"\\]*
54 )*
55 \"""
56
57 | ''' [^'\\]* (?:
58 (?: \\. | '(?!'') )
59 [^'\\]*
60 )*
61 '''
62 )
63
64| (?P<Method>
65 ^
66 (?P<MethodIndent> [ \t]* )
67 def [ \t]+
Guido van Rossumad380551999-06-07 15:25:18 +000068 (?P<MethodName> [a-zA-Z_] \w* )
69 [ \t]* \(
70 )
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000071
Guido van Rossumad380551999-06-07 15:25:18 +000072| (?P<Class>
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000073 ^
74 (?P<ClassIndent> [ \t]* )
75 class [ \t]+
Guido van Rossumad380551999-06-07 15:25:18 +000076 (?P<ClassName> [a-zA-Z_] \w* )
77 [ \t]*
78 (?P<ClassSupers> \( [^)\n]* \) )?
79 [ \t]* :
80 )
81
82| (?P<Import>
83 ^ import [ \t]+
84 (?P<ImportList> [^#;\n]+ )
85 )
86
87| (?P<ImportFrom>
88 ^ from [ \t]+
89 (?P<ImportFromPath>
90 [a-zA-Z_] \w*
91 (?:
92 [ \t]* \. [ \t]* [a-zA-Z_] \w*
93 )*
94 )
95 [ \t]+
96 import [ \t]+
97 (?P<ImportFromList> [^#;\n]+ )
98 )
Guido van Rossumad380551999-06-07 15:25:18 +000099""", re.VERBOSE | re.DOTALL | re.MULTILINE).search
100
101_modules = {} # cache of modules we've seen
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000102
103# each Python class is represented by an instance of this class
104class Class:
105 '''Class to represent a Python class.'''
Sjoerd Mullender825bae71995-11-02 17:21:33 +0000106 def __init__(self, module, name, super, file, lineno):
107 self.module = module
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000108 self.name = name
109 if super is None:
110 super = []
111 self.super = super
112 self.methods = {}
113 self.file = file
114 self.lineno = lineno
115
116 def _addmethod(self, name, lineno):
117 self.methods[name] = lineno
118
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000119class Function(Class):
120 '''Class to represent a top-level Python function'''
121 def __init__(self, module, name, file, lineno):
122 Class.__init__(self, module, name, None, file, lineno)
123 def _addmethod(self, name, lineno):
124 assert 0, "Function._addmethod() shouldn't be called"
125
Guido van Rossum7a840e81998-10-12 15:21:38 +0000126def readmodule(module, path=[], inpackage=0):
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000127 '''Backwards compatible interface.
128
129 Like readmodule_ex() but strips Function objects from the
130 resulting dictionary.'''
131
132 dict = readmodule_ex(module, path, inpackage)
133 res = {}
134 for key, value in dict.items():
135 if not isinstance(value, Function):
136 res[key] = value
137 return res
138
139def readmodule_ex(module, path=[], inpackage=0):
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000140 '''Read a module file and return a dictionary of classes.
141
142 Search for MODULE in PATH and sys.path, read and parse the
143 module and return a dictionary with one entry for each class
144 found in the module.'''
145
Guido van Rossum3d548711999-06-09 15:49:09 +0000146 dict = {}
147
Guido van Rossum7a840e81998-10-12 15:21:38 +0000148 i = string.rfind(module, '.')
149 if i >= 0:
150 # Dotted module name
Guido van Rossum06884361998-10-12 15:23:04 +0000151 package = string.strip(module[:i])
152 submodule = string.strip(module[i+1:])
Guido van Rossum7a840e81998-10-12 15:21:38 +0000153 parent = readmodule(package, path, inpackage)
154 child = readmodule(submodule, parent['__path__'], 1)
155 return child
156
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000157 if _modules.has_key(module):
158 # we've seen this module before...
159 return _modules[module]
160 if module in sys.builtin_module_names:
161 # this is a built-in module
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000162 _modules[module] = dict
163 return dict
164
165 # search the path for the module
166 f = None
Guido van Rossum7a840e81998-10-12 15:21:38 +0000167 if inpackage:
168 try:
169 f, file, (suff, mode, type) = \
170 imp.find_module(module, path)
171 except ImportError:
172 f = None
173 if f is None:
Fred Drake3d199af1999-02-18 20:51:50 +0000174 fullpath = list(path) + sys.path
Guido van Rossum7a840e81998-10-12 15:21:38 +0000175 f, file, (suff, mode, type) = imp.find_module(module, fullpath)
176 if type == imp.PKG_DIRECTORY:
Guido van Rossum3d548711999-06-09 15:49:09 +0000177 dict['__path__'] = [file]
Guido van Rossum7a840e81998-10-12 15:21:38 +0000178 _modules[module] = dict
Guido van Rossum3d548711999-06-09 15:49:09 +0000179 path = [file] + path
180 f, file, (suff, mode, type) = \
181 imp.find_module('__init__', [file])
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000182 if type != imp.PY_SOURCE:
183 # not Python source, can't do anything with this module
184 f.close()
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000185 _modules[module] = dict
186 return dict
187
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000188 _modules[module] = dict
189 imports = []
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000190 classstack = [] # stack of (class, indent) pairs
Guido van Rossumad380551999-06-07 15:25:18 +0000191 src = f.read()
192 f.close()
193
194 # To avoid having to stop the regexp at each newline, instead
195 # when we need a line number we simply string.count the number of
196 # newlines in the string since the last time we did this; i.e.,
197 # lineno = lineno + \
198 # string.count(src, '\n', last_lineno_pos, here)
199 # last_lineno_pos = here
200 countnl = string.count
201 lineno, last_lineno_pos = 1, 0
202 i = 0
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000203 while 1:
Guido van Rossumad380551999-06-07 15:25:18 +0000204 m = _getnext(src, i)
205 if not m:
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000206 break
Guido van Rossumad380551999-06-07 15:25:18 +0000207 start, i = m.span()
208
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000209 if m.start("Method") >= 0:
210 # found a method definition or function
211 thisindent = _indent(m.group("MethodIndent"))
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000212 meth_name = m.group("MethodName")
213 lineno = lineno + \
214 countnl(src, '\n',
215 last_lineno_pos, start)
216 last_lineno_pos = start
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000217 # close all classes indented at least as much
218 while classstack and \
219 classstack[-1][1] >= thisindent:
220 del classstack[-1]
221 if classstack:
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000222 # it's a class method
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000223 cur_class = classstack[-1][0]
Guido van Rossumad380551999-06-07 15:25:18 +0000224 cur_class._addmethod(meth_name, lineno)
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000225 else:
226 # it's a function
227 f = Function(module, meth_name,
228 file, lineno)
229 dict[meth_name] = f
Guido van Rossumad380551999-06-07 15:25:18 +0000230
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000231 elif m.start("String") >= 0:
232 pass
233
Guido van Rossumad380551999-06-07 15:25:18 +0000234 elif m.start("Class") >= 0:
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000235 # we found a class definition
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000236 thisindent = _indent(m.group("ClassIndent"))
237 # close all classes indented at least as much
238 while classstack and \
239 classstack[-1][1] >= thisindent:
240 del classstack[-1]
Guido van Rossumad380551999-06-07 15:25:18 +0000241 lineno = lineno + \
242 countnl(src, '\n', last_lineno_pos, start)
243 last_lineno_pos = start
244 class_name = m.group("ClassName")
245 inherit = m.group("ClassSupers")
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000246 if inherit:
247 # the class inherits from other classes
248 inherit = string.strip(inherit[1:-1])
249 names = []
250 for n in string.splitfields(inherit, ','):
251 n = string.strip(n)
252 if dict.has_key(n):
253 # we know this super class
254 n = dict[n]
255 else:
256 c = string.splitfields(n, '.')
257 if len(c) > 1:
258 # super class
259 # is of the
260 # form module.class:
261 # look in
262 # module for class
263 m = c[-2]
264 c = c[-1]
265 if _modules.has_key(m):
266 d = _modules[m]
267 if d.has_key(c):
268 n = d[c]
269 names.append(n)
270 inherit = names
271 # remember this class
Guido van Rossumad380551999-06-07 15:25:18 +0000272 cur_class = Class(module, class_name, inherit,
273 file, lineno)
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000274 dict[class_name] = cur_class
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000275 classstack.append((cur_class, thisindent))
Guido van Rossum31626bc1997-10-24 14:46:16 +0000276
Guido van Rossumad380551999-06-07 15:25:18 +0000277 elif m.start("Import") >= 0:
278 # import module
279 for n in string.split(m.group("ImportList"), ','):
280 n = string.strip(n)
281 try:
282 # recursively read the imported module
283 d = readmodule(n, path, inpackage)
284 except:
285 print 'module', n, 'not found'
286
287 elif m.start("ImportFrom") >= 0:
288 # from module import stuff
289 mod = m.group("ImportFromPath")
290 names = string.split(m.group("ImportFromList"), ',')
291 try:
292 # recursively read the imported module
293 d = readmodule(mod, path, inpackage)
294 except:
295 print 'module', mod, 'not found'
296 continue
297 # add any classes that were defined in the
298 # imported module to our name space if they
299 # were mentioned in the list
300 for n in names:
301 n = string.strip(n)
302 if d.has_key(n):
303 dict[n] = d[n]
304 elif n == '*':
305 # only add a name if not
306 # already there (to mimic what
307 # Python does internally)
308 # also don't add names that
309 # start with _
310 for n in d.keys():
311 if n[0] != '_' and \
312 not dict.has_key(n):
313 dict[n] = d[n]
314 else:
315 assert 0, "regexp _getnext found something unexpected"
316
317 return dict
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000318
319def _indent(ws, _expandtabs=string.expandtabs):
320 return len(_expandtabs(ws, TABWIDTH))