home *** CD-ROM | disk | FTP | other *** search
/ PC Extra 07 & 08 / pca1507.iso / Software / psp8 / Data1.cab / pyclbr.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-22  |  10.2 KB  |  262 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. """Parse a Python file and retrieve classes and methods.
  5.  
  6. Parse enough of a Python file to recognize class and method
  7. definitions and to find out the superclasses of a class.
  8.  
  9. The interface consists of a single function:
  10.         readmodule(module, path)
  11. module is the name of a Python module, path is an optional list of
  12. directories where the module is to be searched.  If present, path is
  13. prepended to the system search path sys.path.
  14. The return value is a dictionary.  The keys of the dictionary are
  15. the names of the classes defined in the module (including classes
  16. that are defined via the from XXX import YYY construct).  The values
  17. are class instances of the class Class defined here.
  18.  
  19. A class is described by the class Class in this module.  Instances
  20. of this class have the following instance variables:
  21.         name -- the name of the class
  22.         super -- a list of super classes (Class instances)
  23.         methods -- a dictionary of methods
  24.         file -- the file in which the class was defined
  25.         lineno -- the line in the file on which the class statement occurred
  26. The dictionary of methods uses the method names as keys and the line
  27. numbers on which the method was defined as values.
  28. If the name of a super class is not recognized, the corresponding
  29. entry in the list of super classes is not a class instance but a
  30. string giving the name of the super class.  Since import statements
  31. are recognized and imported modules are scanned as well, this
  32. shouldn't happen often.
  33.  
  34. BUGS
  35. - Continuation lines are not dealt with at all, except inside strings.
  36. - Nested classes and functions can confuse 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.  
  41. PACKAGE 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.)
  54. """
  55. import sys
  56. import imp
  57. import re
  58. import string
  59. __all__ = [
  60.     'readmodule']
  61. TABWIDTH = 8
  62. _getnext = re.compile('\n    (?P<String>\n       \\""" [^"\\\\]* (?:\n                        (?: \\\\. | "(?!"") )\n                        [^"\\\\]*\n                    )*\n       \\"""\n\n    |   \'\'\' [^\'\\\\]* (?:\n                        (?: \\\\. | \'(?!\'\') )\n                        [^\'\\\\]*\n                    )*\n        \'\'\'\n\n    |   " [^"\\\\\\n]* (?: \\\\. [^"\\\\\\n]*)* "\n\n    |   \' [^\'\\\\\\n]* (?: \\\\. [^\'\\\\\\n]*)* \'\n    )\n\n|   (?P<Method>\n        ^\n        (?P<MethodIndent> [ \\t]* )\n        def [ \\t]+\n        (?P<MethodName> [a-zA-Z_] \\w* )\n        [ \\t]* \\(\n    )\n\n|   (?P<Class>\n        ^\n        (?P<ClassIndent> [ \\t]* )\n        class [ \\t]+\n        (?P<ClassName> [a-zA-Z_] \\w* )\n        [ \\t]*\n        (?P<ClassSupers> \\( [^)\\n]* \\) )?\n        [ \\t]* :\n    )\n\n|   (?P<Import>\n        ^ import [ \\t]+\n        (?P<ImportList> [^#;\\n]+ )\n    )\n\n|   (?P<ImportFrom>\n        ^ from [ \\t]+\n        (?P<ImportFromPath>\n            [a-zA-Z_] \\w*\n            (?:\n                [ \\t]* \\. [ \\t]* [a-zA-Z_] \\w*\n            )*\n        )\n        [ \\t]+\n        import [ \\t]+\n        (?P<ImportFromList> [^#;\\n]+ )\n    )\n', re.VERBOSE | re.DOTALL | re.MULTILINE).search
  63. _modules = { }
  64.  
  65. class Class:
  66.     '''Class to represent a Python class.'''
  67.     
  68.     def __init__(self, module, name, super, file, lineno):
  69.         self.module = module
  70.         self.name = name
  71.         if super is None:
  72.             super = []
  73.         
  74.         self.super = super
  75.         self.methods = { }
  76.         self.file = file
  77.         self.lineno = lineno
  78.  
  79.     
  80.     def _addmethod(self, name, lineno):
  81.         self.methods[name] = lineno
  82.  
  83.  
  84.  
  85. class Function(Class):
  86.     '''Class to represent a top-level Python function'''
  87.     
  88.     def __init__(self, module, name, file, lineno):
  89.         Class.__init__(self, module, name, None, file, lineno)
  90.  
  91.     
  92.     def _addmethod(self, name, lineno):
  93.         if not __debug__ and 0:
  94.             raise AssertionError, "Function._addmethod() shouldn't be called"
  95.  
  96.  
  97.  
  98. def readmodule(module, path = [], inpackage = 0):
  99.     '''Backwards compatible interface.
  100.  
  101.     Like readmodule_ex() but strips Function objects from the
  102.     resulting dictionary.'''
  103.     dict = readmodule_ex(module, path, inpackage)
  104.     res = { }
  105.     for key, value in dict.items():
  106.         if not isinstance(value, Function):
  107.             res[key] = value
  108.         
  109.     
  110.     return res
  111.  
  112.  
  113. def readmodule_ex(module, path = [], inpackage = 0):
  114.     '''Read a module file and return a dictionary of classes.
  115.  
  116.     Search for MODULE in PATH and sys.path, read and parse the
  117.     module and return a dictionary with one entry for each class
  118.     found in the module.'''
  119.     dict = { }
  120.     i = module.rfind('.')
  121.     if i >= 0:
  122.         package = module[:i].strip()
  123.         submodule = module[i + 1:].strip()
  124.         parent = readmodule_ex(package, path, inpackage)
  125.         child = readmodule_ex(submodule, parent['__path__'], 1)
  126.         return child
  127.     
  128.     if _modules.has_key(module):
  129.         return _modules[module]
  130.     
  131.     if module in sys.builtin_module_names:
  132.         _modules[module] = dict
  133.         return dict
  134.     
  135.     f = None
  136.     if inpackage:
  137.         
  138.         try:
  139.             (suff, mode, type) = (f, file)
  140.         except ImportError:
  141.             f = None
  142.  
  143.     
  144.     if f is None:
  145.         fullpath = list(path) + sys.path
  146.         (suff, mode, type) = (f, file)
  147.     
  148.     if type == imp.PKG_DIRECTORY:
  149.         dict['__path__'] = [
  150.             file]
  151.         _modules[module] = dict
  152.         path = [
  153.             file] + path
  154.         (suff, mode, type) = (f, file)
  155.     
  156.     if type != imp.PY_SOURCE:
  157.         f.close()
  158.         _modules[module] = dict
  159.         return dict
  160.     
  161.     _modules[module] = dict
  162.     classstack = []
  163.     src = f.read()
  164.     f.close()
  165.     countnl = string.count
  166.     (lineno, last_lineno_pos) = (1, 0)
  167.     i = 0
  168.     while 1:
  169.         m = _getnext(src, i)
  170.         if not m:
  171.             break
  172.         
  173.         (start, i) = m.span()
  174.         if m.start('Method') >= 0:
  175.             thisindent = _indent(m.group('MethodIndent'))
  176.             meth_name = m.group('MethodName')
  177.             lineno = lineno + countnl(src, '\n', last_lineno_pos, start)
  178.             last_lineno_pos = start
  179.             while classstack and classstack[-1][1] >= thisindent:
  180.                 del classstack[-1]
  181.             if classstack:
  182.                 cur_class = classstack[-1][0]
  183.                 cur_class._addmethod(meth_name, lineno)
  184.             else:
  185.                 f = Function(module, meth_name, file, lineno)
  186.                 dict[meth_name] = f
  187.         elif m.start('String') >= 0:
  188.             pass
  189.         elif m.start('Class') >= 0:
  190.             thisindent = _indent(m.group('ClassIndent'))
  191.             while classstack and classstack[-1][1] >= thisindent:
  192.                 del classstack[-1]
  193.             lineno = lineno + countnl(src, '\n', last_lineno_pos, start)
  194.             last_lineno_pos = start
  195.             class_name = m.group('ClassName')
  196.             inherit = m.group('ClassSupers')
  197.             if inherit:
  198.                 inherit = inherit[1:-1].strip()
  199.                 names = []
  200.                 for n in inherit.split(','):
  201.                     n = n.strip()
  202.                     if dict.has_key(n):
  203.                         n = dict[n]
  204.                     else:
  205.                         c = n.split('.')
  206.                         if len(c) > 1:
  207.                             m = c[-2]
  208.                             c = c[-1]
  209.                             if _modules.has_key(m):
  210.                                 d = _modules[m]
  211.                                 if d.has_key(c):
  212.                                     n = d[c]
  213.                                 
  214.                             
  215.                         
  216.                     names.append(n)
  217.                 
  218.                 inherit = names
  219.             
  220.             cur_class = Class(module, class_name, inherit, file, lineno)
  221.             dict[class_name] = cur_class
  222.             classstack.append((cur_class, thisindent))
  223.         elif m.start('Import') >= 0:
  224.             for n in m.group('ImportList').split(','):
  225.                 n = n.strip()
  226.                 
  227.                 try:
  228.                     d = readmodule_ex(n, path, inpackage)
  229.                 except:
  230.                     pass
  231.  
  232.             
  233.         elif m.start('ImportFrom') >= 0:
  234.             mod = m.group('ImportFromPath')
  235.             names = m.group('ImportFromList').split(',')
  236.             
  237.             try:
  238.                 d = readmodule_ex(mod, path, inpackage)
  239.             except:
  240.                 continue
  241.  
  242.             for n in names:
  243.                 n = n.strip()
  244.                 if d.has_key(n):
  245.                     dict[n] = d[n]
  246.                 elif n == '*':
  247.                     for n in d.keys():
  248.                         if n[0] != '_' and not dict.has_key(n):
  249.                             dict[n] = d[n]
  250.                         
  251.                     
  252.                 
  253.             
  254.         elif not __debug__ and 0:
  255.             raise AssertionError, 'regexp _getnext found something unexpected'
  256.     return dict
  257.  
  258.  
  259. def _indent(ws, _expandtabs = string.expandtabs):
  260.     return len(_expandtabs(ws, TABWIDTH))
  261.  
  262.