home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / pyclbr.py < prev    next >
Text File  |  1997-10-24  |  6KB  |  215 lines

  1. '''Parse a Python file and retrieve classes and methods.
  2.  
  3. Parse enough of a Python file to recognize class and method
  4. definitions and to find out the superclasses of a class.
  5.  
  6. The interface consists of a single function:
  7.     readmodule(module, path)
  8. module is the name of a Python module, path is an optional list of
  9. directories where the module is to be searched.  If present, path is
  10. prepended to the system search path sys.path.
  11. The return value is a dictionary.  The keys of the dictionary are
  12. the names of the classes defined in the module (including classes
  13. that are defined via the from XXX import YYY construct).  The values
  14. are class instances of the class Class defined here.
  15.  
  16. A class is described by the class Class in this module.  Instances
  17. of 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
  23. The dictionary of methods uses the method names as keys and the line
  24. numbers on which the method was defined as values.
  25. If the name of a super class is not recognized, the corresponding
  26. entry in the list of super classes is not a class instance but a
  27. string giving the name of the super class.  Since import statements
  28. are recognized and imported modules are scanned as well, this
  29. shouldn't happen often.
  30.  
  31. BUGS
  32. Continuation lines are not dealt with at all and strings may confuse
  33. the hell out of the parser, but it usually works.'''
  34.  
  35. import os
  36. import sys
  37. import imp
  38. import re
  39. import string
  40.  
  41. id = '(?P<id>[A-Za-z_][A-Za-z0-9_]*)'    # match identifier
  42. blank_line = re.compile('^[ \t]*($|#)')
  43. is_class = re.compile('^class[ \t]+'+id+'[ \t]*(?P<sup>\([^)]*\))?[ \t]*:')
  44. is_method = re.compile('^[ \t]+def[ \t]+'+id+'[ \t]*\(')
  45. is_import = re.compile('^import[ \t]*(?P<imp>[^#]+)')
  46. is_from = re.compile('^from[ \t]+'+id+'[ \t]+import[ \t]+(?P<imp>[^#]+)')
  47. dedent = re.compile('^[^ \t]')
  48. indent = re.compile('^[^ \t]*')
  49.  
  50. _modules = {}                # cache of modules we've seen
  51.  
  52. # each Python class is represented by an instance of this class
  53. class Class:
  54.     '''Class to represent a Python class.'''
  55.     def __init__(self, module, name, super, file, lineno):
  56.         self.module = module
  57.         self.name = name
  58.         if super is None:
  59.             super = []
  60.         self.super = super
  61.         self.methods = {}
  62.         self.file = file
  63.         self.lineno = lineno
  64.  
  65.     def _addmethod(self, name, lineno):
  66.         self.methods[name] = lineno
  67.  
  68. def readmodule(module, path = []):
  69.     '''Read a module file and return a dictionary of classes.
  70.  
  71.     Search for MODULE in PATH and sys.path, read and parse the
  72.     module and return a dictionary with one entry for each class
  73.     found in the module.'''
  74.  
  75.     if _modules.has_key(module):
  76.         # we've seen this module before...
  77.         return _modules[module]
  78.     if module in sys.builtin_module_names:
  79.         # this is a built-in module
  80.         dict = {}
  81.         _modules[module] = dict
  82.         return dict
  83.  
  84.     # search the path for the module
  85.     f = None
  86.     suffixes = imp.get_suffixes()
  87.     for dir in path + sys.path:
  88.         for suff, mode, type in suffixes:
  89.             file = os.path.join(dir, module + suff)
  90.             try:
  91.                 f = open(file, mode)
  92.             except IOError:
  93.                 pass
  94.             else:
  95.                 # found the module
  96.                 break
  97.         if f:
  98.             break
  99.     if not f:
  100.         raise IOError, 'module ' + module + ' not found'
  101.     if type != imp.PY_SOURCE:
  102.         # not Python source, can't do anything with this module
  103.         f.close()
  104.         dict = {}
  105.         _modules[module] = dict
  106.         return dict
  107.  
  108.     cur_class = None
  109.     dict = {}
  110.     _modules[module] = dict
  111.     imports = []
  112.     lineno = 0
  113.     while 1:
  114.         line = f.readline()
  115.         if not line:
  116.             break
  117.         lineno = lineno + 1    # count lines
  118.         line = line[:-1]    # remove line feed
  119.         if blank_line.match(line):
  120.             # ignore blank (and comment only) lines
  121.             continue
  122. ##         res = indent.match(line)
  123. ##         if res:
  124. ##             indentation = len(string.expandtabs(res.group(0), 8))
  125.         res = is_import.match(line)
  126.         if res:
  127.             # import module
  128.             for n in string.splitfields(res.group('imp'), ','):
  129.                 n = string.strip(n)
  130.                 try:
  131.                     # recursively read the
  132.                     # imported module
  133.                     d = readmodule(n, path)
  134.                 except:
  135.                     print 'module',n,'not found'
  136.                     pass
  137.             continue
  138.         res = is_from.match(line)
  139.         if res:
  140.             # from module import stuff
  141.             mod = res.group('id')
  142.             names = string.splitfields(res.group('imp'), ',')
  143.             try:
  144.                 # recursively read the imported module
  145.                 d = readmodule(mod, path)
  146.             except:
  147.                 print 'module',mod,'not found'
  148.                 continue
  149.             # add any classes that were defined in the
  150.             # imported module to our name space if they
  151.             # were mentioned in the list
  152.             for n in names:
  153.                 n = string.strip(n)
  154.                 if d.has_key(n):
  155.                     dict[n] = d[n]
  156.                 elif n == '*':
  157.                     # only add a name if not
  158.                     # already there (to mimic what
  159.                     # Python does internally)
  160.                     # also don't add names that
  161.                     # start with _
  162.                     for n in d.keys():
  163.                         if n[0] != '_' and \
  164.                            not dict.has_key(n):
  165.                             dict[n] = d[n]
  166.             continue
  167.         res = is_class.match(line)
  168.         if res:
  169.             # we found a class definition
  170.             class_name = res.group('id')
  171.             inherit = res.group('sup')
  172.             if inherit:
  173.                 # the class inherits from other classes
  174.                 inherit = string.strip(inherit[1:-1])
  175.                 names = []
  176.                 for n in string.splitfields(inherit, ','):
  177.                     n = string.strip(n)
  178.                     if dict.has_key(n):
  179.                         # we know this super class
  180.                         n = dict[n]
  181.                     else:
  182.                         c = string.splitfields(n, '.')
  183.                         if len(c) > 1:
  184.                             # super class
  185.                             # is of the
  186.                             # form module.class:
  187.                             # look in
  188.                             # module for class
  189.                             m = c[-2]
  190.                             c = c[-1]
  191.                             if _modules.has_key(m):
  192.                                 d = _modules[m]
  193.                                 if d.has_key(c):
  194.                                     n = d[c]
  195.                     names.append(n)
  196.                 inherit = names
  197.             # remember this class
  198.             cur_class = Class(module, class_name, inherit, file, lineno)
  199.             dict[class_name] = cur_class
  200.             continue
  201.         res = is_method.match(line)
  202.         if res:
  203.             # found a method definition
  204.             if cur_class:
  205.                 # and we know the class it belongs to
  206.                 meth_name = res.group('id')
  207.                 cur_class._addmethod(meth_name, lineno)
  208.             continue
  209.         if dedent.match(line):
  210.             # end of class definition
  211.             cur_class = None
  212.     f.close()
  213.     return dict
  214.  
  215.