blob: 9bc68c5ee7331671c17f2a963524fb9d1cfda238 [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
Tim Petersc6ac8a72001-10-24 20:22:40 +000032- Continuation lines are not dealt with at all, except inside strings.
33- Nested classes and functions can confuse it.
Guido van Rossumb2693021999-06-10 19:05:54 +000034- Code that doesn't pass tabnanny or python -t will confuse it, unless
35 you set the module TABWIDTH vrbl (default 8) to the correct tab width
36 for the file.
37
38PACKAGE RELATED BUGS
39- If you have a package and a module inside that or another package
40 with the same name, module caching doesn't work properly since the
41 key is the base name of the module/package.
42- The only entry that is returned when you readmodule a package is a
43 __path__ whose value is a list which confuses certain class browsers.
44- When code does:
45 from package import subpackage
46 class MyClass(subpackage.SuperClass):
47 ...
48 It can't locate the parent. It probably needs to have the same
49 hairy logic that the import locator already does. (This logic
50 exists coded in Python in the freeze package.)
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000051"""
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000052
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000053import sys
54import imp
Guido van Rossum31626bc1997-10-24 14:46:16 +000055import re
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000056import string
57
Skip Montanaroc62c81e2001-02-12 02:00:42 +000058__all__ = ["readmodule"]
59
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000060TABWIDTH = 8
61
Guido van Rossumad380551999-06-07 15:25:18 +000062_getnext = re.compile(r"""
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000063 (?P<String>
64 \""" [^"\\]* (?:
Tim Peters2344fae2001-01-15 00:50:52 +000065 (?: \\. | "(?!"") )
66 [^"\\]*
67 )*
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000068 \"""
69
70 | ''' [^'\\]* (?:
Tim Peters2344fae2001-01-15 00:50:52 +000071 (?: \\. | '(?!'') )
72 [^'\\]*
73 )*
74 '''
Tim Petersc6ac8a72001-10-24 20:22:40 +000075
76 | " [^"\\\n]* (?: \\. [^"\\\n]*)* "
77
78 | ' [^'\\\n]* (?: \\. [^'\\\n]*)* '
Guido van Rossumdf9f7a31999-06-08 12:53:21 +000079 )
80
81| (?P<Method>
Tim Peters2344fae2001-01-15 00:50:52 +000082 ^
83 (?P<MethodIndent> [ \t]* )
84 def [ \t]+
85 (?P<MethodName> [a-zA-Z_] \w* )
86 [ \t]* \(
Guido van Rossumad380551999-06-07 15:25:18 +000087 )
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +000088
Guido van Rossumad380551999-06-07 15:25:18 +000089| (?P<Class>
Tim Peters2344fae2001-01-15 00:50:52 +000090 ^
91 (?P<ClassIndent> [ \t]* )
92 class [ \t]+
93 (?P<ClassName> [a-zA-Z_] \w* )
94 [ \t]*
95 (?P<ClassSupers> \( [^)\n]* \) )?
96 [ \t]* :
Guido van Rossumad380551999-06-07 15:25:18 +000097 )
98
99| (?P<Import>
Tim Peters2344fae2001-01-15 00:50:52 +0000100 ^ import [ \t]+
101 (?P<ImportList> [^#;\n]+ )
Guido van Rossumad380551999-06-07 15:25:18 +0000102 )
103
104| (?P<ImportFrom>
Tim Peters2344fae2001-01-15 00:50:52 +0000105 ^ from [ \t]+
106 (?P<ImportFromPath>
107 [a-zA-Z_] \w*
108 (?:
109 [ \t]* \. [ \t]* [a-zA-Z_] \w*
110 )*
111 )
112 [ \t]+
113 import [ \t]+
114 (?P<ImportFromList> [^#;\n]+ )
Guido van Rossumad380551999-06-07 15:25:18 +0000115 )
Guido van Rossumad380551999-06-07 15:25:18 +0000116""", re.VERBOSE | re.DOTALL | re.MULTILINE).search
117
118_modules = {} # cache of modules we've seen
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000119
120# each Python class is represented by an instance of this class
121class Class:
Tim Peters2344fae2001-01-15 00:50:52 +0000122 '''Class to represent a Python class.'''
123 def __init__(self, module, name, super, file, lineno):
124 self.module = module
125 self.name = name
126 if super is None:
127 super = []
128 self.super = super
129 self.methods = {}
130 self.file = file
131 self.lineno = lineno
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000132
Tim Peters2344fae2001-01-15 00:50:52 +0000133 def _addmethod(self, name, lineno):
134 self.methods[name] = lineno
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000135
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000136class Function(Class):
Tim Peters2344fae2001-01-15 00:50:52 +0000137 '''Class to represent a top-level Python function'''
138 def __init__(self, module, name, file, lineno):
139 Class.__init__(self, module, name, None, file, lineno)
140 def _addmethod(self, name, lineno):
141 assert 0, "Function._addmethod() shouldn't be called"
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000142
Guido van Rossum7a840e81998-10-12 15:21:38 +0000143def readmodule(module, path=[], inpackage=0):
Tim Peters2344fae2001-01-15 00:50:52 +0000144 '''Backwards compatible interface.
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000145
Tim Peters2344fae2001-01-15 00:50:52 +0000146 Like readmodule_ex() but strips Function objects from the
147 resulting dictionary.'''
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000148
Tim Peters2344fae2001-01-15 00:50:52 +0000149 dict = readmodule_ex(module, path, inpackage)
150 res = {}
151 for key, value in dict.items():
152 if not isinstance(value, Function):
153 res[key] = value
154 return res
Guido van Rossuma3b4a331999-06-10 14:39:39 +0000155
156def readmodule_ex(module, path=[], inpackage=0):
Tim Peters2344fae2001-01-15 00:50:52 +0000157 '''Read a module file and return a dictionary of classes.
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000158
Tim Peters2344fae2001-01-15 00:50:52 +0000159 Search for MODULE in PATH and sys.path, read and parse the
160 module and return a dictionary with one entry for each class
161 found in the module.'''
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000162
Tim Peters2344fae2001-01-15 00:50:52 +0000163 dict = {}
Guido van Rossum3d548711999-06-09 15:49:09 +0000164
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000165 i = module.rfind('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000166 if i >= 0:
167 # Dotted module name
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000168 package = module[:i].strip()
169 submodule = module[i+1:].strip()
Fred Drake03f7a702001-08-13 20:20:51 +0000170 parent = readmodule_ex(package, path, inpackage)
171 child = readmodule_ex(submodule, parent['__path__'], 1)
Tim Peters2344fae2001-01-15 00:50:52 +0000172 return child
Guido van Rossum7a840e81998-10-12 15:21:38 +0000173
Raymond Hettinger54f02222002-06-01 14:18:47 +0000174 if module in _modules:
Tim Peters2344fae2001-01-15 00:50:52 +0000175 # we've seen this module before...
176 return _modules[module]
177 if module in sys.builtin_module_names:
178 # this is a built-in module
179 _modules[module] = dict
180 return dict
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000181
Tim Peters2344fae2001-01-15 00:50:52 +0000182 # search the path for the module
183 f = None
184 if inpackage:
185 try:
186 f, file, (suff, mode, type) = \
187 imp.find_module(module, path)
188 except ImportError:
189 f = None
190 if f is None:
191 fullpath = list(path) + sys.path
192 f, file, (suff, mode, type) = imp.find_module(module, fullpath)
193 if type == imp.PKG_DIRECTORY:
194 dict['__path__'] = [file]
195 _modules[module] = dict
196 path = [file] + path
197 f, file, (suff, mode, type) = \
198 imp.find_module('__init__', [file])
199 if type != imp.PY_SOURCE:
200 # not Python source, can't do anything with this module
201 f.close()
202 _modules[module] = dict
203 return dict
Sjoerd Mullender8cb4b1f1995-07-28 09:30:01 +0000204
Tim Peters2344fae2001-01-15 00:50:52 +0000205 _modules[module] = dict
Tim Peters2344fae2001-01-15 00:50:52 +0000206 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
Walter Dörwald65230a22002-06-03 15:58:32 +0000211 # when we need a line number we simply count the number of
Tim Peters2344fae2001-01-15 00:50:52 +0000212 # newlines in the string since the last time we did this; i.e.,
Walter Dörwald65230a22002-06-03 15:58:32 +0000213 # lineno += src.count('\n', last_lineno_pos, here)
Tim Peters2344fae2001-01-15 00:50:52 +0000214 # last_lineno_pos = here
Tim Peters2344fae2001-01-15 00:50:52 +0000215 lineno, last_lineno_pos = 1, 0
216 i = 0
217 while 1:
218 m = _getnext(src, i)
219 if not m:
220 break
221 start, i = m.span()
Guido van Rossumad380551999-06-07 15:25:18 +0000222
Tim Peters2344fae2001-01-15 00:50:52 +0000223 if m.start("Method") >= 0:
224 # found a method definition or function
225 thisindent = _indent(m.group("MethodIndent"))
226 meth_name = m.group("MethodName")
Walter Dörwald65230a22002-06-03 15:58:32 +0000227 lineno += src.count('\n', last_lineno_pos, start)
Tim Peters2344fae2001-01-15 00:50:52 +0000228 last_lineno_pos = start
229 # close all classes indented at least as much
230 while classstack and \
231 classstack[-1][1] >= thisindent:
232 del classstack[-1]
233 if classstack:
234 # it's a class method
235 cur_class = classstack[-1][0]
236 cur_class._addmethod(meth_name, lineno)
237 else:
238 # it's a function
239 f = Function(module, meth_name,
240 file, lineno)
241 dict[meth_name] = f
Guido van Rossumad380551999-06-07 15:25:18 +0000242
Tim Peters2344fae2001-01-15 00:50:52 +0000243 elif m.start("String") >= 0:
244 pass
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000245
Tim Peters2344fae2001-01-15 00:50:52 +0000246 elif m.start("Class") >= 0:
247 # we found a class definition
248 thisindent = _indent(m.group("ClassIndent"))
249 # close all classes indented at least as much
250 while classstack and \
251 classstack[-1][1] >= thisindent:
252 del classstack[-1]
Walter Dörwald65230a22002-06-03 15:58:32 +0000253 lineno += src.count('\n', last_lineno_pos, start)
Tim Peters2344fae2001-01-15 00:50:52 +0000254 last_lineno_pos = start
255 class_name = m.group("ClassName")
256 inherit = m.group("ClassSupers")
257 if inherit:
258 # the class inherits from other classes
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000259 inherit = inherit[1:-1].strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000260 names = []
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000261 for n in inherit.split(','):
262 n = n.strip()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000263 if n in dict:
Tim Peters2344fae2001-01-15 00:50:52 +0000264 # we know this super class
265 n = dict[n]
266 else:
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000267 c = n.split('.')
Tim Peters2344fae2001-01-15 00:50:52 +0000268 if len(c) > 1:
269 # super class
270 # is of the
271 # form module.class:
272 # look in
273 # module for class
274 m = c[-2]
275 c = c[-1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000276 if m in _modules:
Tim Peters2344fae2001-01-15 00:50:52 +0000277 d = _modules[m]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000278 if c in d:
Tim Peters2344fae2001-01-15 00:50:52 +0000279 n = d[c]
280 names.append(n)
281 inherit = names
282 # remember this class
283 cur_class = Class(module, class_name, inherit,
284 file, lineno)
285 dict[class_name] = cur_class
286 classstack.append((cur_class, thisindent))
Guido van Rossum31626bc1997-10-24 14:46:16 +0000287
Tim Peters2344fae2001-01-15 00:50:52 +0000288 elif m.start("Import") >= 0:
289 # import module
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000290 for n in m.group("ImportList").split(','):
291 n = n.strip()
Tim Peters2344fae2001-01-15 00:50:52 +0000292 try:
293 # recursively read the imported module
Fred Drake03f7a702001-08-13 20:20:51 +0000294 d = readmodule_ex(n, path, inpackage)
Tim Peters2344fae2001-01-15 00:50:52 +0000295 except:
296 ##print 'module', n, 'not found'
297 pass
Guido van Rossumad380551999-06-07 15:25:18 +0000298
Tim Peters2344fae2001-01-15 00:50:52 +0000299 elif m.start("ImportFrom") >= 0:
300 # from module import stuff
301 mod = m.group("ImportFromPath")
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000302 names = m.group("ImportFromList").split(',')
Tim Peters2344fae2001-01-15 00:50:52 +0000303 try:
304 # recursively read the imported module
Fred Drake03f7a702001-08-13 20:20:51 +0000305 d = readmodule_ex(mod, path, inpackage)
Tim Peters2344fae2001-01-15 00:50:52 +0000306 except:
307 ##print 'module', mod, 'not found'
308 continue
309 # add any classes that were defined in the
310 # imported module to our name space if they
311 # were mentioned in the list
312 for n in names:
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000313 n = n.strip()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000314 if n in d:
Tim Peters2344fae2001-01-15 00:50:52 +0000315 dict[n] = d[n]
316 elif n == '*':
317 # only add a name if not
318 # already there (to mimic what
319 # Python does internally)
320 # also don't add names that
321 # start with _
Raymond Hettingere0d49722002-06-02 18:55:56 +0000322 for n in d:
Tim Peters2344fae2001-01-15 00:50:52 +0000323 if n[0] != '_' and \
Raymond Hettinger54f02222002-06-01 14:18:47 +0000324 not n in dict:
Tim Peters2344fae2001-01-15 00:50:52 +0000325 dict[n] = d[n]
326 else:
327 assert 0, "regexp _getnext found something unexpected"
Guido van Rossumad380551999-06-07 15:25:18 +0000328
Tim Peters2344fae2001-01-15 00:50:52 +0000329 return dict
Guido van Rossumdf9f7a31999-06-08 12:53:21 +0000330
331def _indent(ws, _expandtabs=string.expandtabs):
Tim Peters2344fae2001-01-15 00:50:52 +0000332 return len(_expandtabs(ws, TABWIDTH))