浏览代码

ctypes: apply pep8

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@68348 15284696-431f-4ddb-bdfa-cd5b030d7da7
Pietro Zambelli 9 年之前
父节点
当前提交
cf80f34df3
共有 33 个文件被更改,包括 3019 次插入2314 次删除
  1. 1 1
      lib/python/ctypes/__init__.py
  2. 66 61
      lib/python/ctypes/ctypesgen.py
  3. 3 3
      lib/python/ctypes/ctypesgencore/__init__.py
  4. 132 97
      lib/python/ctypes/ctypesgencore/ctypedescs.py
  5. 121 79
      lib/python/ctypes/ctypesgencore/descriptions.py
  6. 102 75
      lib/python/ctypes/ctypesgencore/expressions.py
  7. 68 49
      lib/python/ctypes/ctypesgencore/libraryloader.py
  8. 6 3
      lib/python/ctypes/ctypesgencore/messages.py
  9. 4 2
      lib/python/ctypes/ctypesgencore/options.py
  10. 3 2
      lib/python/ctypes/ctypesgencore/parser/__init__.py
  11. 25 4
      lib/python/ctypes/ctypesgencore/parser/cdeclarations.py
  12. 256 156
      lib/python/ctypes/ctypesgencore/parser/cgrammar.py
  13. 35 30
      lib/python/ctypes/ctypesgencore/parser/cparser.py
  14. 44 40
      lib/python/ctypes/ctypesgencore/parser/ctypesparser.py
  15. 135 133
      lib/python/ctypes/ctypesgencore/parser/datacollectingparser.py
  16. 327 279
      lib/python/ctypes/ctypesgencore/parser/lex.py
  17. 55 4
      lib/python/ctypes/ctypesgencore/parser/lextab.py
  18. 265 265
      lib/python/ctypes/ctypesgencore/parser/parsetab.py
  19. 61 26
      lib/python/ctypes/ctypesgencore/parser/pplexer.py
  20. 42 26
      lib/python/ctypes/ctypesgencore/parser/preprocessor.py
  21. 723 580
      lib/python/ctypes/ctypesgencore/parser/yacc.py
  22. 1 1
      lib/python/ctypes/ctypesgencore/printer/__init__.py
  23. 1 1
      lib/python/ctypes/ctypesgencore/printer/defaultheader.py
  24. 117 37
      lib/python/ctypes/ctypesgencore/printer/preamble.py
  25. 115 108
      lib/python/ctypes/ctypesgencore/printer/printer.py
  26. 1 1
      lib/python/ctypes/ctypesgencore/printer/test.py
  27. 1 1
      lib/python/ctypes/ctypesgencore/processor/__init__.py
  28. 49 38
      lib/python/ctypes/ctypesgencore/processor/dependencies.py
  29. 109 96
      lib/python/ctypes/ctypesgencore/processor/operations.py
  30. 56 52
      lib/python/ctypes/ctypesgencore/processor/pipeline.py
  31. 3 3
      lib/python/ctypes/fix.sed
  32. 69 49
      lib/python/ctypes/loader.py
  33. 23 12
      lib/python/ctypes/preamble.py

+ 1 - 1
lib/python/ctypes/__init__.py

@@ -16,4 +16,4 @@ __all__ = [
     'stats',
     'vector',
     'vedit'
-    ]
+]

+ 66 - 61
lib/python/ctypes/ctypesgen.py

@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 
+
 def find_names_in_modules(modules):
     names = set()
     for module in modules:
@@ -11,7 +12,12 @@ def find_names_in_modules(modules):
             names.union(dir(module))
     return names
 
-import optparse, sys
+import optparse
+import sys
+
+import ctypesgencore
+import ctypesgencore.messages as msgs
+
 
 def option_callback_W(option, opt, value, parser):
     # Options preceded by a "-Wl," are simply treated as though the "-Wl,"
@@ -26,6 +32,7 @@ def option_callback_W(option, opt, value, parser):
     # Push the linker option onto the list for further parsing.
     parser.rargs.insert(0, value)
 
+
 def option_callback_libdir(option, opt, value, parser):
     # There are two sets of linker search paths: those for use at compile time
     # and those for use at runtime. Search paths specified with -L, -R, or
@@ -33,91 +40,89 @@ def option_callback_libdir(option, opt, value, parser):
     parser.values.compile_libdirs.append(value)
     parser.values.runtime_libdirs.append(value)
 
-import ctypesgencore
-import ctypesgencore.messages as msgs
 
-if __name__=="__main__":
+if __name__ == "__main__":
     usage = 'usage: %prog [options] /path/to/header.h ...'
     op = optparse.OptionParser(usage=usage)
-    
+
     # Parameters
     op.add_option('-o', '--output', dest='output', metavar='FILE',
-        help='write wrapper to FILE')
+                  help='write wrapper to FILE')
     op.add_option('-l', '--library', dest='libraries', action='append',
-        default=[], metavar='LIBRARY', help='link to LIBRARY')
+                  default=[], metavar='LIBRARY', help='link to LIBRARY')
     op.add_option('', '--include', dest='other_headers', action='append',
-        default=[], metavar='HEADER',
-        help='include system header HEADER (e.g. stdio.h or stdlib.h)')
+                  default=[], metavar='HEADER',
+                  help='include system header HEADER (e.g. stdio.h or stdlib.h)')
     op.add_option('-m', '--module', '--link-module', action='append',
-        dest='modules', metavar='MODULE', default=[],
-        help='use symbols from Python module MODULE')
+                  dest='modules', metavar='MODULE', default=[],
+                  help='use symbols from Python module MODULE')
     op.add_option('-I', '--includedir', dest='include_search_paths',
-        action='append', default=[], metavar='INCLUDEDIR',
-        help='add INCLUDEDIR as a directory to search for headers')
+                  action='append', default=[], metavar='INCLUDEDIR',
+                  help='add INCLUDEDIR as a directory to search for headers')
     op.add_option('-W', action="callback", callback=option_callback_W,
-        metavar="l,OPTION", type="str",
-        help="where OPTION is -L, -R, or --rpath")
+                  metavar="l,OPTION", type="str",
+                  help="where OPTION is -L, -R, or --rpath")
     op.add_option("-L", "-R", "--rpath", "--libdir", action="callback",
-        callback=option_callback_libdir, metavar="LIBDIR", type="str",
-        help="Add LIBDIR to the search path (both compile-time and run-time)")
+                  callback=option_callback_libdir, metavar="LIBDIR", type="str",
+                  help="Add LIBDIR to the search path (both compile-time and run-time)")
     op.add_option('', "--compile-libdir", action="append",
-        dest="compile_libdirs", metavar="LIBDIR", default=[],
-        help="Add LIBDIR to the compile-time library search path.")
+                  dest="compile_libdirs", metavar="LIBDIR", default=[],
+                  help="Add LIBDIR to the compile-time library search path.")
     op.add_option('', "--runtime-libdir", action="append",
-        dest="runtime_libdirs", metavar="LIBDIR", default=[],
-        help="Add LIBDIR to the run-time library search path.")
-    
+                  dest="runtime_libdirs", metavar="LIBDIR", default=[],
+                  help="Add LIBDIR to the run-time library search path.")
+
     # Parser options
     op.add_option('', '--cpp', dest='cpp', default='gcc -E',
-        help='The command to invoke the c preprocessor, including any ' \
-             'necessary options (default: gcc -E)')
+                  help='The command to invoke the c preprocessor, including any '
+                  'necessary options (default: gcc -E)')
     op.add_option('', '--save-preprocessed-headers', metavar='FILENAME',
-        dest='save_preprocessed_headers', default=None,
-        help='Save the preprocessed headers to the specified FILENAME')
-    
+                  dest='save_preprocessed_headers', default=None,
+                  help='Save the preprocessed headers to the specified FILENAME')
+
     # Processor options
     op.add_option('-a', '--all-headers', action='store_true',
-        dest='all_headers', default=False,
-        help='include symbols from all headers, including system headers')
+                  dest='all_headers', default=False,
+                  help='include symbols from all headers, including system headers')
     op.add_option('', '--builtin-symbols', action='store_true',
-        dest='builtin_symbols', default=False,
-        help='include symbols automatically generated by the preprocessor')
+                  dest='builtin_symbols', default=False,
+                  help='include symbols automatically generated by the preprocessor')
     op.add_option('', '--no-macros', action='store_false', dest='include_macros',
-        default=True, help="Don't output macros.")
+                  default=True, help="Don't output macros.")
     op.add_option('-i', '--include-symbols', dest='include_symbols',
-        default=None, help='regular expression for symbols to always include')
+                  default=None, help='regular expression for symbols to always include')
     op.add_option('-x', '--exclude-symbols', dest='exclude_symbols',
-        default=None, help='regular expression for symbols to exclude')
-    
+                  default=None, help='regular expression for symbols to exclude')
+
     # Printer options
     op.add_option('', '--header-template', dest='header_template', default=None,
-        metavar='TEMPLATE',
-        help='Use TEMPLATE as the header template in the output file.')
+                  metavar='TEMPLATE',
+                  help='Use TEMPLATE as the header template in the output file.')
     op.add_option('', '--strip-build-path', dest='strip_build_path',
-        default=None, metavar='BUILD_PATH',
-        help='Strip build path from header paths in the wrapper file.')
+                  default=None, metavar='BUILD_PATH',
+                  help='Strip build path from header paths in the wrapper file.')
     op.add_option('', '--insert-file', dest='inserted_files', default=[],
-        action='append', metavar='FILENAME',
-        help='Add the contents of FILENAME to the end of the wrapper file.')
-    
+                  action='append', metavar='FILENAME',
+                  help='Add the contents of FILENAME to the end of the wrapper file.')
+
     # Error options
     op.add_option('', "--all-errors", action="store_true", default=False,
-        dest="show_all_errors", help="Display all warnings and errors even " \
-             "if they would not affect output.")
+                  dest="show_all_errors", help="Display all warnings and errors even "
+                  "if they would not affect output.")
     op.add_option('', "--show-long-errors", action="store_true", default=False,
-        dest="show_long_errors", help="Display long error messages " \
-            "instead of abbreviating error messages.")
+                  dest="show_long_errors", help="Display long error messages "
+                  "instead of abbreviating error messages.")
     op.add_option('', "--no-macro-warnings", action="store_false", default=True,
-        dest="show_macro_warnings", help="Do not print macro warnings.")
+                  dest="show_macro_warnings", help="Do not print macro warnings.")
 
     op.set_defaults(**ctypesgencore.options.default_values)
-    
+
     (options, args) = op.parse_args(list(sys.argv[1:]))
     options.headers = args
 
     # Figure out what names will be defined by imported Python modules
     options.other_known_names = find_names_in_modules(options.modules)
-    
+
     # Required parameters
     if len(args) < 1:
         msgs.error_message('No header files specified', cls='usage')
@@ -129,22 +134,22 @@ if __name__=="__main__":
 
     if len(options.libraries) == 0:
         msgs.warning_message('No libraries specified', cls='usage')
-    
+
     # Step 1: Parse
-    descriptions=ctypesgencore.parser.parse(options.headers,options)
-    
+    descriptions = ctypesgencore.parser.parse(options.headers, options)
+
     # Step 2: Process
-    ctypesgencore.processor.process(descriptions,options)
-    
+    ctypesgencore.processor.process(descriptions, options)
+
     # Step 3: Print
-    ctypesgencore.printer.WrapperPrinter(options.output,options,descriptions)
-    
+    ctypesgencore.printer.WrapperPrinter(options.output, options, descriptions)
+
     msgs.status_message("Wrapping complete.")
-    
+
     # Correct what may be a common mistake
     if descriptions.all == []:
         if not options.all_headers:
-            msgs.warning_message("There wasn't anything of use in the " \
-                "specified header file(s). Perhaps you meant to run with " \
-                "--all-headers to include objects from included sub-headers? ",
-                cls = 'usage')
+            msgs.warning_message("There wasn't anything of use in the "
+                                 "specified header file(s). Perhaps you meant to run with "
+                                 "--all-headers to include objects from included sub-headers? ",
+                                 cls='usage')

+ 3 - 3
lib/python/ctypes/ctypesgencore/__init__.py

@@ -43,9 +43,9 @@ format.
 """
 
 
-__all__ = ["parser","processor","printer",
-           "descriptions","ctypedescs","expressions",
-           "messages","options"]
+__all__ = ["parser", "processor", "printer",
+           "descriptions", "ctypedescs", "expressions",
+           "messages", "options"]
 
 # Workhorse modules
 import parser

+ 132 - 97
lib/python/ctypes/ctypesgencore/ctypedescs.py

@@ -24,68 +24,77 @@ import warnings
 __docformat__ = 'restructuredtext'
 
 ctypes_type_map = {
-   # typename   signed  longs
-    ('void',    True,   0): 'None',
-    ('int',     True,   0): 'c_int',
-    ('int',     False,  0): 'c_uint',
-    ('int',     True,   1): 'c_long',
-    ('int',     False,  1): 'c_ulong',
-    ('int',     True,   2): 'c_longlong',
-    ('int',     False,  2): 'c_ulonglong',
-    ('char',    True,   0): 'c_char',
-    ('char',    False,  0): 'c_ubyte',
-    ('short',   True,   0): 'c_short',
-    ('short',   False,  0): 'c_ushort',
-    ('float',   True,   0): 'c_float',
-    ('double',  True,   0): 'c_double',
-    ('size_t',  True,   0): 'c_size_t',
-    ('int8_t',  True,   0): 'c_int8',
-    ('int16_t', True,   0): 'c_int16',
-    ('int32_t', True,   0): 'c_int32',
-    ('int64_t', True,   0): 'c_int64',
-    ('apr_int64_t',True,0): 'c_int64',
-    ('off64_t', True,   0): 'c_int64',
-    ('uint8_t', True,   0): 'c_uint8',
-    ('uint16_t',True,   0): 'c_uint16',
-    ('uint32_t',True,   0): 'c_uint32',
-    ('uint64_t',True,   0): 'c_uint64',
-    ('apr_uint64_t',True,0): 'c_uint64',
-    ('wchar_t', True,   0): 'c_wchar',
-    ('ptrdiff_t',True,  0): 'c_ptrdiff_t',  # Requires definition in preamble
-    ('ssize_t', True,   0): 'c_ptrdiff_t',  # Requires definition in preamble
-    ('va_list', True,   0): 'c_void_p',
+    # typename   signed  longs
+    ('void', True, 0): 'None',
+    ('int', True, 0): 'c_int',
+    ('int', False, 0): 'c_uint',
+    ('int', True, 1): 'c_long',
+    ('int', False, 1): 'c_ulong',
+    ('int', True, 2): 'c_longlong',
+    ('int', False, 2): 'c_ulonglong',
+    ('char', True, 0): 'c_char',
+    ('char', False, 0): 'c_ubyte',
+    ('short', True, 0): 'c_short',
+    ('short', False, 0): 'c_ushort',
+    ('float', True, 0): 'c_float',
+    ('double', True, 0): 'c_double',
+    ('size_t', True, 0): 'c_size_t',
+    ('int8_t', True, 0): 'c_int8',
+    ('int16_t', True, 0): 'c_int16',
+    ('int32_t', True, 0): 'c_int32',
+    ('int64_t', True, 0): 'c_int64',
+    ('apr_int64_t', True, 0): 'c_int64',
+    ('off64_t', True, 0): 'c_int64',
+    ('uint8_t', True, 0): 'c_uint8',
+    ('uint16_t', True, 0): 'c_uint16',
+    ('uint32_t', True, 0): 'c_uint32',
+    ('uint64_t', True, 0): 'c_uint64',
+    ('apr_uint64_t', True, 0): 'c_uint64',
+    ('wchar_t', True, 0): 'c_wchar',
+    ('ptrdiff_t', True, 0): 'c_ptrdiff_t',  # Requires definition in preamble
+    ('ssize_t', True, 0): 'c_ptrdiff_t',  # Requires definition in preamble
+    ('va_list', True, 0): 'c_void_p',
 }
 
 # This protocol is used for walking type trees.
+
+
 class CtypesTypeVisitor(object):
+
     def visit_struct(self, struct):
         pass
 
     def visit_enum(self, enum):
         pass
-    
+
     def visit_typedef(self, name):
         pass
-    
+
     def visit_error(self, error, cls):
         pass
-    
+
     def visit_identifier(self, identifier):
         # This one comes from inside ExpressionNodes. There may be
         # ExpressionNode objects in array count expressions.
         pass
 
+
 def visit_type_and_collect_info(ctype):
     class Visitor(CtypesTypeVisitor):
-        def visit_struct(self,struct):
+
+        def visit_struct(self, struct):
             structs.append(struct)
-        def visit_enum(self,enum):
+
+        def visit_enum(self, enum):
             enums.append(enum)
-        def visit_typedef(self,typedef):
+
+        def visit_typedef(self, typedef):
             typedefs.append(typedef)
-        def visit_error(self,error,cls):
-            errors.append((error,cls))
-        def visit_identifier(self,identifier):
+
+        def visit_error(self, error, cls):
+            errors.append((error, cls))
+
+        def visit_identifier(self, identifier):
             identifiers.append(identifier)
     structs = []
     enums = []
@@ -94,35 +103,41 @@ def visit_type_and_collect_info(ctype):
     identifiers = []
     v = Visitor()
     ctype.visit(v)
-    return structs,enums,typedefs,errors,identifiers
+    return structs, enums, typedefs, errors, identifiers
 
 # Remove one level of indirection from funtion pointer; needed for typedefs
 # and function parameters.
+
+
 def remove_function_pointer(t):
-    if type(t) == CtypesPointer and type(t.destination) == CtypesFunction:
+    if isinstance(t, CtypesPointer) and isinstance(t.destination, CtypesFunction):
         return t.destination
-    elif type(t) == CtypesPointer:
+    elif isinstance(t, CtypesPointer):
         t.destination = remove_function_pointer(t.destination)
         return t
     else:
         return t
 
+
 class CtypesType(object):
+
     def __init__(self):
-        self.errors=[]
-    
+        self.errors = []
+
     def __repr__(self):
         return "<Ctype \"%s\">" % self.py_string()
-    
-    def error(self,message,cls=None):
-        self.errors.append((message,cls))
-    
-    def visit(self,visitor):
-        for error,cls in self.errors:
-            visitor.visit_error(error,cls)
+
+    def error(self, message, cls=None):
+        self.errors.append((message, cls))
+
+    def visit(self, visitor):
+        for error, cls in self.errors:
+            visitor.visit_error(error, cls)
+
 
 class CtypesSimple(CtypesType):
     """Represents a builtin type, like "char" or "int"."""
+
     def __init__(self, name, signed, longs):
         CtypesType.__init__(self)
         self.name = name
@@ -130,80 +145,92 @@ class CtypesSimple(CtypesType):
         self.longs = longs
 
     def py_string(self):
-        return ctypes_type_map[(self.name,self.signed,self.longs)]
+        return ctypes_type_map[(self.name, self.signed, self.longs)]
+
 
 class CtypesSpecial(CtypesType):
-    def __init__(self,name):
+
+    def __init__(self, name):
         CtypesType.__init__(self)
         self.name = name
-    
+
     def py_string(self):
         return self.name
 
+
 class CtypesTypedef(CtypesType):
     """Represents a type defined by a typedef."""
+
     def __init__(self, name):
         CtypesType.__init__(self)
         self.name = name
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         if not self.errors:
             visitor.visit_typedef(self.name)
-        CtypesType.visit(self,visitor)
-    
+        CtypesType.visit(self, visitor)
+
     def py_string(self):
         return self.name
 
+
 class CtypesBitfield(CtypesType):
+
     def __init__(self, base, bitfield):
         CtypesType.__init__(self)
         self.base = base
         self.bitfield = bitfield
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         self.base.visit(visitor)
-        CtypesType.visit(self,visitor)
-    
+        CtypesType.visit(self, visitor)
+
     def py_string(self):
         return self.base.py_string()
 
+
 class CtypesPointer(CtypesType):
+
     def __init__(self, destination, qualifiers):
         CtypesType.__init__(self)
         self.destination = destination
         self.qualifiers = qualifiers
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         if self.destination:
             self.destination.visit(visitor)
-        CtypesType.visit(self,visitor)
+        CtypesType.visit(self, visitor)
 
     def py_string(self):
         return 'POINTER(%s)' % self.destination.py_string()
 
+
 class CtypesArray(CtypesType):
+
     def __init__(self, base, count):
         CtypesType.__init__(self)
         self.base = base
         self.count = count
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         self.base.visit(visitor)
         if self.count:
             self.count.visit(visitor)
-        CtypesType.visit(self,visitor)
-    
+        CtypesType.visit(self, visitor)
+
     def py_string(self):
         if self.count is None:
             return 'POINTER(%s)' % self.base.py_string()
-        if type(self.base) == CtypesArray:
+        if isinstance(self.base, CtypesArray):
             return '(%s) * %s' % (self.base.py_string(),
                                   self.count.py_string(False))
         else:
             return '%s * %s' % (self.base.py_string(),
                                 self.count.py_string(False))
 
+
 class CtypesFunction(CtypesType):
+
     def __init__(self, restype, parameters, variadic=False):
         CtypesType.__init__(self)
         self.restype = restype
@@ -212,8 +239,8 @@ class CtypesFunction(CtypesType):
         # when ctypes automagically returns it as an int.
         # Instead, convert to POINTER(c_void).  c_void is not a ctypes type,
         # you can make it any arbitrary type.
-        if type(self.restype) == CtypesPointer and \
-           type(self.restype.destination) == CtypesSimple and \
+        if isinstance(self.restype, CtypesPointer) and \
+           isinstance(self.restype.destination, CtypesSimple) and \
            self.restype.destination.name == 'None':
             self.restype = CtypesPointer(CtypesSpecial('c_void'), ())
 
@@ -223,55 +250,59 @@ class CtypesFunction(CtypesType):
 
         self.argtypes = [remove_function_pointer(p) for p in parameters]
         self.variadic = variadic
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         self.restype.visit(visitor)
         for a in self.argtypes:
             a.visit(visitor)
-        CtypesType.visit(self,visitor)
+        CtypesType.visit(self, visitor)
 
     def py_string(self):
         return 'CFUNCTYPE(UNCHECKED(%s), %s)' % (self.restype.py_string(),
-            ', '.join([a.py_string() for a in self.argtypes]))
+                                                 ', '.join([a.py_string() for a in self.argtypes]))
 
 last_tagnum = 0
+
+
 def anonymous_struct_tag():
     global last_tagnum
     last_tagnum += 1
     return 'anon_%d' % last_tagnum
 
+
 class CtypesStruct(CtypesType):
+
     def __init__(self, tag, variety, members, src=None):
         CtypesType.__init__(self)
         self.tag = tag
-        self.variety = variety # "struct" or "union"
+        self.variety = variety  # "struct" or "union"
         self.members = members
-        
+
         if not self.tag:
             self.tag = anonymous_struct_tag()
             self.anonymous = True
         else:
             self.anonymous = False
-        
-        if self.members==None:
+
+        if self.members is None:
             self.opaque = True
         else:
             self.opaque = False
-        
-        self.src = src        
-    
+
+        self.src = src
+
     def get_required_types(self):
         types = CtypesType.get_required_types(self)
-        types.add((self.variety,self.tag))
+        types.add((self.variety, self.tag))
         return types
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         visitor.visit_struct(self)
         if not self.opaque:
-            for name,ctype in self.members:
+            for name, ctype in self.members:
                 ctype.visit(visitor)
-        CtypesType.visit(self,visitor)
-    
+        CtypesType.visit(self, visitor)
+
     def get_subtypes(self):
         if self.opaque:
             return set()
@@ -279,36 +310,40 @@ class CtypesStruct(CtypesType):
             return set([m[1] for m in self.members])
 
     def py_string(self):
-        return "%s_%s" % (self.variety,self.tag)
+        return "%s_%s" % (self.variety, self.tag)
 
 last_tagnum = 0
+
+
 def anonymous_enum_tag():
     global last_tagnum
     last_tagnum += 1
     return 'anon_%d' % last_tagnum
 
+
 class CtypesEnum(CtypesType):
+
     def __init__(self, tag, enumerators, src=None):
         CtypesType.__init__(self)
         self.tag = tag
         self.enumerators = enumerators
-        
+
         if not self.tag:
             self.tag = anonymous_enum_tag()
             self.anonymous = True
         else:
             self.anonymous = False
-        
-        if self.enumerators==None:
+
+        if self.enumerators is None:
             self.opaque = True
         else:
             self.opaque = False
-        
+
         self.src = src
-        
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         visitor.visit_enum(self)
-        CtypesType.visit(self,visitor)
+        CtypesType.visit(self, visitor)
 
     def py_string(self):
         return 'enum_%s' % self.tag

+ 121 - 79
lib/python/ctypes/ctypesgencore/descriptions.py

@@ -8,182 +8,224 @@ The descriptions module also contains a class, DescriptionCollection, to hold
 lists of Description objects.
 """
 
+
 class DescriptionCollection(object):
     """Represents a collection of Descriptions."""
-    def __init__(self,constants,typedefs,structs,enums,functions,variables,
-                 macros,all,output_order):
-        self.constants=constants
-        self.typedefs=typedefs
-        self.structs=structs
-        self.enums=enums
-        self.functions=functions
-        self.variables=variables
-        self.macros=macros
-        self.all=all
-        self.output_order=output_order
+
+    def __init__(self, constants, typedefs, structs, enums, functions, variables,
+                 macros, all, output_order):
+        self.constants = constants
+        self.typedefs = typedefs
+        self.structs = structs
+        self.enums = enums
+        self.functions = functions
+        self.variables = variables
+        self.macros = macros
+        self.all = all
+        self.output_order = output_order
+
 
 class Description(object):
     """Represents a constant, typedef, struct, function, variable, enum,
     or macro description. Description is an abstract base class."""
-    def __init__(self,src=None):
-        self.src=src # A tuple of (filename, lineno)
-        
+
+    def __init__(self, src=None):
+        self.src = src  # A tuple of (filename, lineno)
+
         # If object will be included in output file. Values are "yes", "never",
         # and "if_needed".
-        self.include_rule="yes" 
-        
+        self.include_rule = "yes"
+
         # A word about requirements, and dependents:
         # If X requires Y, Y is in X.requirements.
         # If X is in Y.requirements, then Y is in X.dependents.
-        self.requirements=set()
-        self.dependents=set()
-        
+        self.requirements = set()
+        self.dependents = set()
+
         # If the processor module finds a fatal error that prevents a
         # a description from being output, then it appends a string describing
         # the problem to 'errors'. If it finds a nonfatal error, it appends a
         # string to 'warnings'. If the description would have been output, then
         # the errors and warnings are printed.
-        
+
         # If there is anything in 'errors' after processing is complete, the
         # description is not output.
-        
-        self.errors=[] 
-        self.warnings=[]
-    
-    def add_requirements(self,reqs):
+
+        self.errors = []
+        self.warnings = []
+
+    def add_requirements(self, reqs):
         self.requirements = self.requirements.union(reqs)
         for req in reqs:
             req.dependents.add(self)
-    
-    def error(self,msg,cls = None):
-        self.errors.append((msg,cls))
-    def warning(self,msg,cls = None):
-        self.warnings.append((msg,cls))
-    
+
+    def error(self, msg, cls=None):
+        self.errors.append((msg, cls))
+
+    def warning(self, msg, cls=None):
+        self.warnings.append((msg, cls))
+
     def __repr__(self):
         return "<Description: %s>" % self.casual_name()
-    
+
     def casual_name(self):
         """Return a name to show the user."""
+
     def py_name(self):
         """Return the name associated with this description in Python code."""
+
     def c_name(self):
         """Return the name associated with this description in C code."""
 
+
 class ConstantDescription(Description):
     """Simple class to contain information about a constant."""
-    def __init__(self,name,value,src=None):
-        Description.__init__(self,src)
+
+    def __init__(self, name, value, src=None):
+        Description.__init__(self, src)
         # Name of constant, a string
-        self.name=name 
+        self.name = name
         # Value of constant, as an ExpressionNode object
-        self.value=value 
+        self.value = value
+
     def casual_name(self):
-        return "Constant \"%s\""%self.name
+        return "Constant \"%s\"" % self.name
+
     def py_name(self):
         return self.name
+
     def c_name(self):
         return self.name
 
+
 class TypedefDescription(Description):
     """Simple container class for a type definition."""
-    def __init__(self,name,ctype,src=None):
-        Description.__init__(self,src)
-        self.name=name # Name, a string
-        self.ctype=ctype # The base type as a ctypedescs.CtypeType object
+
+    def __init__(self, name, ctype, src=None):
+        Description.__init__(self, src)
+        self.name = name  # Name, a string
+        self.ctype = ctype  # The base type as a ctypedescs.CtypeType object
+
     def casual_name(self):
-        return "Typedef \"%s\""%self.name
+        return "Typedef \"%s\"" % self.name
+
     def py_name(self):
         return self.name
+
     def c_name(self):
         return self.name
 
+
 class StructDescription(Description):
     """Simple container class for a structure or union definition."""
-    def __init__(self,tag,variety,members,opaque,ctype,src=None):
-        Description.__init__(self,src)
+
+    def __init__(self, tag, variety, members, opaque, ctype, src=None):
+        Description.__init__(self, src)
         # The name of the structure minus the "struct" or "union"
-        self.tag=tag 
+        self.tag = tag
         # A string "struct" or "union"
-        self.variety=variety 
+        self.variety = variety
         # A list of pairs of (name,ctype)
-        self.members=members 
+        self.members = members
         # True if struct body was not specified in header file
-        self.opaque=opaque 
+        self.opaque = opaque
         # The original CtypeStruct that created the struct
-        self.ctype=ctype 
+        self.ctype = ctype
+
     def casual_name(self):
-        return "%s \"%s\""%(self.variety.capitalize(),self.tag)
+        return "%s \"%s\"" % (self.variety.capitalize(), self.tag)
+
     def py_name(self):
-        return "%s_%s"%(self.variety,self.tag)
+        return "%s_%s" % (self.variety, self.tag)
+
     def c_name(self):
-        return "%s %s"%(self.variety,self.tag)
+        return "%s %s" % (self.variety, self.tag)
+
 
 class EnumDescription(Description):
     """Simple container class for an enum definition."""
-    def __init__(self,tag,members,ctype,src=None):
-        Description.__init__(self,src)
+
+    def __init__(self, tag, members, ctype, src=None):
+        Description.__init__(self, src)
         # The name of the enum, minus the "enum"
-        self.tag=tag 
+        self.tag = tag
         # A list of (name,value) pairs where value is a number
-        self.members=members 
+        self.members = members
         # The original CtypeEnum that created the enum
-        self.ctype=ctype 
+        self.ctype = ctype
+
     def casual_name(self):
-        return "Enum \"%s\""%self.tag
+        return "Enum \"%s\"" % self.tag
+
     def py_name(self):
-        return "enum_%s"%self.tag
+        return "enum_%s" % self.tag
+
     def c_name(self):
-        return "enum %s"%self.tag
+        return "enum %s" % self.tag
+
 
 class FunctionDescription(Description):
     """Simple container class for a C function."""
-    def __init__(self,name,restype,argtypes,variadic=False,src=None):
-        Description.__init__(self,src)
+
+    def __init__(self, name, restype, argtypes, variadic=False, src=None):
+        Description.__init__(self, src)
         # Name, a string
-        self.name=name 
+        self.name = name
         # Name according to C - stored in case description is renamed
-        self.cname=name 
+        self.cname = name
         # A ctype representing return type
-        self.restype=restype 
+        self.restype = restype
         # A list of ctypes representing the argument types
-        self.argtypes=argtypes 
+        self.argtypes = argtypes
         # Does this function accept a variable number of arguments?
-        self.variadic=variadic 
+        self.variadic = variadic
+
     def casual_name(self):
-        return "Function \"%s\""%self.name
+        return "Function \"%s\"" % self.name
+
     def py_name(self):
         return self.name
+
     def c_name(self):
         return self.cname
 
+
 class VariableDescription(Description):
     """Simple container class for a C variable declaration."""
-    def __init__(self,name,ctype,src=None):
-        Description.__init__(self,src)
+
+    def __init__(self, name, ctype, src=None):
+        Description.__init__(self, src)
         # Name, a string
-        self.name=name 
+        self.name = name
         # Name according to C - stored in case description is renamed
-        self.cname=name 
+        self.cname = name
         # The type of the variable
-        self.ctype=ctype 
+        self.ctype = ctype
+
     def casual_name(self):
-        return "Variable \"%s\""%self.name
+        return "Variable \"%s\"" % self.name
+
     def py_name(self):
         return self.name
+
     def c_name(self):
         return self.cname
 
+
 class MacroDescription(Description):
     """Simple container class for a C macro."""
-    def __init__(self,name,params,expr,src=None):
-        Description.__init__(self,src)
+
+    def __init__(self, name, params, expr, src=None):
+        Description.__init__(self, src)
         self.name = name
         self.params = params
-        self.expr = expr # ExpressionNode for the macro's body
+        self.expr = expr  # ExpressionNode for the macro's body
+
     def casual_name(self):
-        return "Macro \"%s\""%self.name
+        return "Macro \"%s\"" % self.name
+
     def py_name(self):
         return self.name
+
     def c_name(self):
-        return self.name
+        return self.name

+ 102 - 75
lib/python/ctypes/ctypesgencore/expressions.py

@@ -23,9 +23,11 @@ import keyword
 #
 # On the other hand, this would be a challenge to write.
 
+
 class EvaluationContext(object):
     '''Interface for evaluating expression nodes.
     '''
+
     def evaluate_identifier(self, name):
         warnings.warn('Attempt to evaluate identifier "%s" failed' % name)
         return 0
@@ -33,38 +35,42 @@ class EvaluationContext(object):
     def evaluate_sizeof(self, type):
         warnings.warn('Attempt to evaluate sizeof "%s" failed' % str(type))
         return 0
-    
+
     def evaluate_sizeof(self, object):
         warnings.warn('Attempt to evaluate sizeof object "%s" failed' % str(object))
         return 0
-    
+
     def evaluate_parameter(self, name):
         warnings.warn('Attempt to evaluate parameter "%s" failed' % name)
         return 0
 
+
 class ExpressionNode(object):
+
     def __init__(self):
         self.errors = []
-    
-    def error(self,message,cls = None):
-        self.errors.append((message,cls))
-    
+
+    def error(self, message, cls=None):
+        self.errors.append((message, cls))
+
     def __repr__(self):
         try:
             string = repr(self.py_string(True))
         except ValueError:
             string = "<error in expression node>"
         return "<ExpressionNode: %s>" % string
-    
-    def visit(self,visitor):
-        for error,cls in self.errors:
-            visitor.visit_error(error,cls)
+
+    def visit(self, visitor):
+        for error, cls in self.errors:
+            visitor.visit_error(error, cls)
+
 
 class ConstantExpressionNode(ExpressionNode):
+
     def __init__(self, value):
         ExpressionNode.__init__(self)
         self.value = value
-    
+
     def evaluate(self, context):
         return self.value
 
@@ -82,40 +88,46 @@ class ConstantExpressionNode(ExpressionNode):
             return "float('-inf')"
         return repr(self.value)
 
+
 class IdentifierExpressionNode(ExpressionNode):
+
     def __init__(self, name):
         ExpressionNode.__init__(self)
         self.name = name
 
     def evaluate(self, context):
         return context.evaluate_identifier(self.name)
-    
+
     def visit(self, visitor):
         visitor.visit_identifier(self.name)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def py_string(self, can_be_ctype):
         # Errors will be thrown in generated code if identifier evaluates
         # to a ctypes object, and can_be_ctype is False.
         return self.name
 
+
 class ParameterExpressionNode(ExpressionNode):
+
     def __init__(self, name):
         ExpressionNode.__init__(self)
         self.name = name
-    
+
     def evaluate(self, context):
         return context.evaluate_parameter(self.name)
-    
+
     def visit(self, visitor):
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def py_string(self, can_be_ctype):
         # Errors will be thrown in generated code if parameter is
         # a ctypes object, and can_be_ctype is False.
         return self.name
 
+
 class UnaryExpressionNode(ExpressionNode):
+
     def __init__(self, name, op, format, child_can_be_ctype, child):
         ExpressionNode.__init__(self)
         self.name = name
@@ -123,31 +135,33 @@ class UnaryExpressionNode(ExpressionNode):
         self.format = format
         self.child_can_be_ctype = child_can_be_ctype
         self.child = child
-    
+
     def visit(self, visitor):
         self.child.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
         if self.op:
             return self.op(self.child.evaluate(context))
         else:
-            raise ValueError,"The C operator \"%s\" can't be evaluated right " \
-                "now" % self.name
+            raise ValueError("The C operator \"%s\" can't be evaluated right "
+                             "now" % self.name)
 
     def py_string(self, can_be_ctype):
         return self.format % \
             self.child.py_string(self.child_can_be_ctype and can_be_ctype)
 
+
 class SizeOfExpressionNode(ExpressionNode):
+
     def __init__(self, child):
         ExpressionNode.__init__(self)
         self.child = child
-    
+
     def visit(self, visitor):
         self.child.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
         if isinstance(self.child, CtypesType):
             return context.evaluate_sizeof(self.child)
@@ -160,7 +174,9 @@ class SizeOfExpressionNode(ExpressionNode):
         else:
             return 'sizeof(%s)' % self.child.py_string(True)
 
+
 class BinaryExpressionNode(ExpressionNode):
+
     def __init__(self, name, op, format, can_be_ctype, left, right):
         ExpressionNode.__init__(self)
         self.name = name
@@ -169,38 +185,40 @@ class BinaryExpressionNode(ExpressionNode):
         self.can_be_ctype = can_be_ctype
         self.left = left
         self.right = right
-    
+
     def visit(self, visitor):
         self.left.visit(visitor)
         self.right.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
         if self.op:
-           return self.op(self.left.evaluate(context), 
-                          self.right.evaluate(context))
+            return self.op(self.left.evaluate(context),
+                           self.right.evaluate(context))
         else:
-            raise ValueError,"The C operator \"%s\" can't be evaluated right " \
-                "now" % self.name
+            raise ValueError("The C operator \"%s\" can't be evaluated right "
+                             "now" % self.name)
 
     def py_string(self, can_be_ctype):
         return self.format % \
             (self.left.py_string(self.can_be_ctype[0] and can_be_ctype),
              self.right.py_string(self.can_be_ctype[0] and can_be_ctype))
 
+
 class ConditionalExpressionNode(ExpressionNode):
+
     def __init__(self, cond, yes, no):
         ExpressionNode.__init__(self)
         self.cond = cond
         self.yes = yes
         self.no = no
-    
+
     def visit(self, visitor):
         self.cond.visit(visitor)
         self.yes.visit(visitor)
         self.no.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
         if self.cond.evaluate(context):
             return self.yes.evaluate(context)
@@ -213,100 +231,109 @@ class ConditionalExpressionNode(ExpressionNode):
              self.cond.py_string(True),
              self.no.py_string(can_be_ctype))
 
+
 class AttributeExpressionNode(ExpressionNode):
+
     def __init__(self, op, format, base, attribute):
         ExpressionNode.__init__(self)
         self.op = op
         self.format = format
         self.base = base
         self.attribute = attribute
-        
-        # Attribute access will raise parse errors if you don't do this. 
-        # Fortunately, the processor module does the same thing to 
+
+        # Attribute access will raise parse errors if you don't do this.
+        # Fortunately, the processor module does the same thing to
         # the struct member name.
         if self.attribute in keyword.kwlist:
-            self.attribute = "_"+self.attribute
-    
-    def visit(self,visitor):
+            self.attribute = "_" + self.attribute
+
+    def visit(self, visitor):
         self.base.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
-        return self.op(self.base.evalute(context),self.attribute)
-    
+        return self.op(self.base.evalute(context), self.attribute)
+
     def py_string(self, can_be_ctype):
         if can_be_ctype:
             return self.format % (self.base.py_string(can_be_ctype),
                                   self.attribute)
         else:
-            return "(%s.value)" % (self.format % \
-                    (self.base.py_string(can_be_ctype), self.attribute))
+            return "(%s.value)" % (self.format %
+                                   (self.base.py_string(can_be_ctype), self.attribute))
+
 
 class CallExpressionNode(ExpressionNode):
-    def __init__(self,function,arguments):
+
+    def __init__(self, function, arguments):
         ExpressionNode.__init__(self)
         self.function = function
         self.arguments = arguments
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         self.function.visit(visitor)
         for arg in self.arguments:
             arg.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
-    def evaluate(self,context):
+        ExpressionNode.visit(self, visitor)
+
+    def evaluate(self, context):
         arguments = [arg.evaluate(context) for arg in self.arguments]
         return self.function.evaluate(context)(*arguments)
-    
+
     def py_string(self, can_be_ctype):
         function = self.function.py_string(can_be_ctype)
         arguments = [x.py_string(can_be_ctype) for x in self.arguments]
         if can_be_ctype:
-            return '(%s (%s))' % (function,", ".join(arguments))
+            return '(%s (%s))' % (function, ", ".join(arguments))
         else:
-            return '((%s (%s)).value)' % (function,", ".join(arguments))
+            return '((%s (%s)).value)' % (function, ", ".join(arguments))
 
 # There seems not to be any reasonable way to translate C typecasts
 # into Python. Ctypesgen doesn't try, except for the special case of NULL.
+
+
 class TypeCastExpressionNode(ExpressionNode):
+
     def __init__(self, base, ctype):
         ExpressionNode.__init__(self)
         self.base = base
         self.ctype = ctype
         self.isnull = isinstance(ctype, CtypesPointer) and \
-                      isinstance(base, ConstantExpressionNode) and \
-                      base.value == 0
-    
-    def visit(self,visitor):
+            isinstance(base, ConstantExpressionNode) and \
+            base.value == 0
+
+    def visit(self, visitor):
         # No need to visit ctype because it isn't actually used
         self.base.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
-    def evaluate(self,context):
+        ExpressionNode.visit(self, visitor)
+
+    def evaluate(self, context):
         if self.isnull:
             return None
         else:
             return self.base.evaluate(context)
-    
+
     def py_string(self, can_be_ctype):
         if self.isnull:
             return "None"
         else:
             return self.base.py_string(can_be_ctype)
 
+
 class UnsupportedExpressionNode(ExpressionNode):
-    def __init__(self,message):
+
+    def __init__(self, message):
         ExpressionNode.__init__(self)
         self.message = message
-        self.error(message,'unsupported-type')
-    
-    def evaluate(self,context):
-        raise ValueError, "Tried to evaluate an unsupported expression " \
-            "node: %s" % self.message
-    
+        self.error(message, 'unsupported-type')
+
+    def evaluate(self, context):
+        raise ValueError("Tried to evaluate an unsupported expression "
+                         "node: %s" % self.message)
+
     def __repr__(self):
         return "<UnsupportedExpressionNode>"
-    
+
     def py_string(self, can_be_ctype):
-        raise ValueError, "Called py_string() an unsupported expression " \
-            "node: %s" % self.message
+        raise ValueError("Called py_string() an unsupported expression "
+                         "node: %s" % self.message)

+ 68 - 49
lib/python/ctypes/ctypesgencore/libraryloader.py

@@ -2,14 +2,14 @@
 # Copyright (c) 2008 David James
 # Copyright (c) 2006-2008 Alex Holkner
 # All rights reserved.
-# 
+#
 # Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions 
+# modification, are permitted provided that the following conditions
 # are met:
 #
 #  * Redistributions of source code must retain the above copyright
 #    notice, this list of conditions and the following disclaimer.
-#  * Redistributions in binary form must reproduce the above copyright 
+#  * Redistributions in binary form must reproduce the above copyright
 #    notice, this list of conditions and the following disclaimer in
 #    the documentation and/or other materials provided with the
 #    distribution.
@@ -32,31 +32,37 @@
 # POSSIBILITY OF SUCH DAMAGE.
 # ----------------------------------------------------------------------------
 
-import os.path, re, sys, glob
+import os.path
+import re
+import sys
+import glob
 import ctypes
 import ctypes.util
 
+
 def _environ_path(name):
     if name in os.environ:
         return os.environ[name].split(":")
     else:
         return []
 
+
 class LibraryLoader(object):
+
     def __init__(self):
-        self.other_dirs=[]
-    
-    def load_library(self,libname):
+        self.other_dirs = []
+
+    def load_library(self, libname):
         """Given the name of a library, load it."""
         paths = self.getpaths(libname)
-        
+
         for path in paths:
             if os.path.exists(path):
                 return self.load(path)
-        
-        raise ImportError,"%s not found." % libname
-    
-    def load(self,path):
+
+        raise ImportError("%s not found." % libname)
+
+    def load(self, path):
         """Given a path to a library, load it."""
         try:
             # Darwin requires dlopen to be called with mode RTLD_GLOBAL instead
@@ -68,42 +74,44 @@ class LibraryLoader(object):
             else:
                 return ctypes.cdll.LoadLibrary(path)
         except OSError as e:
-            raise ImportError,e
-    
-    def getpaths(self,libname):
+            raise ImportError(e)
+
+    def getpaths(self, libname):
         """Return a list of paths where the library might be found."""
         if os.path.isabs(libname):
             yield libname
-        
+
         else:
             for path in self.getplatformpaths(libname):
                 yield path
-            
+
             path = ctypes.util.find_library(libname)
-            if path: yield path
-    
+            if path:
+                yield path
+
     def getplatformpaths(self, libname):
         return []
 
 # Darwin (Mac OS X)
 
+
 class DarwinLibraryLoader(LibraryLoader):
     name_formats = ["lib%s.dylib", "lib%s.so", "lib%s.bundle", "%s.dylib",
-                "%s.so", "%s.bundle", "%s"]
-    
-    def getplatformpaths(self,libname):
+                    "%s.so", "%s.bundle", "%s"]
+
+    def getplatformpaths(self, libname):
         if os.path.pathsep in libname:
             names = [libname]
         else:
             names = [format % libname for format in self.name_formats]
-        
+
         for dir in self.getdirs(libname):
             for name in names:
-                yield os.path.join(dir,name)
-    
-    def getdirs(self,libname):
+                yield os.path.join(dir, name)
+
+    def getdirs(self, libname):
         '''Implements the dylib search as specified in Apple documentation:
-        
+
         http://developer.apple.com/documentation/DeveloperTools/Conceptual/
             DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html
 
@@ -116,9 +124,9 @@ class DarwinLibraryLoader(LibraryLoader):
         if not dyld_fallback_library_path:
             dyld_fallback_library_path = [os.path.expanduser('~/lib'),
                                           '/usr/local/lib', '/usr/lib']
-        
+
         dirs = []
-        
+
         if '/' in libname:
             dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
         else:
@@ -127,7 +135,7 @@ class DarwinLibraryLoader(LibraryLoader):
 
         dirs.extend(self.other_dirs)
         dirs.append(".")
-        
+
         if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
             dirs.append(os.path.join(
                 os.environ['RESOURCEPATH'],
@@ -135,14 +143,15 @@ class DarwinLibraryLoader(LibraryLoader):
                 'Frameworks'))
 
         dirs.extend(dyld_fallback_library_path)
-        
+
         return dirs
 
 # Posix
 
+
 class PosixLibraryLoader(LibraryLoader):
     _ld_so_cache = None
-    
+
     def _create_ld_so_cache(self):
         # Recreate search path followed by ld.so.  This is going to be
         # slow to build, and incorrect (ld.so uses ld.so.cache, which may
@@ -153,17 +162,19 @@ class PosixLibraryLoader(LibraryLoader):
 
         directories = []
         for name in ("LD_LIBRARY_PATH",
-                     "SHLIB_PATH", # HPUX
-                     "LIBPATH", # OS/2, AIX
-                     "LIBRARY_PATH", # BE/OS
-                    ):
+                     "SHLIB_PATH",  # HPUX
+                     "LIBPATH",  # OS/2, AIX
+                     "LIBRARY_PATH",  # BE/OS
+                     ):
             if name in os.environ:
                 directories.extend(os.environ[name].split(os.pathsep))
         directories.extend(self.other_dirs)
         directories.append(".")
 
-        try: directories.extend([dir.strip() for dir in open('/etc/ld.so.conf')])
-        except IOError: pass
+        try:
+            directories.extend([dir.strip() for dir in open('/etc/ld.so.conf')])
+        except IOError:
+            pass
 
         directories.extend(['/lib', '/usr/lib', '/lib64', '/usr/lib64'])
 
@@ -178,7 +189,7 @@ class PosixLibraryLoader(LibraryLoader):
                     # Index by filename
                     if file not in cache:
                         cache[file] = path
-                    
+
                     # Index by library name
                     match = lib_re.match(file)
                     if match:
@@ -189,37 +200,44 @@ class PosixLibraryLoader(LibraryLoader):
                 pass
 
         self._ld_so_cache = cache
-    
+
     def getplatformpaths(self, libname):
         if self._ld_so_cache is None:
             self._create_ld_so_cache()
 
         result = self._ld_so_cache.get(libname)
-        if result: yield result
+        if result:
+            yield result
 
         path = ctypes.util.find_library(libname)
-        if path: yield os.path.join("/lib",path)
+        if path:
+            yield os.path.join("/lib", path)
 
 # Windows
 
+
 class _WindowsLibrary(object):
+
     def __init__(self, path):
         self.cdll = ctypes.cdll.LoadLibrary(path)
         self.windll = ctypes.windll.LoadLibrary(path)
 
     def __getattr__(self, name):
-        try: return getattr(self.cdll,name)
+        try:
+            return getattr(self.cdll, name)
         except AttributeError:
-            try: return getattr(self.windll,name)
+            try:
+                return getattr(self.windll, name)
             except AttributeError:
                 raise
 
+
 class WindowsLibraryLoader(LibraryLoader):
     name_formats = ["%s.dll", "lib%s.dll"]
-    
+
     def load(self, path):
         return _WindowsLibrary(path)
-    
+
     def getplatformpaths(self, libname):
         if os.path.sep not in libname:
             for name in self.name_formats:
@@ -233,13 +251,14 @@ class WindowsLibraryLoader(LibraryLoader):
 # the Ctypesgen maintainers.
 
 loaderclass = {
-    "darwin":   DarwinLibraryLoader,
-    "cygwin":   WindowsLibraryLoader,
-    "win32":    WindowsLibraryLoader
+    "darwin": DarwinLibraryLoader,
+    "cygwin": WindowsLibraryLoader,
+    "win32": WindowsLibraryLoader
 }
 
 loader = loaderclass.get(sys.platform, PosixLibraryLoader)()
 
+
 def add_library_search_dirs(other_dirs):
     loader.other_dirs = other_dirs
 

+ 6 - 3
lib/python/ctypes/ctypesgencore/messages.py

@@ -22,13 +22,16 @@ Warning classes are:
 
 import sys
 
-__all__ = ["error_message","warning_message","status_message"]
+__all__ = ["error_message", "warning_message", "status_message"]
 
-def error_message(msg,cls=None):
+
+def error_message(msg, cls=None):
     print "Error: %s" % msg
 
-def warning_message(msg,cls=None):
+
+def warning_message(msg, cls=None):
     print "Warning: %s" % msg
 
+
 def status_message(msg):
     print "Status: %s" % msg

+ 4 - 2
lib/python/ctypes/ctypesgencore/options.py

@@ -8,9 +8,10 @@ would be a pain. So this module exists to provide a "default" options object
 for convenience.
 """
 
-import optparse, copy
+import optparse
+import copy
 
-default_values={
+default_values = {
     "other_headers": [],
     "modules": [],
     "include_search_paths": [],
@@ -33,5 +34,6 @@ default_values={
     "strip_build_path": None
 }
 
+
 def get_default_options():
     return optparse.Values(copy.deepcopy(default_values))

+ 3 - 2
lib/python/ctypes/ctypesgencore/parser/__init__.py

@@ -16,9 +16,10 @@ for more information.
 
 from datacollectingparser import DataCollectingParser
 
+
 def parse(headers, options):
-    parser=DataCollectingParser(headers, options)
+    parser = DataCollectingParser(headers, options)
     parser.parse()
     return parser.data()
 
-__all__ = ["parse"]
+__all__ = ["parse"]

+ 25 - 4
lib/python/ctypes/ctypesgencore/parser/cdeclarations.py

@@ -12,7 +12,9 @@ __docformat__ = 'restructuredtext'
 # C Object Model
 # --------------------------------------------------------------------------
 
+
 class Declaration(object):
+
     def __init__(self):
         self.declarator = None
         self.type = Type()
@@ -28,8 +30,10 @@ class Declaration(object):
         l = ['%s=%r' % (k, v) for k, v in d.items()]
         return 'Declaration(%s)' % ', '.join(l)
 
+
 class Declarator(object):
     pointer = None
+
     def __init__(self):
         self.identifier = None
         self.initializer = None
@@ -52,8 +56,10 @@ class Declarator(object):
             s += '(' + ', '.join([repr(p) for p in self.parameters]) + ')'
         return s
 
+
 class Pointer(Declarator):
     pointer = None
+
     def __init__(self):
         super(Pointer, self).__init__()
         self.qualifiers = []
@@ -65,14 +71,16 @@ class Pointer(Declarator):
         return 'POINTER%s(%r)' % (q, self.pointer) + \
             super(Pointer, self).__repr__()
 
+
 class Array(object):
+
     def __init__(self):
         self.size = None
         self.array = None
 
     def __repr__(self):
         if self.size:
-            a =  '[%r]' % self.size
+            a = '[%r]' % self.size
         else:
             a = '[]'
         if self.array:
@@ -80,7 +88,9 @@ class Array(object):
         else:
             return a
 
+
 class Parameter(object):
+
     def __init__(self):
         self.type = Type()
         self.storage = None
@@ -99,6 +109,7 @@ class Parameter(object):
 
 
 class Type(object):
+
     def __init__(self):
         self.qualifiers = []
         self.specifiers = []
@@ -108,13 +119,17 @@ class Type(object):
 
 # These are used only internally.
 
+
 class StorageClassSpecifier(str):
     pass
 
+
 class TypeSpecifier(str):
     pass
 
+
 class StructTypeSpecifier(object):
+
     def __init__(self, is_union, tag, declarations):
         self.is_union = is_union
         self.tag = tag
@@ -131,11 +146,13 @@ class StructTypeSpecifier(object):
             s += ' {%s}' % '; '.join([repr(d) for d in self.declarations])
         return s
 
+
 class EnumSpecifier(object):
+
     def __init__(self, tag, enumerators, src=None):
         self.tag = tag
         self.enumerators = enumerators
-        self.src=src
+        self.src = src
 
     def __repr__(self):
         s = 'enum'
@@ -145,7 +162,9 @@ class EnumSpecifier(object):
             s += ' {%s}' % ', '.join([repr(e) for e in self.enumerators])
         return s
 
+
 class Enumerator(object):
+
     def __init__(self, name, expression):
         self.name = name
         self.expression = expression
@@ -156,19 +175,21 @@ class Enumerator(object):
             s += ' = %r' % self.expression
         return s
 
+
 class TypeQualifier(str):
     pass
 
+
 def apply_specifiers(specifiers, declaration):
     '''Apply specifiers to the declaration (declaration may be
     a Parameter instead).'''
     for s in specifiers:
-        if type(s) == StorageClassSpecifier:
+        if isinstance(s, StorageClassSpecifier):
             if declaration.storage:
                 # Multiple storage classes, technically an error... ignore it
                 pass
             declaration.storage = s
         elif type(s) in (TypeSpecifier, StructTypeSpecifier, EnumSpecifier):
             declaration.type.specifiers.append(s)
-        elif type(s) == TypeQualifier:
+        elif isinstance(s, TypeQualifier):
             declaration.type.qualifiers.append(s)

文件差异内容过多而无法显示
+ 256 - 156
lib/python/ctypes/ctypesgencore/parser/cgrammar.py


+ 35 - 30
lib/python/ctypes/ctypesgencore/parser/cparser.py

@@ -25,7 +25,9 @@ import cdeclarations
 # Lexer
 # --------------------------------------------------------------------------
 
+
 class CLexer(object):
+
     def __init__(self, cparser):
         self.cparser = cparser
         self.type_names = set()
@@ -38,17 +40,17 @@ class CLexer(object):
     def token(self):
         while self.pos < len(self.tokens):
             t = self.tokens[self.pos]
-            
+
             self.pos += 1
 
             if not t:
                 break
-            
+
             if t.type == 'PP_DEFINE':
                 self.in_define = True
             elif t.type == 'PP_END_DEFINE':
                 self.in_define = False
-            
+
             # Transform PP tokens into C tokens
             elif t.type == 'LPAREN':
                 t.type = '('
@@ -57,36 +59,38 @@ class CLexer(object):
             elif t.type == 'IDENTIFIER' and t.value in cgrammar.keywords:
                 t.type = t.value.upper()
             elif t.type == 'IDENTIFIER' and t.value in self.type_names:
-                if (self.pos < 2 or self.tokens[self.pos-2].type not in
-                    ('ENUM', 'STRUCT', 'UNION')):
+                if (self.pos < 2 or self.tokens[self.pos - 2].type not in
+                        ('ENUM', 'STRUCT', 'UNION')):
                     t.type = 'TYPE_NAME'
-            
+
             t.lexer = self
             t.clexpos = self.pos - 1
-            
+
             return t
         return None
-        
+
 # --------------------------------------------------------------------------
 # Parser
 # --------------------------------------------------------------------------
 
+
 class CParser(object):
     '''Parse a C source file.
 
     Subclass and override the handle_* methods.  Call `parse` with a string
     to parse.
     '''
+
     def __init__(self, options, stddef_types=True, gnu_types=True):
-        self.preprocessor_parser = preprocessor.PreprocessorParser(options,self)
+        self.preprocessor_parser = preprocessor.PreprocessorParser(options, self)
         self.parser = yacc.Parser()
-        prototype = yacc.yacc(method        = 'LALR',
-                              debug         = False,
-                              module        = cgrammar,
-                              write_tables  = True,
-                              outputdir     = os.path.dirname(__file__),
-                              optimize      = True)
-        
+        prototype = yacc.yacc(method='LALR',
+                              debug=False,
+                              module=cgrammar,
+                              write_tables=True,
+                              outputdir=os.path.dirname(__file__),
+                              optimize=True)
+
         # If yacc is reading tables from a file, then it won't find the error
         # function... need to set it manually
         prototype.errorfunc = cgrammar.p_error
@@ -102,7 +106,7 @@ class CParser(object):
             self.lexer.type_names.add('__builtin_va_list')
         if sys.platform == 'win32':
             self.lexer.type_names.add('__int64')
-        
+
     def parse(self, filename, debug=False):
         '''Parse a file.
 
@@ -120,22 +124,22 @@ class CParser(object):
     # ----------------------------------------------------------------------
 
     def handle_error(self, message, filename, lineno):
-        '''A parse error occurred.  
-        
+        '''A parse error occurred.
+
         The default implementation prints `lineno` and `message` to stderr.
         The parser will try to recover from errors by synchronising at the
         next semicolon.
         '''
         print >> sys.stderr, '%s:%s %s' % (filename, lineno, message)
-    
+
     def handle_pp_error(self, message):
         '''The C preprocessor emitted an error.
-        
+
         The default implementatin prints the error to stderr. If processing
         can continue, it will.
         '''
         print >> sys.stderr, 'Preprocessor:', message
-    
+
     def handle_status(self, message):
         '''Progress information.
 
@@ -144,7 +148,7 @@ class CParser(object):
         print >> sys.stderr, message
 
     def handle_define(self, name, params, value, filename, lineno):
-        '''#define `name` `value` 
+        '''#define `name` `value`
         or #define `name`(`params`) `value`
 
         name is a string
@@ -154,19 +158,19 @@ class CParser(object):
 
     def handle_define_constant(self, name, value, filename, lineno):
         '''#define `name` `value`
-        
+
         name is a string
         value is an ExpressionNode or None
         '''
-    
+
     def handle_define_macro(self, name, params, value, filename, lineno):
         '''#define `name`(`params`) `value`
-        
+
         name is a string
         params is a list of strings
         value is an ExpressionNode or None
         '''
-    
+
     def impl_handle_declaration(self, declaration, filename, lineno):
         '''Internal method that calls `handle_declaration`.  This method
         also adds any new type definitions to the lexer's list of valid type
@@ -183,13 +187,14 @@ class CParser(object):
         self.handle_declaration(declaration, filename, lineno)
 
     def handle_declaration(self, declaration, filename, lineno):
-        '''A declaration was encountered.  
-        
+        '''A declaration was encountered.
+
         `declaration` is an instance of Declaration.  Where a declaration has
         multiple initialisers, each is returned as a separate declaration.
         '''
         pass
 
+
 class DebugCParser(CParser):
     '''A convenience class that prints each invocation of a handle_* method to
     stdout.
@@ -203,6 +208,6 @@ class DebugCParser(CParser):
 
     def handle_declaration(self, declaration, filename, lineno):
         print declaration
-        
+
 if __name__ == '__main__':
     DebugCParser().parse(sys.argv[1], debug=True)

+ 44 - 40
lib/python/ctypes/ctypesgencore/parser/ctypesparser.py

@@ -17,12 +17,13 @@ from ctypesgencore.ctypedescs import *
 from cdeclarations import *
 from ctypesgencore.expressions import *
 
-def get_ctypes_type(typ, declarator, check_qualifiers=False):       
+
+def get_ctypes_type(typ, declarator, check_qualifiers=False):
     signed = True
     typename = 'int'
     longs = 0
     t = None
-    
+
     for specifier in typ.specifiers:
         if isinstance(specifier, StructTypeSpecifier):
             t = make_struct_from_specifier(specifier)
@@ -36,15 +37,15 @@ def get_ctypes_type(typ, declarator, check_qualifiers=False):
             longs += 1
         else:
             typename = str(specifier)
-    
+
     if not t:
         # It is a numeric type of some sort
-        if (typename,signed,longs) in ctypes_type_map:
-            t = CtypesSimple(typename,signed,longs)
-        
+        if (typename, signed, longs) in ctypes_type_map:
+            t = CtypesSimple(typename, signed, longs)
+
         elif signed and not longs:
             t = CtypesTypedef(typename)
-        
+
         else:
             name = " ".join(typ.specifiers)
             if typename in [x[0] for x in ctypes_type_map.keys()]:
@@ -54,10 +55,10 @@ def get_ctypes_type(typ, declarator, check_qualifiers=False):
                 error = "Ctypes does not support adding additional " \
                     "specifiers to typedefs, such as \"%s\"" % name
             t = CtypesTypedef(name)
-            t.error(error,cls='unsupported-type')
-        
+            t.error(error, cls='unsupported-type')
+
         if declarator and declarator.bitfield:
-            t = CtypesBitfield(t,declarator.bitfield)
+            t = CtypesBitfield(t, declarator.bitfield)
 
     qualifiers = []
     qualifiers.extend(typ.qualifiers)
@@ -67,50 +68,51 @@ def get_ctypes_type(typ, declarator, check_qualifiers=False):
 
             params = []
             for param in declarator.parameters:
-                if param=="...":
+                if param == "...":
                     break
                 params.append(get_ctypes_type(param.type, param.declarator))
             t = CtypesFunction(t, params, variadic)
-        
+
         a = declarator.array
         while a:
             t = CtypesArray(t, a.size)
             a = a.array
 
         qualifiers.extend(declarator.qualifiers)
-        
+
         t = CtypesPointer(t, declarator.qualifiers)
-        
+
         declarator = declarator.pointer
-    
+
     if declarator and declarator.parameters is not None:
         variadic = "..." in declarator.parameters
 
         params = []
         for param in declarator.parameters:
-            if param=="...":
+            if param == "...":
                 break
             params.append(get_ctypes_type(param.type, param.declarator))
         t = CtypesFunction(t, params, variadic)
-    
+
     if declarator:
         a = declarator.array
         while a:
             t = CtypesArray(t, a.size)
             a = a.array
-    
+
     if isinstance(t, CtypesPointer) and \
        isinstance(t.destination, CtypesSimple) and \
-       t.destination.name=="char" and \
+       t.destination.name == "char" and \
        t.destination.signed:
-       t = CtypesSpecial("String")
+        t = CtypesSpecial("String")
 
     return t
 
+
 def make_struct_from_specifier(specifier):
-    variety = {True:"union", False:"struct"}[specifier.is_union]
+    variety = {True: "union", False: "struct"}[specifier.is_union]
     tag = specifier.tag
-    
+
     if specifier.declarations:
         members = []
         for declaration in specifier.declarations:
@@ -127,13 +129,14 @@ def make_struct_from_specifier(specifier):
             members.append((name, remove_function_pointer(t)))
     else:
         members = None
-    
-    return CtypesStruct(tag,variety,members,
-                        src=(specifier.filename,specifier.lineno))
+
+    return CtypesStruct(tag, variety, members,
+                        src=(specifier.filename, specifier.lineno))
+
 
 def make_enum_from_specifier(specifier):
     tag = specifier.tag
-    
+
     enumerators = []
     last_name = None
     for e in specifier.enumerators:
@@ -141,32 +144,33 @@ def make_enum_from_specifier(specifier):
             value = e.expression
         else:
             if last_name:
-                value = BinaryExpressionNode("addition", (lambda x,y:x+y),
-                    "(%s + %s)", (False,False),
-                    IdentifierExpressionNode(last_name),
-                    ConstantExpressionNode(1))
+                value = BinaryExpressionNode("addition", (lambda x, y: x + y),
+                                             "(%s + %s)", (False, False),
+                                             IdentifierExpressionNode(last_name),
+                                             ConstantExpressionNode(1))
             else:
                 value = ConstantExpressionNode(0)
-        
-        enumerators.append((e.name,value))
+
+        enumerators.append((e.name, value))
         last_name = e.name
-    
+
     return CtypesEnum(tag, enumerators,
-                      src=(specifier.filename,specifier.lineno))
+                      src=(specifier.filename, specifier.lineno))
+
 
 class CtypesParser(CParser):
     '''Parse a C file for declarations that can be used by ctypes.
-    
+
     Subclass and override the handle_ctypes_* methods.
     '''
 
     def handle_declaration(self, declaration, filename, lineno):
         t = get_ctypes_type(declaration.type, declaration.declarator)
-        
+
         if type(t) in (CtypesStruct, CtypesEnum):
             self.handle_ctypes_new_type(
                 remove_function_pointer(t), filename, lineno)
-        
+
         declarator = declaration.declarator
         if declarator is None:
             # XXX TEMPORARY while struct with no typedef not filled in
@@ -177,17 +181,17 @@ class CtypesParser(CParser):
         if declaration.storage == 'typedef':
             self.handle_ctypes_typedef(
                 name, remove_function_pointer(t), filename, lineno)
-        elif type(t) == CtypesFunction:
+        elif isinstance(t, CtypesFunction):
             self.handle_ctypes_function(
                 name, t.restype, t.argtypes, t.variadic, filename, lineno)
         elif declaration.storage != 'static':
             self.handle_ctypes_variable(name, t, filename, lineno)
 
     # ctypes parser interface.  Override these methods in your subclass.
-    
+
     def handle_ctypes_new_type(self, ctype, filename, lineno):
         pass
-    
+
     def handle_ctypes_typedef(self, name, ctype, filename, lineno):
         pass
 

+ 135 - 133
lib/python/ctypes/ctypesgencore/parser/datacollectingparser.py

@@ -4,7 +4,7 @@
 DataCollectingParser subclasses ctypesparser.CtypesParser and builds Description
 objects from the CtypesType objects and other information from CtypesParser.
 After parsing is complete, a DescriptionCollection object can be retrieved by
-calling DataCollectingParser.data(). 
+calling DataCollectingParser.data().
 """
 
 import ctypesparser
@@ -15,6 +15,7 @@ from ctypesgencore.messages import *
 from tempfile import mkstemp
 import os
 
+
 class DataCollectingParser(ctypesparser.CtypesParser,
                            ctypesparser.CtypesTypeVisitor):
     """Main class for the Parser component. Steps for use:
@@ -22,41 +23,42 @@ class DataCollectingParser(ctypesparser.CtypesParser,
     p.parse()
     data=p.data() #A dictionary of constants, enums, structs, functions, etc.
     """
-    def __init__(self,headers,options):
-        ctypesparser.CtypesParser.__init__(self,options)
-        self.headers=headers
-        self.options=options
-        
-        self.constants=[]
-        self.typedefs=[]
-        self.structs=[]
-        self.enums=[]
-        self.functions=[]
-        self.variables=[]
-        self.macros=[]
-        
-        self.all=[]
-        self.output_order=[]
-        
+
+    def __init__(self, headers, options):
+        ctypesparser.CtypesParser.__init__(self, options)
+        self.headers = headers
+        self.options = options
+
+        self.constants = []
+        self.typedefs = []
+        self.structs = []
+        self.enums = []
+        self.functions = []
+        self.variables = []
+        self.macros = []
+
+        self.all = []
+        self.output_order = []
+
         # NULL is a useful macro to have defined
         null = ConstantExpressionNode(None)
-        nullmacro = ConstantDescription("NULL",null,("<built-in>",1))
+        nullmacro = ConstantDescription("NULL", null, ("<built-in>", 1))
         self.constants.append(nullmacro)
         self.all.append(nullmacro)
         self.output_order.append(("constant", nullmacro))
-        
+
         # A list of tuples describing macros; saved to be processed after
         # everything else has been parsed
         self.saved_macros = []
         # A set of structs that are already known
-        self.already_seen_structs=set() 
+        self.already_seen_structs = set()
         # A dict of structs that have only been seen in opaque form
-        self.already_seen_opaque_structs={} 
+        self.already_seen_opaque_structs = {}
         # A set of enums that are already known
-        self.already_seen_enums=set() 
+        self.already_seen_enums = set()
         # A dict of enums that have only been seen in opaque form
-        self.already_seen_opaque_enums={}
-            
+        self.already_seen_opaque_enums = {}
+
     def parse(self):
         fd, fname = mkstemp(suffix=".h")
         f = os.fdopen(fd, 'w+b')
@@ -66,17 +68,17 @@ class DataCollectingParser(ctypesparser.CtypesParser,
             print >>f, '#include "%s"' % os.path.abspath(header)
         f.flush()
         f.close()
-        ctypesparser.CtypesParser.parse(self,fname,None)
+        ctypesparser.CtypesParser.parse(self, fname, None)
         os.remove(fname)
 
-        for name, params, expr, (filename,lineno) in self.saved_macros:
+        for name, params, expr, (filename, lineno) in self.saved_macros:
             self.handle_macro(name, params, expr, filename, lineno)
-            
+
     def handle_define_constant(self, name, expr, filename, lineno):
         # Called by CParser
         # Save to handle later
         self.saved_macros.append((name, None, expr, (filename, lineno)))
-    
+
     def handle_define_unparseable(self, name, params, value, filename, lineno):
         # Called by CParser
         if params:
@@ -86,66 +88,66 @@ class DataCollectingParser(ctypesparser.CtypesParser,
             original_string = "#define %s %s" % \
                 (name, " ".join(value))
         macro = MacroDescription(name, params, None,
-                                 src = (filename,lineno))
+                                 src=(filename, lineno))
         macro.error("Could not parse macro \"%s\"" % original_string,
-                    cls = 'macro')
+                    cls='macro')
         macro.original_string = original_string
         self.macros.append(macro)
         self.all.append(macro)
-        self.output_order.append(('macro',macro))
-    
+        self.output_order.append(('macro', macro))
+
     def handle_define_macro(self, name, params, expr, filename, lineno):
         # Called by CParser
         # Save to handle later
-        self.saved_macros.append((name, params, expr, (filename,lineno)))
-    
+        self.saved_macros.append((name, params, expr, (filename, lineno)))
+
     def handle_ctypes_typedef(self, name, ctype, filename, lineno):
         # Called by CtypesParser
         ctype.visit(self)
-        
-        typedef=TypedefDescription(name,
-                                   ctype,
-                                   src=(filename,repr(lineno)))
-        
+
+        typedef = TypedefDescription(name,
+                                     ctype,
+                                     src=(filename, repr(lineno)))
+
         self.typedefs.append(typedef)
         self.all.append(typedef)
-        self.output_order.append(('typedef',typedef))
-    
+        self.output_order.append(('typedef', typedef))
+
     def handle_ctypes_new_type(self, ctype, filename, lineno):
         # Called by CtypesParser
-        if isinstance(ctype,ctypesparser.CtypesEnum):
+        if isinstance(ctype, ctypesparser.CtypesEnum):
             self.handle_enum(ctype, filename, lineno)
         else:
             self.handle_struct(ctype, filename, lineno)
-    
+
     def handle_ctypes_function(self, name, restype, argtypes, variadic,
                                filename, lineno):
         # Called by CtypesParser
         restype.visit(self)
         for argtype in argtypes:
             argtype.visit(self)
-        
-        function=FunctionDescription(name,
-                                     restype,
-                                     argtypes,
-                                     variadic = variadic,
-                                     src=(filename,repr(lineno)))
-        
+
+        function = FunctionDescription(name,
+                                       restype,
+                                       argtypes,
+                                       variadic=variadic,
+                                       src=(filename, repr(lineno)))
+
         self.functions.append(function)
         self.all.append(function)
-        self.output_order.append(('function',function))
+        self.output_order.append(('function', function))
 
     def handle_ctypes_variable(self, name, ctype, filename, lineno):
         # Called by CtypesParser
         ctype.visit(self)
-        
-        variable=VariableDescription(name,
-                                     ctype,
-                                     src=(filename,repr(lineno)))
-        
+
+        variable = VariableDescription(name,
+                                       ctype,
+                                       src=(filename, repr(lineno)))
+
         self.variables.append(variable)
         self.all.append(variable)
-        self.output_order.append(('variable',variable))
+        self.output_order.append(('variable', variable))
 
     def handle_struct(self, ctypestruct, filename, lineno):
         # Called from within DataCollectingParser
@@ -155,79 +157,79 @@ class DataCollectingParser(ctypesparser.CtypesParser,
         # find a transparent struct with the same tag, we fill in the
         # opaque struct with the information from the transparent struct and
         # move the opaque struct to the end of the struct list.
-        
-        name = "%s %s"%(ctypestruct.variety,ctypestruct.tag)
-        
+
+        name = "%s %s" % (ctypestruct.variety, ctypestruct.tag)
+
         if name in self.already_seen_structs:
             return
-        
+
         if ctypestruct.opaque:
             if name not in self.already_seen_opaque_structs:
                 struct = StructDescription(ctypestruct.tag,
                                            ctypestruct.variety,
-                                           None, # No members
-                                           True, # Opaque
+                                           None,  # No members
+                                           True,  # Opaque
                                            ctypestruct,
-                                           src=(filename,str(lineno)))
-                
-                self.already_seen_opaque_structs[name]=struct
+                                           src=(filename, str(lineno)))
+
+                self.already_seen_opaque_structs[name] = struct
                 self.structs.append(struct)
                 self.all.append(struct)
-                self.output_order.append(('struct',struct))
-        
+                self.output_order.append(('struct', struct))
+
         else:
-            for (membername,ctype) in ctypestruct.members:
+            for (membername, ctype) in ctypestruct.members:
                 ctype.visit(self)
-            
+
             if name in self.already_seen_opaque_structs:
                 # Fill in older version
-                struct=self.already_seen_opaque_structs[name]
+                struct = self.already_seen_opaque_structs[name]
                 struct.opaque = False
                 struct.members = ctypestruct.members
                 struct.ctype = ctypestruct
                 struct.src = ctypestruct.src
-                
-                self.output_order.append(('struct-body',struct))
-                
+
+                self.output_order.append(('struct-body', struct))
+
                 del self.already_seen_opaque_structs[name]
-            
+
             else:
                 struct = StructDescription(ctypestruct.tag,
                                            ctypestruct.variety,
                                            ctypestruct.members,
-                                           False, # Not opaque
-                                           src=(filename,str(lineno)),
-                                           ctype=ctypestruct)                
+                                           False,  # Not opaque
+                                           src=(filename, str(lineno)),
+                                           ctype=ctypestruct)
                 self.structs.append(struct)
                 self.all.append(struct)
-                self.output_order.append(('struct',struct))
-                self.output_order.append(('struct-body',struct))
-            
+                self.output_order.append(('struct', struct))
+                self.output_order.append(('struct-body', struct))
+
             self.already_seen_structs.add(name)
-    
+
     def handle_enum(self, ctypeenum, filename, lineno):
         # Called from within DataCollectingParser.
-        
+
         # Process for handling opaque enums is the same as process for opaque
         # structs. See handle_struct() for more details.
-        
+
         tag = ctypeenum.tag
         if tag in self.already_seen_enums:
             return
-            
+
         if ctypeenum.opaque:
             if tag not in self.already_seen_opaque_enums:
-                enum=EnumDescription(ctypeenum.tag,
-                             ctypeenum.enumerators,
-                             ctypeenum,
-                             src = (filename,str(lineno)))
+                enum = EnumDescription(ctypeenum.tag,
+                                       ctypeenum.enumerators,
+                                       ctypeenum,
+                                       src=(filename, str(lineno)))
                 enum.opaque = True
-                
-                self.already_seen_opaque_enums[tag]=enum
+
+                self.already_seen_opaque_enums[tag] = enum
                 self.enums.append(enum)
                 self.all.append(enum)
-                self.output_order.append(('enum',enum))
-                
+                self.output_order.append(('enum', enum))
+
         else:
             if tag in self.already_seen_opaque_enums:
                 # Fill in older opaque version
@@ -235,87 +237,87 @@ class DataCollectingParser(ctypesparser.CtypesParser,
                 enum.opaque = False
                 enum.ctype = ctypeenum
                 enum.src = ctypeenum.src
-            
+
                 del self.already_seen_opaque_enums[tag]
-            
+
             else:
-                enum=EnumDescription(ctypeenum.tag,
-                                None,
-                                src=(filename,str(lineno)),
-                                ctype=ctypeenum)
+                enum = EnumDescription(ctypeenum.tag,
+                                       None,
+                                       src=(filename, str(lineno)),
+                                       ctype=ctypeenum)
                 enum.opaque = False
-                
+
                 self.enums.append(enum)
                 self.all.append(enum)
-                self.output_order.append(('enum',enum))
-            
+                self.output_order.append(('enum', enum))
+
             self.already_seen_enums.add(tag)
-            
-            for (enumname,expr) in ctypeenum.enumerators:                
-                constant=ConstantDescription(enumname, expr,
-                                             src=(filename,lineno))
-                
+
+            for (enumname, expr) in ctypeenum.enumerators:
+                constant = ConstantDescription(enumname, expr,
+                                               src=(filename, lineno))
+
                 self.constants.append(constant)
                 self.all.append(constant)
-                self.output_order.append(('constant',constant))
-    
+                self.output_order.append(('constant', constant))
+
     def handle_macro(self, name, params, expr, filename, lineno):
         # Called from within DataCollectingParser
-        src = (filename,lineno)
-        
-        if expr==None:
+        src = (filename, lineno)
+
+        if expr is None:
             expr = ConstantExpressionNode(True)
             constant = ConstantDescription(name, expr, src)
             self.constants.append(constant)
             self.all.append(constant)
             return
-        
+
         expr.visit(self)
-        
-        if isinstance(expr,CtypesType):
+
+        if isinstance(expr, CtypesType):
             if params:
                 macro = MacroDescription(name, "", src)
-                macro.error("%s has parameters but evaluates to a type. " \
-                    "Ctypesgen does not support it." % macro.casual_name(),
-                    cls = 'macro')
+                macro.error("%s has parameters but evaluates to a type. "
+                            "Ctypesgen does not support it." % macro.casual_name(),
+                            cls='macro')
                 self.macros.append(macro)
                 self.all.append(macro)
-                self.output_order.append(('macro',macro))
-            
+                self.output_order.append(('macro', macro))
+
             else:
                 typedef = TypedefDescription(name, expr, src)
                 self.typedefs.append(typedef)
                 self.all.append(typedef)
-                self.output_order.append(('typedef',typedef))
-        
+                self.output_order.append(('typedef', typedef))
+
         else:
             macro = MacroDescription(name, params, expr, src)
             self.macros.append(macro)
             self.all.append(macro)
-            self.output_order.append(('macro',macro))
-        
+            self.output_order.append(('macro', macro))
+
         # Macros could possibly contain things like __FILE__, __LINE__, etc...
         # This could be supported, but it would be a lot of work. It would
         # probably also bloat the Preamble considerably.
-        
+
     def handle_error(self, message, filename, lineno):
         # Called by CParser
-        error_message("%s:%d: %s" % (filename,lineno,message), cls='cparser')
-    
+        error_message("%s:%d: %s" % (filename, lineno, message), cls='cparser')
+
     def handle_pp_error(self, message):
         # Called by PreprocessorParser
-        error_message("%s: %s" % (self.options.cpp, message), cls = 'cparser')
-    
+        error_message("%s: %s" % (self.options.cpp, message), cls='cparser')
+
     def handle_status(self, message):
         # Called by CParser
         status_message(message)
-    
+
     def visit_struct(self, struct):
         self.handle_struct(struct, struct.src[0], struct.src[1])
-    
-    def visit_enum(self,enum):
+
+    def visit_enum(self, enum):
         self.handle_enum(enum, enum.src[0], enum.src[1])
-    
+
     def data(self):
         return DescriptionCollection(self.constants,
                                      self.typedefs,

文件差异内容过多而无法显示
+ 327 - 279
lib/python/ctypes/ctypesgencore/parser/lex.py


文件差异内容过多而无法显示
+ 55 - 4
lib/python/ctypes/ctypesgencore/parser/lextab.py


文件差异内容过多而无法显示
+ 265 - 265
lib/python/ctypes/ctypesgencore/parser/parsetab.py


+ 61 - 26
lib/python/ctypes/ctypesgencore/parser/pplexer.py

@@ -10,7 +10,14 @@ Reference is C99:
 
 __docformat__ = 'restructuredtext'
 
-import os, re, shlex, sys, tokenize, lex, yacc, traceback
+import os
+import re
+import shlex
+import sys
+import tokenize
+import lex
+import yacc
+import traceback
 import ctypes
 from lex import TOKEN
 
@@ -21,15 +28,15 @@ tokens = (
     'PTR_OP', 'INC_OP', 'DEC_OP', 'LEFT_OP', 'RIGHT_OP', 'LE_OP', 'GE_OP',
     'EQ_OP', 'NE_OP', 'AND_OP', 'OR_OP', 'MUL_ASSIGN', 'DIV_ASSIGN',
     'MOD_ASSIGN', 'ADD_ASSIGN', 'SUB_ASSIGN', 'LEFT_ASSIGN', 'RIGHT_ASSIGN',
-    'AND_ASSIGN', 'XOR_ASSIGN', 'OR_ASSIGN',  'PERIOD', 'ELLIPSIS',
+    'AND_ASSIGN', 'XOR_ASSIGN', 'OR_ASSIGN', 'PERIOD', 'ELLIPSIS',
 
     'LPAREN', 'NEWLINE',
-    
+
     'PP_DEFINE', 'PP_DEFINE_NAME', 'PP_DEFINE_MACRO_NAME', 'PP_MACRO_PARAM',
     'PP_STRINGIFY', 'PP_IDENTIFIER_PASTE', 'PP_END_DEFINE'
 )
 
-states = [('DEFINE',"exclusive")]
+states = [('DEFINE', "exclusive")]
 
 subs = {
     'D': '[0-9]',
@@ -41,8 +48,12 @@ subs = {
 }
 # Helper: substitute {foo} with subs[foo] in string (makes regexes more lexy)
 sub_pattern = re.compile('{([^}]*)}')
+
+
 def sub_repl_match(m):
     return subs[m.groups()[0]]
+
+
 def sub(s):
     return sub_pattern.sub(sub_repl_match, s)
 
@@ -53,7 +64,9 @@ def sub(s):
 # Numbers represented as int and float types.
 # For all other tokens, type is just str representation.
 
+
 class StringLiteral(str):
+
     def __new__(cls, value):
         assert value[0] == '"' and value[-1] == '"'
         # Unescaping probably not perfect but close enough.
@@ -125,6 +138,7 @@ punctuators = {
     r'?': (r'\?', '?')
 }
 
+
 def punctuator_regex(punctuators):
     punctuator_regexes = [v[0] for v in punctuators.values()]
     punctuator_regexes.sort(lambda a, b: -cmp(len(a), len(b)))
@@ -133,45 +147,51 @@ def punctuator_regex(punctuators):
 # Process line-number directives from the preprocessor
 # See http://docs.freebsd.org/info/cpp/cpp.info.Output.html
 DIRECTIVE = r'\#\s+(\d+)\s+"([^"]+)"[ \d]*\n'
+
+
 @TOKEN(DIRECTIVE)
 def t_ANY_directive(t):
     t.lexer.filename = t.groups[2]
     t.lexer.lineno = int(t.groups[1])
     return None
 
+
 @TOKEN(punctuator_regex(punctuators))
 def t_ANY_punctuator(t):
     t.type = punctuators[t.value][1]
     return t
 
 IDENTIFIER = sub('{L}({L}|{D})*')
+
+
 @TOKEN(IDENTIFIER)
 def t_INITIAL_identifier(t):
     t.type = 'IDENTIFIER'
     return t
 
+
 @TOKEN(IDENTIFIER)
 def t_DEFINE_identifier(t):
     if t.lexer.next_is_define_name:
         # This identifier is the name of a macro
         # We need to look ahead and see if this macro takes parameters or not.
         if t.lexpos + len(t.value) < t.lexer.lexlen and \
-            t.lexer.lexdata[t.lexpos + len(t.value)] == '(':
-            
+                t.lexer.lexdata[t.lexpos + len(t.value)] == '(':
+
             t.type = 'PP_DEFINE_MACRO_NAME'
-            
+
             # Look ahead and read macro parameter list
             lexdata = t.lexer.lexdata
             pos = t.lexpos + len(t.value) + 1
             while lexdata[pos] not in '\n)':
-                pos+=1
-            params = lexdata[t.lexpos+len(t.value)+1 : pos]
+                pos += 1
+            params = lexdata[t.lexpos + len(t.value) + 1: pos]
             paramlist = [x.strip() for x in params.split(",") if x.strip()]
             t.lexer.macro_params = paramlist
-                    
+
         else:
             t.type = 'PP_DEFINE_NAME'
-        
+
         t.lexer.next_is_define_name = False
     elif t.value in t.lexer.macro_params:
         t.type = 'PP_MACRO_PARAM'
@@ -179,19 +199,21 @@ def t_DEFINE_identifier(t):
         t.type = 'IDENTIFIER'
     return t
 
-FLOAT_LITERAL = sub(r"(?P<p1>{D}+)?(?P<dp>[.]?)(?P<p2>(?(p1){D}*|{D}+))" \
+FLOAT_LITERAL = sub(r"(?P<p1>{D}+)?(?P<dp>[.]?)(?P<p2>(?(p1){D}*|{D}+))"
                     r"(?P<exp>(?:[Ee][+-]?{D}+)?)(?P<suf>{FS}?)(?!\w)")
+
+
 @TOKEN(FLOAT_LITERAL)
 def t_ANY_float(t):
     t.type = 'PP_NUMBER'
     m = t.lexer.lexmatch
-    
+
     p1 = m.group("p1")
     dp = m.group("dp")
     p2 = m.group("p2")
     exp = m.group("exp")
     suf = m.group("suf")
-    
+
     if dp or exp or (suf and suf in ("Ff")):
         s = m.group(0)
         if suf:
@@ -203,58 +225,67 @@ def t_ANY_float(t):
         t.value = "l" + p1
     else:
         t.value = "i" + p1
-        
+
     return t
 
 INT_LITERAL = sub(r"(?P<p1>(?:0x{H}+)|(?:{D}+))(?P<suf>{IS})")
+
+
 @TOKEN(INT_LITERAL)
 def t_ANY_int(t):
     t.type = 'PP_NUMBER'
     m = t.lexer.lexmatch
-    
+
     if "L" in m.group(3) or "l" in m.group(2):
         prefix = "l"
     else:
         prefix = "i"
-    
+
     g1 = m.group(2)
     if g1.startswith("0x"):
         # Convert base from hexadecimal
-        g1 = str(long(g1[2:],16))
-    elif g1[0]=="0":
+        g1 = str(long(g1[2:], 16))
+    elif g1[0] == "0":
         # Convert base from octal
-        g1 = str(long(g1,8))
-    
+        g1 = str(long(g1, 8))
+
     t.value = prefix + g1
-        
+
     return t
 
 CHARACTER_CONSTANT = sub(r"L?'(\\.|[^\\'])+'")
+
+
 @TOKEN(CHARACTER_CONSTANT)
 def t_ANY_character_constant(t):
     t.type = 'CHARACTER_CONSTANT'
     return t
 
 STRING_LITERAL = sub(r'L?"(\\.|[^\\"])*"')
+
+
 @TOKEN(STRING_LITERAL)
 def t_ANY_string_literal(t):
     t.type = 'STRING_LITERAL'
     t.value = StringLiteral(t.value)
     return t
 
+
 @TOKEN(r'\(')
 def t_ANY_lparen(t):
-    if t.lexpos == 0 or t.lexer.lexdata[t.lexpos-1] not in (' \t\f\v\n'):
+    if t.lexpos == 0 or t.lexer.lexdata[t.lexpos - 1] not in (' \t\f\v\n'):
         t.type = 'LPAREN'
     else:
         t.type = '('
     return t
 
+
 @TOKEN(r'\n')
 def t_INITIAL_newline(t):
     t.lexer.lineno += 1
     return None
 
+
 @TOKEN(r'\#define')
 def t_INITIAL_pp_define(t):
     t.type = 'PP_DEFINE'
@@ -263,33 +294,37 @@ def t_INITIAL_pp_define(t):
     t.lexer.macro_params = set()
     return t
 
+
 @TOKEN(r'\n')
 def t_DEFINE_newline(t):
     t.type = 'PP_END_DEFINE'
     t.lexer.begin("INITIAL")
     del t.lexer.macro_params
-    
+
     # Damage control in case the token immediately after the #define failed
     # to handle this
     t.lexer.next_is_define_name = False
     return t
 
+
 @TOKEN(r'(\#\#)|(\#)')
 def t_DEFINE_pp_param_op(t):
-    if t.value=='#':
+    if t.value == '#':
         t.type = 'PP_STRINGIFY'
     else:
         t.type = 'PP_IDENTIFIER_PASTE'
     return t
 
+
 def t_INITIAL_error(t):
     t.type = 'OTHER'
     return t
 
+
 def t_DEFINE_error(t):
     t.type = 'OTHER'
     t.value = t.value[0]
-    t.lexer.lexpos+=1 # Skip it if it's an error in a #define
+    t.lexer.lexpos += 1  # Skip it if it's an error in a #define
     return t
 
 t_ANY_ignore = ' \t\v\f\r'

+ 42 - 26
lib/python/ctypes/ctypesgencore/parser/preprocessor.py

@@ -10,7 +10,15 @@ Reference is C99:
 
 __docformat__ = 'restructuredtext'
 
-import os, re, shlex, sys, tokenize, lex, yacc, traceback, subprocess
+import os
+import re
+import shlex
+import sys
+import tokenize
+import lex
+import yacc
+import traceback
+import subprocess
 import ctypes
 from lex import TOKEN
 import pplexer
@@ -19,7 +27,9 @@ import pplexer
 # Lexers
 # --------------------------------------------------------------------------
 
+
 class PreprocessorLexer(lex.Lexer):
+
     def __init__(self):
         lex.Lexer.__init__(self)
         self.filename = '<input>'
@@ -27,7 +37,7 @@ class PreprocessorLexer(lex.Lexer):
 
     def input(self, data, filename=None):
         if filename:
-            self.filename = filename 
+            self.filename = filename
         self.lasttoken = None
         self.input_stack = []
 
@@ -61,7 +71,9 @@ class PreprocessorLexer(lex.Lexer):
 
         return result
 
+
 class TokenListLexer(object):
+
     def __init__(self, tokens):
         self.tokens = tokens
         self.pos = 0
@@ -74,6 +86,7 @@ class TokenListLexer(object):
         else:
             return None
 
+
 def symbol_to_token(sym):
     if isinstance(sym, yacc.YaccSymbol):
         return sym.value
@@ -82,6 +95,7 @@ def symbol_to_token(sym):
     else:
         assert False, 'Not a symbol: %r' % sym
 
+
 def create_token(type, value, production=None):
     '''Create a token of type and value, at the position where 'production'
     was reduced.  Don`t specify production if the token is built-in'''
@@ -101,8 +115,10 @@ def create_token(type, value, production=None):
 # Grammars
 # --------------------------------------------------------------------------
 
+
 class PreprocessorParser(object):
-    def __init__(self,options,cparser):
+
+    def __init__(self, options, cparser):
         self.defines = ["inline=", "__inline__=", "__extension__=",
                         "_Bool=uint8_t", "__const=const", "__asm__(x)=",
                         "__asm(x)=", "CTYPESGEN=1"]
@@ -121,45 +137,45 @@ class PreprocessorParser(object):
                              lextab='lextab',
                              outputdir=os.path.dirname(__file__),
                              module=pplexer)
-        
+
         self.options = options
-        self.cparser = cparser # An instance of CParser
+        self.cparser = cparser  # An instance of CParser
 
     def parse(self, filename):
         """Parse a file and save its output"""
-        
+
         cmd = self.options.cpp
         if sys.platform == 'darwin':
             cmd += " -U __BLOCKS__"
         cmd += " -U __GNUC__"
         cmd += " -dD"
         for path in self.options.include_search_paths:
-            cmd += " -I%s" % path 
+            cmd += " -I%s" % path
         for define in self.defines:
             cmd += ' "-D%s"' % define
-        cmd += " " + filename.replace('\\','/')
+        cmd += " " + filename.replace('\\', '/')
 
         self.cparser.handle_status(cmd)
-        
+
         if sys.platform == 'win32':
             cmd = ['sh.exe', '-c', cmd]
 
         pp = subprocess.Popen(cmd,
-                              shell = True,
-                              stdout = subprocess.PIPE,
-                              stderr = subprocess.PIPE)
+                              shell=True,
+                              stdout=subprocess.PIPE,
+                              stderr=subprocess.PIPE)
         ppout, pperr = pp.communicate()
-        
+
         for line in pperr.split("\n"):
             if line:
                 self.cparser.handle_pp_error(line)
-        
+
         # We separate lines that are #defines and lines that are source code
         # We put all the source lines first, then all the #define lines.
-        
-        source_lines= []
+
+        source_lines = []
         define_lines = []
-        
+
         for line in ppout.split("\n"):
             line = line.rstrip('\r')
             line = line + "\n"
@@ -167,35 +183,35 @@ class PreprocessorParser(object):
                 # Line number information has to go with both groups
                 source_lines.append(line)
                 define_lines.append(line)
-            
+
             elif line.startswith("#define"):
                 source_lines.append("\n")
                 define_lines.append(line)
-            
+
             elif line.startswith("#"):
                 # It's a directive, but not a #define. Remove it
                 source_lines.append("\n")
                 define_lines.append("\n")
-            
+
             else:
                 source_lines.append(line)
                 define_lines.append("\n")
-        
+
         text = "".join(source_lines + define_lines)
-        
+
         if self.options.save_preprocessed_headers:
-            self.cparser.handle_status("Saving preprocessed headers to %s." % \
-                self.options.save_preprocessed_headers)
+            self.cparser.handle_status("Saving preprocessed headers to %s." %
+                                       self.options.save_preprocessed_headers)
             try:
                 f = file(self.options.save_preprocessed_headers, "w")
                 f.write(text)
                 f.close()
             except IOError:
                 self.cparser.handle_error("Couldn't save headers.")
-        
+
         self.lexer.input(text)
         self.output = []
-        
+
         while True:
             token = self.lexer.token()
             if token is not None:

文件差异内容过多而无法显示
+ 723 - 580
lib/python/ctypes/ctypesgencore/parser/yacc.py


+ 1 - 1
lib/python/ctypes/ctypesgencore/printer/__init__.py

@@ -7,4 +7,4 @@ produce the final .py output files.
 
 from printer import WrapperPrinter
 
-__all__ = ["WrapperPrinter"]
+__all__ = ["WrapperPrinter"]

+ 1 - 1
lib/python/ctypes/ctypesgencore/printer/defaultheader.py

@@ -6,4 +6,4 @@ Generated with:
 Do not modify this file.
 '''
 
-__docformat__ =  'restructuredtext'
+__docformat__ = 'restructuredtext'

+ 117 - 37
lib/python/ctypes/ctypesgencore/printer/preamble.py

@@ -1,4 +1,6 @@
-import ctypes, os, sys
+import ctypes
+import os
+import sys
 from ctypes import *
 
 _int_types = (c_int16, c_int32)
@@ -13,12 +15,14 @@ for t in _int_types:
 del t
 del _int_types
 
+
 class c_void(Structure):
     # c_void_p is a buggy return type, converting to int, so
     # POINTER(None) == c_void_p is actually written as
     # POINTER(c_void), so it can be treated as a real pointer.
     _fields_ = [('dummy', c_int)]
 
+
 def POINTER(obj):
     p = ctypes.POINTER(obj)
 
@@ -34,7 +38,9 @@ def POINTER(obj):
 
     return p
 
+
 class UserString:
+
     def __init__(self, seq):
         if isinstance(seq, basestring):
             self.data = seq
@@ -42,12 +48,19 @@ class UserString:
             self.data = seq.data[:]
         else:
             self.data = str(seq)
+
     def __str__(self): return str(self.data)
+
     def __repr__(self): return repr(self.data)
+
     def __int__(self): return int(self.data)
+
     def __long__(self): return long(self.data)
+
     def __float__(self): return float(self.data)
+
     def __complex__(self): return complex(self.data)
+
     def __hash__(self): return hash(self.data)
 
     def __cmp__(self, string):
@@ -55,13 +68,17 @@ class UserString:
             return cmp(self.data, string.data)
         else:
             return cmp(self.data, string)
+
     def __contains__(self, char):
         return char in self.data
 
     def __len__(self): return len(self.data)
+
     def __getitem__(self, index): return self.__class__(self.data[index])
+
     def __getslice__(self, start, end):
-        start = max(start, 0); end = max(end, 0)
+        start = max(start, 0)
+        end = max(end, 0)
         return self.__class__(self.data[start:end])
 
     def __add__(self, other):
@@ -71,24 +88,30 @@ class UserString:
             return self.__class__(self.data + other)
         else:
             return self.__class__(self.data + str(other))
+
     def __radd__(self, other):
         if isinstance(other, basestring):
             return self.__class__(other + self.data)
         else:
             return self.__class__(str(other) + self.data)
+
     def __mul__(self, n):
-        return self.__class__(self.data*n)
+        return self.__class__(self.data * n)
     __rmul__ = __mul__
+
     def __mod__(self, args):
         return self.__class__(self.data % args)
 
     # the following methods are defined in alphabetical order:
     def capitalize(self): return self.__class__(self.data.capitalize())
+
     def center(self, width, *args):
         return self.__class__(self.data.center(width, *args))
-    def count(self, sub, start=0, end=sys.maxint):
+
+    def count(self, sub, start=0, end=sys.maxsize):
         return self.data.count(sub, start, end)
-    def decode(self, encoding=None, errors=None): # XXX improve this?
+
+    def decode(self, encoding=None, errors=None):  # XXX improve this?
         if encoding:
             if errors:
                 return self.__class__(self.data.decode(encoding, errors))
@@ -96,7 +119,8 @@ class UserString:
                 return self.__class__(self.data.decode(encoding))
         else:
             return self.__class__(self.data.decode())
-    def encode(self, encoding=None, errors=None): # XXX improve this?
+
+    def encode(self, encoding=None, errors=None):  # XXX improve this?
         if encoding:
             if errors:
                 return self.__class__(self.data.encode(encoding, errors))
@@ -104,56 +128,91 @@ class UserString:
                 return self.__class__(self.data.encode(encoding))
         else:
             return self.__class__(self.data.encode())
-    def endswith(self, suffix, start=0, end=sys.maxint):
+
+    def endswith(self, suffix, start=0, end=sys.maxsize):
         return self.data.endswith(suffix, start, end)
+
     def expandtabs(self, tabsize=8):
         return self.__class__(self.data.expandtabs(tabsize))
-    def find(self, sub, start=0, end=sys.maxint):
+
+    def find(self, sub, start=0, end=sys.maxsize):
         return self.data.find(sub, start, end)
-    def index(self, sub, start=0, end=sys.maxint):
+
+    def index(self, sub, start=0, end=sys.maxsize):
         return self.data.index(sub, start, end)
+
     def isalpha(self): return self.data.isalpha()
+
     def isalnum(self): return self.data.isalnum()
+
     def isdecimal(self): return self.data.isdecimal()
+
     def isdigit(self): return self.data.isdigit()
+
     def islower(self): return self.data.islower()
+
     def isnumeric(self): return self.data.isnumeric()
+
     def isspace(self): return self.data.isspace()
+
     def istitle(self): return self.data.istitle()
+
     def isupper(self): return self.data.isupper()
+
     def join(self, seq): return self.data.join(seq)
+
     def ljust(self, width, *args):
         return self.__class__(self.data.ljust(width, *args))
+
     def lower(self): return self.__class__(self.data.lower())
+
     def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
+
     def partition(self, sep):
         return self.data.partition(sep)
+
     def replace(self, old, new, maxsplit=-1):
         return self.__class__(self.data.replace(old, new, maxsplit))
-    def rfind(self, sub, start=0, end=sys.maxint):
+
+    def rfind(self, sub, start=0, end=sys.maxsize):
         return self.data.rfind(sub, start, end)
-    def rindex(self, sub, start=0, end=sys.maxint):
+
+    def rindex(self, sub, start=0, end=sys.maxsize):
         return self.data.rindex(sub, start, end)
+
     def rjust(self, width, *args):
         return self.__class__(self.data.rjust(width, *args))
+
     def rpartition(self, sep):
         return self.data.rpartition(sep)
+
     def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars))
+
     def split(self, sep=None, maxsplit=-1):
         return self.data.split(sep, maxsplit)
+
     def rsplit(self, sep=None, maxsplit=-1):
         return self.data.rsplit(sep, maxsplit)
+
     def splitlines(self, keepends=0): return self.data.splitlines(keepends)
-    def startswith(self, prefix, start=0, end=sys.maxint):
+
+    def startswith(self, prefix, start=0, end=sys.maxsize):
         return self.data.startswith(prefix, start, end)
+
     def strip(self, chars=None): return self.__class__(self.data.strip(chars))
+
     def swapcase(self): return self.__class__(self.data.swapcase())
+
     def title(self): return self.__class__(self.data.title())
+
     def translate(self, *args):
         return self.__class__(self.data.translate(*args))
+
     def upper(self): return self.__class__(self.data.upper())
+
     def zfill(self, width): return self.__class__(self.data.zfill(width))
 
+
 class MutableString(UserString):
     """mutable string objects
 
@@ -169,33 +228,45 @@ class MutableString(UserString):
     errors that would be very hard to track down.
 
     A faster and better solution is to rewrite your program using lists."""
+
     def __init__(self, string=""):
         self.data = string
+
     def __hash__(self):
-        raise TypeError, "unhashable type (it is mutable)"
+        raise TypeError("unhashable type (it is mutable)")
+
     def __setitem__(self, index, sub):
         if index < 0:
             index += len(self.data)
-        if index < 0 or index >= len(self.data): raise IndexError
-        self.data = self.data[:index] + sub + self.data[index+1:]
+        if index < 0 or index >= len(self.data):
+            raise IndexError
+        self.data = self.data[:index] + sub + self.data[index + 1:]
+
     def __delitem__(self, index):
         if index < 0:
             index += len(self.data)
-        if index < 0 or index >= len(self.data): raise IndexError
-        self.data = self.data[:index] + self.data[index+1:]
+        if index < 0 or index >= len(self.data):
+            raise IndexError
+        self.data = self.data[:index] + self.data[index + 1:]
+
     def __setslice__(self, start, end, sub):
-        start = max(start, 0); end = max(end, 0)
+        start = max(start, 0)
+        end = max(end, 0)
         if isinstance(sub, UserString):
-            self.data = self.data[:start]+sub.data+self.data[end:]
+            self.data = self.data[:start] + sub.data + self.data[end:]
         elif isinstance(sub, basestring):
-            self.data = self.data[:start]+sub+self.data[end:]
+            self.data = self.data[:start] + sub + self.data[end:]
         else:
-            self.data =  self.data[:start]+str(sub)+self.data[end:]
+            self.data = self.data[:start] + str(sub) + self.data[end:]
+
     def __delslice__(self, start, end):
-        start = max(start, 0); end = max(end, 0)
+        start = max(start, 0)
+        end = max(end, 0)
         self.data = self.data[:start] + self.data[end:]
+
     def immutable(self):
         return UserString(self.data)
+
     def __iadd__(self, other):
         if isinstance(other, UserString):
             self.data += other.data
@@ -204,10 +275,12 @@ class MutableString(UserString):
         else:
             self.data += str(other)
         return self
+
     def __imul__(self, n):
         self.data *= n
         return self
 
+
 class String(MutableString, Union):
 
     _fields_ = [('raw', POINTER(c_char)),
@@ -221,7 +294,7 @@ class String(MutableString, Union):
 
     def __len__(self):
         return self.data and len(self.data) or 0
-    
+
     def from_param(cls, obj):
         # Convert None or 0
         if obj is None or obj == 0:
@@ -234,15 +307,15 @@ class String(MutableString, Union):
         # Convert from str
         elif isinstance(obj, str):
             return cls(obj)
-        
+
         # Convert from c_char_p
         elif isinstance(obj, c_char_p):
             return obj
-        
+
         # Convert from POINTER(c_char)
         elif isinstance(obj, POINTER(c_char)):
             return obj
-        
+
         # Convert from raw pointer
         elif isinstance(obj, int):
             return cls(cast(obj, POINTER(c_char)))
@@ -252,6 +325,7 @@ class String(MutableString, Union):
             return String.from_param(obj._as_parameter_)
     from_param = classmethod(from_param)
 
+
 def ReturnString(obj):
     return String.from_param(obj)
 
@@ -262,29 +336,35 @@ def ReturnString(obj):
 #
 # Non-primitive return values wrapped with UNCHECKED won't be
 # typechecked, and will be converted to c_void_p.
+
+
 def UNCHECKED(type):
     if (hasattr(type, "_type_") and isinstance(type._type_, str)
-        and type._type_ != "P"):
+            and type._type_ != "P"):
         return type
     else:
         return c_void_p
 
 # ctypes doesn't have direct support for variadic functions, so we have to write
 # our own wrapper class
+
+
 class _variadic_function(object):
-    def __init__(self,func,restype,argtypes):
-        self.func=func
-        self.func.restype=restype
-        self.argtypes=argtypes
+
+    def __init__(self, func, restype, argtypes):
+        self.func = func
+        self.func.restype = restype
+        self.argtypes = argtypes
+
     def _as_parameter_(self):
         # So we can pass this variadic function as a function pointer
         return self.func
-    def __call__(self,*args):
-        fixed_args=[]
-        i=0
+
+    def __call__(self, *args):
+        fixed_args = []
+        i = 0
         for argtype in self.argtypes:
             # Typecheck what we can
             fixed_args.append(argtype.from_param(args[i]))
-            i+=1
-        return self.func(*fixed_args+list(args[i:]))
-
+            i += 1
+        return self.func(*fixed_args + list(args[i:]))

+ 115 - 108
lib/python/ctypes/ctypesgencore/printer/printer.py

@@ -1,40 +1,45 @@
 #!/usr/bin/env python
 
-import os, sys, time
+import os
+import sys
+import time
 from ctypesgencore.descriptions import *
 from ctypesgencore.ctypedescs import *
 from ctypesgencore.messages import *
 
-import ctypesgencore.libraryloader # So we can get the path to it
-import test # So we can find the path to local files in the printer package
+import ctypesgencore.libraryloader  # So we can get the path to it
+import test  # So we can find the path to local files in the printer package
+
+
+def path_to_local_file(name, known_local_module=test):
+    basedir = os.path.dirname(known_local_module.__file__)
+    return os.path.join(basedir, name)
 
-def path_to_local_file(name,known_local_module = test):
-    basedir=os.path.dirname(known_local_module.__file__)
-    return os.path.join(basedir,name)
 
 class WrapperPrinter:
-    def __init__(self,outpath,options,data):
+
+    def __init__(self, outpath, options, data):
         status_message("Writing to %s." % outpath)
-        
-        self.file=file(outpath,"w")
-        self.options=options
+
+        self.file = file(outpath, "w")
+        self.options = options
 
         if self.options.strip_build_path and \
-          self.options.strip_build_path[-1] != os.path.sep:
+                self.options.strip_build_path[-1] != os.path.sep:
             self.options.strip_build_path += os.path.sep
-        
+
         self.print_header()
         print >>self.file
-        
+
         self.print_preamble()
         print >>self.file
-        
+
         self.print_loader()
         print >>self.file
-                
-        self.print_group(self.options.libraries,"libraries",self.print_library)
-        self.print_group(self.options.modules,"modules",self.print_module)
-        
+
+        self.print_group(self.options.libraries, "libraries", self.print_library)
+        self.print_group(self.options.modules, "modules", self.print_module)
+
         method_table = {
             'function': self.print_function,
             'macro': self.print_macro,
@@ -45,89 +50,89 @@ class WrapperPrinter:
             'enum': self.print_enum,
             'constant': self.print_constant
         }
-        
-        for kind,desc in data.output_order:
+
+        for kind, desc in data.output_order:
             if desc.included:
                 method_table[kind](desc)
                 print >>self.file
-        
-        self.print_group(self.options.inserted_files,"inserted files",
+
+        self.print_group(self.options.inserted_files, "inserted files",
                          self.insert_file)
-    
-    def print_group(self,list,name,function):
+
+    def print_group(self, list, name, function):
         if list:
-            print >>self.file,"# Begin %s" % name
+            print >>self.file, "# Begin %s" % name
             print >>self.file
             for obj in list:
                 function(obj)
             print >>self.file
-            print >>self.file,"# %d %s" % (len(list),name)
-            print >>self.file,"# End %s" % name
+            print >>self.file, "# %d %s" % (len(list), name)
+            print >>self.file, "# End %s" % name
         else:
-            print >>self.file,"# No %s" % name
+            print >>self.file, "# No %s" % name
         print >>self.file
-    
-    def srcinfo(self,src):
-        if src==None:
+
+    def srcinfo(self, src):
+        if src is None:
             print >>self.file
         else:
-            filename,lineno = src
-            if filename in ("<built-in>","<command line>"):
+            filename, lineno = src
+            if filename in ("<built-in>", "<command line>"):
                 print >>self.file, "# %s" % filename
             else:
                 if self.options.strip_build_path and \
-                  filename.startswith(self.options.strip_build_path):
+                        filename.startswith(self.options.strip_build_path):
                     filename = filename[len(self.options.strip_build_path):]
                 print >>self.file, "# %s: %s" % (filename, lineno)
-    
+
     def template_subs(self):
-        template_subs={
+        template_subs = {
             'date': time.ctime(),
             'argv': ' '.join([x for x in sys.argv if not x.startswith("--strip-build-path")]),
             'name': os.path.basename(self.options.headers[0])
         }
-        
-        for opt,value in self.options.__dict__.iteritems():
-            if type(value)==str:
-                template_subs[opt]=value
-            elif isinstance(value,(list,tuple)):
-                template_subs[opt]=(os.path.sep).join(value)
+
+        for opt, value in self.options.__dict__.iteritems():
+            if isinstance(value, str):
+                template_subs[opt] = value
+            elif isinstance(value, (list, tuple)):
+                template_subs[opt] = (os.path.sep).join(value)
             else:
-                template_subs[opt]=repr(value)
-        
+                template_subs[opt] = repr(value)
+
         return template_subs
-    
+
     def print_header(self):
         template_file = None
-        
+
         if self.options.header_template:
             path = self.options.header_template
             try:
-                template_file = file(path,"r")
+                template_file = file(path, "r")
             except IOError:
-                error_message("Cannot load header template from file \"%s\" " \
-                    " - using default template." % path, cls = 'missing-file')
-        
+                error_message("Cannot load header template from file \"%s\" "
+                              " - using default template." % path, cls='missing-file')
+
         if not template_file:
             path = path_to_local_file("defaultheader.py")
-            template_file = file(path,"r")
-        
-        template_subs=self.template_subs()
+            template_file = file(path, "r")
+
+        template_subs = self.template_subs()
         self.file.write(template_file.read() % template_subs)
-        
+
         template_file.close()
-    
+
     def print_preamble(self):
         path = path_to_local_file("preamble.py")
-        
+
         print >>self.file, "# Begin preamble"
         print >>self.file
-        preamble_file=file(path,"r")
+        preamble_file = file(path, "r")
         self.file.write(preamble_file.read())
         preamble_file.close()
         print >>self.file
         print >>self.file, "# End preamble"
-    
+
     def print_loader(self):
         print >>self.file, "_libs = {}"
         print >>self.file, "_libdirs = %s" % self.options.compile_libdirs
@@ -135,92 +140,95 @@ class WrapperPrinter:
         print >>self.file, "# Begin loader"
         print >>self.file
         path = path_to_local_file("libraryloader.py",
-                                      ctypesgencore.libraryloader)
-        loader_file=file(path,"r")
+                                  ctypesgencore.libraryloader)
+        loader_file = file(path, "r")
         self.file.write(loader_file.read())
         loader_file.close()
         print >>self.file
         print >>self.file, "# End loader"
         print >>self.file
         print >>self.file, "add_library_search_dirs([%s])" % \
-                ", ".join([repr(d) for d in self.options.runtime_libdirs])
-    
-    def print_library(self,library):
-        print >>self.file, '_libs["%s"] = load_library("%s")'%(library,library)
-    
-    def print_module(self,module):
+            ", ".join([repr(d) for d in self.options.runtime_libdirs])
+
+    def print_library(self, library):
+        print >>self.file, '_libs["%s"] = load_library("%s")' % (library, library)
+
+    def print_module(self, module):
         print >>self.file, 'from %s import *' % name
-    
-    def print_constant(self,constant):
+
+    def print_constant(self, constant):
         print >>self.file, '%s = %s' % \
-            (constant.name,constant.value.py_string(False)),
+            (constant.name, constant.value.py_string(False)),
         self.srcinfo(constant.src)
-    
-    def print_typedef(self,typedef):
+
+    def print_typedef(self, typedef):
         print >>self.file, '%s = %s' % \
-            (typedef.name,typedef.ctype.py_string()),
+            (typedef.name, typedef.ctype.py_string()),
         self.srcinfo(typedef.src)
-    
+
     def print_struct(self, struct):
         self.srcinfo(struct.src)
         base = {'union': 'Union', 'struct': 'Structure'}[struct.variety]
         print >>self.file, 'class %s_%s(%s):' % \
             (struct.variety, struct.tag, base)
         print >>self.file, '    pass'
-    
+
     def print_struct_members(self, struct):
-        if struct.opaque: return
+        if struct.opaque:
+            return
         print >>self.file, '%s_%s.__slots__ = [' % (struct.variety, struct.tag)
-        for name,ctype in struct.members:
+        for name, ctype in struct.members:
             print >>self.file, "    '%s'," % name
         print >>self.file, ']'
         print >>self.file, '%s_%s._fields_ = [' % (struct.variety, struct.tag)
-        for name,ctype in struct.members:
-            if isinstance(ctype,CtypesBitfield):
+        for name, ctype in struct.members:
+            if isinstance(ctype, CtypesBitfield):
                 print >>self.file, "    ('%s', %s, %s)," % \
                     (name, ctype.py_string(), ctype.bitfield.py_string(False))
             else:
                 print >>self.file, "    ('%s', %s)," % (name, ctype.py_string())
         print >>self.file, ']'
-    
-    def print_enum(self,enum):
+
+    def print_enum(self, enum):
         print >>self.file, 'enum_%s = c_int' % enum.tag,
         self.srcinfo(enum.src)
         # Values of enumerator are output as constants.
-    
+
     def print_function(self, function):
         if function.variadic:
             self.print_variadic_function(function)
         else:
             self.print_fixed_function(function)
-    
+
     def print_fixed_function(self, function):
         self.srcinfo(function.src)
         if function.source_library:
             print >>self.file, "if hasattr(_libs[%r], %r):" % \
-                (function.source_library,function.c_name())
+                (function.source_library, function.c_name())
             print >>self.file, "    %s = _libs[%r].%s" % \
-                (function.py_name(),function.source_library,function.c_name())
+                (function.py_name(), function.source_library, function.c_name())
             print >>self.file, "    %s.restype = %s" % \
-                (function.py_name(),function.restype.py_string())
-            print >>self.file, "    %s.argtypes = [%s]" % (function.py_name(),
+                (function.py_name(), function.restype.py_string())
+            print >>self.file, "    %s.argtypes = [%s]" % (
+                function.py_name(),
                 ', '.join([a.py_string() for a in function.argtypes]))
         else:
             print >>self.file, "for _lib in _libs.values():"
             print >>self.file, "    if hasattr(_lib, %r):" % function.c_name()
-            print >>self.file, "        %s = _lib.%s" % (function.py_name(),function.c_name())
-            print >>self.file, "        %s.restype = %s" % (function.py_name(),function.restype.py_string())
-            print >>self.file, "        %s.argtypes = [%s]" % (function.py_name(),
-                ', '.join([a.py_string() for a in function.argtypes]))
+            print >>self.file, "        %s = _lib.%s" % (function.py_name(), function.c_name())
+            print >>self.file, "        %s.restype = %s" % (
+                function.py_name(), function.restype.py_string())
+            print >>self.file, "        %s.argtypes = [%s]" % (
+                function.py_name(), ', '.join([a.py_string() for a in function.argtypes]))
             print >>self.file, "        break"
-    
-    def print_variadic_function(self,function):
+
+    def print_variadic_function(self, function):
         self.srcinfo(function.src)
         if function.source_library:
             print >>self.file, "if hasattr(_libs[%r], %r):" % \
-                (function.source_library,function.c_name())
+                (function.source_library, function.c_name())
             print >>self.file, "    _func = _libs[%r].%s" % \
-                (function.source_library,function.c_name())
+                (function.source_library, function.c_name())
             print >>self.file, "    _restype = %s" % function.restype.py_string()
             print >>self.file, "    _argtypes = [%s]" % \
                 ', '.join([a.py_string() for a in function.argtypes])
@@ -237,7 +245,6 @@ class WrapperPrinter:
             print >>self.file, "        %s = _variadic_function(_func,_restype,_argtypes)" % \
                 function.py_name()
 
-    
     def print_variable(self, variable):
         self.srcinfo(variable.src)
         if variable.source_library:
@@ -259,40 +266,40 @@ class WrapperPrinter:
             print >>self.file, "        break"
             print >>self.file, '    except:'
             print >>self.file, '        pass'
-    
+
     def print_macro(self, macro):
         if macro.params:
             self.print_func_macro(macro)
         else:
             self.print_simple_macro(macro)
-    
+
     def print_simple_macro(self, macro):
         # The macro translator makes heroic efforts but it occasionally fails.
         # We want to contain the failures as much as possible.
         # Hence the try statement.
         self.srcinfo(macro.src)
         print >>self.file, "try:"
-        print >>self.file, "    %s = %s" % (macro.name,macro.expr.py_string(True))
+        print >>self.file, "    %s = %s" % (macro.name, macro.expr.py_string(True))
         print >>self.file, "except:"
         print >>self.file, "    pass"
-    
+
     def print_func_macro(self, macro):
         self.srcinfo(macro.src)
         print >>self.file, "def %s(%s):" % \
-            (macro.name,", ".join(macro.params))
+            (macro.name, ", ".join(macro.params))
         print >>self.file, "    return %s" % macro.expr.py_string(True)
-    
-    def insert_file(self,filename):
+
+    def insert_file(self, filename):
         try:
-            inserted_file = file(filename,"r")
+            inserted_file = file(filename, "r")
         except IOError:
             error_message("Cannot open file \"%s\". Skipped it." % filename,
-                          cls = 'missing-file')
-        
-        print >>self.file,"# Begin \"%s\"" % filename
+                          cls='missing-file')
+
+        print >>self.file, "# Begin \"%s\"" % filename
         print >>self.file
         self.file.write(inserted_file.read())
         print >>self.file
-        print >>self.file,"# End \"%s\"" % filename
-              
+        print >>self.file, "# End \"%s\"" % filename
+
         inserted_file.close()

+ 1 - 1
lib/python/ctypes/ctypesgencore/printer/test.py

@@ -3,4 +3,4 @@ ctypesgencore.printer.printer imports this module so that it can find the path
 to defaulttemplate.py and defaultloader.py.
 """
 
-pass
+pass

+ 1 - 1
lib/python/ctypes/ctypesgencore/processor/__init__.py

@@ -9,4 +9,4 @@ A convenience_function, process(), calls everything else.
 
 __all__ = ["process"]
 
-from pipeline import process
+from pipeline import process

+ 49 - 38
lib/python/ctypes/ctypesgencore/processor/dependencies.py

@@ -9,58 +9,69 @@ from ctypesgencore.descriptions import *
 from ctypesgencore.ctypedescs import *
 from ctypesgencore.messages import *
 
+
 def find_dependencies(data, opts):
     """Visit each description in `data` and figure out which other descriptions
 it depends on, putting the results in desc.requirements. Also find errors in
 ctypedecls or expressions attached to the description and transfer them to the
 description."""
-    
+
     struct_names = {}
     enum_names = {}
     typedef_names = {}
     ident_names = {}
-    
+
     # Start the lookup tables with names from imported modules
-    
+
     for name in opts.other_known_names:
         typedef_names[name] = None
         ident_names[name] = None
         if name.startswith("struct_") or name.startswith("enum_"):
             variety = name.split("_")[0]
             tag = "_".join(name.split("_")[1:])
-            struct_names[(variety,tag)] = None
+            struct_names[(variety, tag)] = None
         if name.startswith("enum_"):
             enum_names[name] = None
-    
+
     def depend(desc, nametable, name):
         """Try to add `name` as a requirement for `desc`, looking `name` up in
 `nametable`. Returns True if found."""
 
         if name in nametable:
             requirement = nametable[name]
-            if requirement: desc.add_requirements([requirement])
+            if requirement:
+                desc.add_requirements([requirement])
             return True
         else:
             return False
-    
+
     def find_dependencies_for(desc, kind):
         """Find all the descriptions that `desc` depends on and add them as
-dependencies for `desc`. Also collect error messages regarding `desc` and 
+dependencies for `desc`. Also collect error messages regarding `desc` and
 convert unlocateable descriptions into error messages."""
 
-        if kind == "constant": roots = [desc.value]
-        if kind == "struct": roots = []
-        if kind == "struct-body": roots = [desc.ctype]
-        if kind == "enum": roots = []
-        if kind == "typedef": roots = [desc.ctype]
-        if kind == "function": roots = desc.argtypes + [desc.restype]
-        if kind == "variable": roots = [desc.ctype]
+        if kind == "constant":
+            roots = [desc.value]
+        if kind == "struct":
+            roots = []
+        if kind == "struct-body":
+            roots = [desc.ctype]
+        if kind == "enum":
+            roots = []
+        if kind == "typedef":
+            roots = [desc.ctype]
+        if kind == "function":
+            roots = desc.argtypes + [desc.restype]
+        if kind == "variable":
+            roots = [desc.ctype]
         if kind == "macro":
-            if desc.expr: roots = [desc.expr]
-            else: roots = []
-        
-        cstructs,cenums,ctypedefs,errors,identifiers = [], [], [], [], []
-        
+            if desc.expr:
+                roots = [desc.expr]
+            else:
+                roots = []
+
+        cstructs, cenums, ctypedefs, errors, identifiers = [], [], [], [], []
+
         for root in roots:
             s, e, t, errs, i = visit_type_and_collect_info(root)
             cstructs.extend(s)
@@ -68,42 +79,42 @@ convert unlocateable descriptions into error messages."""
             ctypedefs.extend(t)
             errors.extend(errs)
             identifiers.extend(i)
-        
+
         unresolvables = []
-        
+
         for cstruct in cstructs:
             if kind == "struct" and desc.variety == cstruct.variety and \
-                desc.tag == cstruct.tag:
+                    desc.tag == cstruct.tag:
                 continue
             if not depend(desc, struct_names, (cstruct.variety, cstruct.tag)):
-                unresolvables.append("%s \"%s\"" % \
-                    (cstruct.variety, cstruct.tag))
-        
+                unresolvables.append("%s \"%s\"" %
+                                     (cstruct.variety, cstruct.tag))
+
         for cenum in cenums:
             if kind == "enum" and desc.tag == cenum.tag:
                 continue
             if not depend(desc, enum_names, cenum.tag):
                 unresolvables.append("enum \"%s\"" % cenum.tag)
-        
+
         for ctypedef in ctypedefs:
             if not depend(desc, typedef_names, ctypedef):
                 unresolvables.append("typedef \"%s\"" % ctypedef)
-        
+
         for ident in identifiers:
             if isinstance(desc, MacroDescription) and \
-                desc.params and ident in desc.params:
+                    desc.params and ident in desc.params:
                 continue
             if not depend(desc, ident_names, ident):
                 unresolvables.append("identifier \"%s\"" % ident)
-        
+
         for u in unresolvables:
-            errors.append(("%s depends on an unknown %s." % \
-                          (desc.casual_name(), u), None))
-        
+            errors.append(("%s depends on an unknown %s." %
+                           (desc.casual_name(), u), None))
+
         for err, cls in errors:
             err += " %s will not be output" % desc.casual_name()
-            desc.error(err, cls = cls)
-        
+            desc.error(err, cls=cls)
+
     def add_to_lookup_table(desc, kind):
         """Add `desc` to the lookup table so that other descriptions that use
 it can find it."""
@@ -125,13 +136,13 @@ it can find it."""
     # no other type of description can look ahead like that.
 
     for kind, desc in data.output_order:
-        if kind!="macro":
+        if kind != "macro":
             find_dependencies_for(desc, kind)
             add_to_lookup_table(desc, kind)
 
     for kind, desc in data.output_order:
-        if kind=="macro":
+        if kind == "macro":
             add_to_lookup_table(desc, kind)
     for kind, desc in data.output_order:
-        if kind=="macro":
+        if kind == "macro":
             find_dependencies_for(desc, kind)

+ 109 - 96
lib/python/ctypes/ctypesgencore/processor/operations.py

@@ -6,195 +6,208 @@ DescriptionCollection and prepare it for output.
 ctypesgencore.processor.pipeline calls the operations module.
 """
 
-import ctypes, re, os, sys, keyword
+import ctypes
+import re
+import os
+import sys
+import keyword
 from ctypesgencore.descriptions import *
 from ctypesgencore.messages import *
 import ctypesgencore.libraryloader
 
 # Processor functions
 
-def automatically_typedef_structs(data,options):
+
+def automatically_typedef_structs(data, options):
     """automatically_typedef_structs() aliases "struct_<tag>" to "<tag>" for
     every struct and union."""
     # XXX Check if it has already been aliased in the C code.
-    
+
     for struct in data.structs:
-        if not struct.ctype.anonymous: # Don't alias anonymous structs
-            typedef=TypedefDescription(struct.tag,
-                                       struct.ctype,
-                                       src=struct.src)
+        if not struct.ctype.anonymous:  # Don't alias anonymous structs
+            typedef = TypedefDescription(struct.tag,
+                                         struct.ctype,
+                                         src=struct.src)
             typedef.add_requirements(set([struct]))
-            
+
             data.typedefs.append(typedef)
-            data.all.insert(data.all.index(struct)+1,typedef)
+            data.all.insert(data.all.index(struct) + 1, typedef)
             data.output_order.append(("typedef", typedef))
 
+
 def remove_NULL(data, options):
     """remove_NULL() removes any NULL definitions from the C headers because
 ctypesgen supplies its own NULL definition."""
-    
+
     for macro in data.macros:
-        if macro.name=="NULL":
+        if macro.name == "NULL":
             macro.include_rule = "never"
 
-def remove_descriptions_in_system_headers(data,opts):
+
+def remove_descriptions_in_system_headers(data, opts):
     """remove_descriptions_in_system_headers() removes descriptions if they came
     from files outside of the header files specified from the command line."""
-    
+
     known_headers = [os.path.basename(x) for x in opts.headers]
-    
+
     for description in data.all:
-        if description.src!=None:
+        if description.src is not None:
             if description.src[0] == "<command line>":
                 description.include_rule = "if_needed"
             elif description.src[0] == "<built-in>":
                 if not opts.builtin_symbols:
-                    description.include_rule="if_needed"
+                    description.include_rule = "if_needed"
             elif os.path.basename(description.src[0]) not in known_headers:
                 if not opts.all_headers:
                     # If something else requires this, include it even though
                     # it is in a system header file.
-                    description.include_rule="if_needed"
+                    description.include_rule = "if_needed"
 
-def remove_macros(data,opts):
+
+def remove_macros(data, opts):
     """remove_macros() removes macros if --no-macros is set."""
     if not opts.include_macros:
         for macro in data.macros:
             macro.include_rule = "never"
 
-def filter_by_regexes_exclude(data,opts):
+
+def filter_by_regexes_exclude(data, opts):
     """filter_by_regexes_exclude() uses regular expressions specified by options
     dictionary to filter symbols."""
     if opts.exclude_symbols:
-        expr=re.compile(opts.exclude_symbols)
+        expr = re.compile(opts.exclude_symbols)
         for object in data.all:
             if expr.match(object.py_name()):
-                object.include_rule="never"
+                object.include_rule = "never"
 
-def filter_by_regexes_include(data,opts):
+
+def filter_by_regexes_include(data, opts):
     """filter_by_regexes_include() uses regular expressions specified by options
     dictionary to re-include symbols previously rejected by other operations."""
     if opts.include_symbols:
-        expr=re.compile(opts.include_symbols)
+        expr = re.compile(opts.include_symbols)
         for object in data.all:
-            if object.include_rule!="never":
+            if object.include_rule != "never":
                 if expr.match(object.py_name()):
-                    object.include_rule="yes"
+                    object.include_rule = "yes"
+
 
-def fix_conflicting_names(data,opts):
+def fix_conflicting_names(data, opts):
     """If any descriptions from the C code would overwrite Python builtins or
     other important names, fix_conflicting_names() adds underscores to resolve
     the name conflict."""
-    
+
     # This is the order of priority for names
     descriptions = data.functions + data.variables + data.structs + \
         data.typedefs + data.enums + data.constants + data.macros
-    
+
     # This dictionary maps names to a string representing where the name
     # came from.
-    important_names={}
-    
-    preamble_names=set()
-    preamble_names=preamble_names.union(['DarwinLibraryLoader',
-        'LibraryLoader', 'LinuxLibraryLoader', 'WindowsLibraryLoader',
-        '_WindowsLibrary', 'add_library_search_dirs', '_environ_path', 'ctypes',
-        'load_library', 'loader', 'os', 're', 'sys'])
-    preamble_names=preamble_names.union(['ArgumentError', 'CFUNCTYPE',
-        'POINTER', 'ReturnString', 'String', 'Structure', 'UNCHECKED', 'Union',
-        'UserString', '_variadic_function', 'addressof', 'c_buffer', 'c_byte',
-        'c_char', 'c_char_p', 'c_double', 'c_float', 'c_int', 'c_int16',
-        'c_int32', 'c_int64', 'c_int8', 'c_long', 'c_longlong', 'c_ptrdiff_t',
-        'c_short', 'c_size_t', 'c_ubyte', 'c_uint', 'c_uint16', 'c_uint32',
-        'c_uint64', 'c_uint8', 'c_ulong', 'c_ulonglong', 'c_ushort', 'c_void',
-        'c_void_p', 'c_voidp', 'c_wchar', 'c_wchar_p', 'cast', 'ctypes', 'os',
-        'pointer', 'sizeof'])
+    important_names = {}
+
+    preamble_names = set()
+    preamble_names = preamble_names.union(
+        ['DarwinLibraryLoader', 'LibraryLoader', 'LinuxLibraryLoader', 'WindowsLibraryLoader',
+         '_WindowsLibrary', 'add_library_search_dirs', '_environ_path', 'ctypes', 'load_library',
+         'loader', 'os', 're', 'sys'])
+    preamble_names = preamble_names.union(
+        ['ArgumentError', 'CFUNCTYPE', 'POINTER', 'ReturnString', 'String', 'Structure',
+         'UNCHECKED', 'Union', 'UserString', '_variadic_function', 'addressof', 'c_buffer',
+         'c_byte', 'c_char', 'c_char_p', 'c_double', 'c_float', 'c_int', 'c_int16', 'c_int32',
+         'c_int64', 'c_int8', 'c_long', 'c_longlong', 'c_ptrdiff_t', 'c_short', 'c_size_t',
+         'c_ubyte', 'c_uint', 'c_uint16', 'c_uint32', 'c_uint64', 'c_uint8', 'c_ulong',
+         'c_ulonglong', 'c_ushort', 'c_void', 'c_void_p', 'c_voidp', 'c_wchar', 'c_wchar_p', 'cast',
+         'ctypes', 'os', 'pointer', 'sizeof'])
     for name in preamble_names:
         important_names[name] = "a name needed by ctypes or ctypesgen"
-    for name in dir(__builtins__): important_names[name] = "a Python builtin"
+    for name in dir(__builtins__):
+        important_names[name] = "a Python builtin"
     for name in opts.other_known_names:
         important_names[name] = "a name from an included Python module"
-    for name in keyword.kwlist: important_names[name] = "a Python keyword"
-    
+    for name in keyword.kwlist:
+        important_names[name] = "a Python keyword"
+
     for description in descriptions:
         if description.py_name() in important_names:
             conflict_name = important_names[description.py_name()]
-            
-            original_name=description.casual_name()
+
+            original_name = description.casual_name()
             while description.py_name() in important_names:
                 if isinstance(description,
-                                (StructDescription, EnumDescription)):
-                    description.tag+="_"
+                              (StructDescription, EnumDescription)):
+                    description.tag += "_"
                 else:
-                    description.name="_"+description.name
-            
+                    description.name = "_" + description.name
+
             if not description.dependents:
-                description.warning("%s has been renamed to %s due to a name " \
-                    "conflict with %s." % \
-                    (original_name,
-                    description.casual_name(),
-                    conflict_name),
-                    cls = 'rename')
+                description.warning("%s has been renamed to %s due to a name "
+                                    "conflict with %s." %
+                                    (original_name,
+                                     description.casual_name(),
+                                     conflict_name),
+                                    cls='rename')
             else:
-                description.warning("%s has been renamed to %s due to a name " \
-                    "conflict with %s. Other objects depend on %s - those " \
-                    "objects will be skipped." % \
-                    (original_name, description.casual_name(),
-                    conflict_name, original_name),
-                    cls = 'rename')
-                
+                description.warning("%s has been renamed to %s due to a name "
+                                    "conflict with %s. Other objects depend on %s - those "
+                                    "objects will be skipped." %
+                                    (original_name, description.casual_name(),
+                                     conflict_name, original_name),
+                                    cls='rename')
+
                 for dependent in description.dependents:
                     dependent.include_rule = "never"
-            
-            if description.include_rule=="yes":
+
+            if description.include_rule == "yes":
                 important_names[description.py_name()] = \
                     description.casual_name()
-    
+
     # Names of struct members don't conflict with much, but they can conflict
     # with Python keywords.
-    
+
     for struct in data.structs:
         if not struct.opaque:
-            for i,(name,type) in enumerate(struct.members):
+            for i, (name, type) in enumerate(struct.members):
                 if name in keyword.kwlist:
-                    struct.members[i] = ("_"+name,type)
-                    struct.warning("Member \"%s\" of %s has been renamed to " \
-                        "\"%s\" because it has the same name as a Python " \
-                        "keyword." % (name, struct.casual_name(), "_"+name),
-                        cls = 'rename')
-    
+                    struct.members[i] = ("_" + name, type)
+                    struct.warning("Member \"%s\" of %s has been renamed to "
+                                   "\"%s\" because it has the same name as a Python "
+                                   "keyword." % (name, struct.casual_name(), "_" + name),
+                                   cls='rename')
+
     # Macro arguments may be have names that conflict with Python keywords.
     # In a perfect world, this would simply rename the parameter instead
     # of throwing an error message.
-    
+
     for macro in data.macros:
         if macro.params:
             for param in macro.params:
                 if param in keyword.kwlist:
-                    macro.error("One of the parameters to %s, \"%s\" has the " \
-                        "same name as a Python keyword. %s will be skipped." % \
-                        (macro.casual_name(), param, macro.casual_name()),
-                        cls = 'name-conflict')
+                    macro.error("One of the parameters to %s, \"%s\" has the "
+                                "same name as a Python keyword. %s will be skipped." %
+                                (macro.casual_name(), param, macro.casual_name()),
+                                cls='name-conflict')
 
-def find_source_libraries(data,opts):
+
+def find_source_libraries(data, opts):
     """find_source_libraries() determines which library contains each function
     and variable."""
-    
-    all_symbols=data.functions+data.variables
-    
+
+    all_symbols = data.functions + data.variables
+
     for symbol in all_symbols:
-        symbol.source_library=None
-    
+        symbol.source_library = None
+
     ctypesgencore.libraryloader.add_library_search_dirs(opts.compile_libdirs)
-    
+
     for library_name in opts.libraries:
         try:
-            library=ctypesgencore.libraryloader.load_library(library_name)
+            library = ctypesgencore.libraryloader.load_library(library_name)
         except ImportError as e:
-            warning_message("Could not load library \"%s\". Okay, I'll " \
-                "try to load it at runtime instead. " % (library_name),
-                cls = 'missing-library')
+            warning_message("Could not load library \"%s\". Okay, I'll "
+                            "try to load it at runtime instead. " % (library_name),
+                            cls='missing-library')
             continue
         for symbol in all_symbols:
-            if symbol.source_library==None:
-                if hasattr(library,symbol.c_name()):
-                    symbol.source_library=library_name
+            if symbol.source_library is None:
+                if hasattr(library, symbol.c_name()):
+                    symbol.source_library = library_name

+ 56 - 52
lib/python/ctypes/ctypesgencore/processor/pipeline.py

@@ -1,6 +1,8 @@
 #!/usr/bin/env python
 
-import ctypes, re, os
+import ctypes
+import re
+import os
 from ctypesgencore.processor.operations import *
 from ctypesgencore.processor.dependencies import find_dependencies
 from ctypesgencore.ctypedescs import *
@@ -38,25 +40,27 @@ the errors that print_errors_encountered() has flagged.
 
 """
 
-def process(data,options):
+
+def process(data, options):
     status_message("Processing description list.")
-    
-    find_dependencies(data,options)
-    
-    automatically_typedef_structs(data,options)
+
+    find_dependencies(data, options)
+
+    automatically_typedef_structs(data, options)
     remove_NULL(data, options)
-    remove_descriptions_in_system_headers(data,options)
-    filter_by_regexes_exclude(data,options)
-    filter_by_regexes_include(data,options)
-    remove_macros(data,options)
-    fix_conflicting_names(data,options)
-    find_source_libraries(data,options)
-        
-    calculate_final_inclusion(data,options)
-    print_errors_encountered(data,options)
-    calculate_final_inclusion(data,options)
-
-def calculate_final_inclusion(data,opts):
+    remove_descriptions_in_system_headers(data, options)
+    filter_by_regexes_exclude(data, options)
+    filter_by_regexes_include(data, options)
+    remove_macros(data, options)
+    fix_conflicting_names(data, options)
+    find_source_libraries(data, options)
+
+    calculate_final_inclusion(data, options)
+    print_errors_encountered(data, options)
+    calculate_final_inclusion(data, options)
+
+
+def calculate_final_inclusion(data, opts):
     """calculate_final_inclusion() calculates which descriptions will be included in the
     output library.
 
@@ -66,69 +70,69 @@ def calculate_final_inclusion(data,opts):
     An object with include_rule="if_needed" is included if an object to be
         included requires it and if its requirements can be included.
     """
-    
+
     def can_include_desc(desc):
-        if desc.can_include==None:
-            if desc.include_rule=="no":
-                desc.can_include=False
-            elif desc.include_rule=="yes" or desc.include_rule=="if_needed":
-                desc.can_include=True
+        if desc.can_include is None:
+            if desc.include_rule == "no":
+                desc.can_include = False
+            elif desc.include_rule == "yes" or desc.include_rule == "if_needed":
+                desc.can_include = True
                 for req in desc.requirements:
                     if not can_include_desc(req):
-                        desc.can_include=False
+                        desc.can_include = False
         return desc.can_include
-        
+
     def do_include_desc(desc):
         if desc.included:
-            return # We've already been here
+            return  # We've already been here
         desc.included = True
         for req in desc.requirements:
             do_include_desc(req)
-    
+
     for desc in data.all:
-        desc.can_include=None # None means "Not Yet Decided"
-        desc.included=False
-        
+        desc.can_include = None  # None means "Not Yet Decided"
+        desc.included = False
+
     for desc in data.all:
-        if desc.include_rule=="yes":
+        if desc.include_rule == "yes":
             if can_include_desc(desc):
                 do_include_desc(desc)
 
-def print_errors_encountered(data,opts):
+
+def print_errors_encountered(data, opts):
     # See descriptions.py for an explanation of the error-handling mechanism
     for desc in data.all:
         # If description would not have been included, dont bother user by
         # printing warnings.
         if desc.included or opts.show_all_errors:
-            if opts.show_long_errors or len(desc.errors)+len(desc.warnings)<=2:
-                for (error,cls) in desc.errors:
+            if opts.show_long_errors or len(desc.errors) + len(desc.warnings) <= 2:
+                for (error, cls) in desc.errors:
                     # Macro errors will always be displayed as warnings.
                     if isinstance(desc, MacroDescription):
                         if opts.show_macro_warnings:
-                            warning_message(error,cls)
+                            warning_message(error, cls)
                     else:
-                        error_message(error,cls)
-                for (warning,cls) in desc.warnings:
-                    warning_message(warning,cls)
-            
+                        error_message(error, cls)
+                for (warning, cls) in desc.warnings:
+                    warning_message(warning, cls)
+
             else:
                 if desc.errors:
-                    error1,cls1 = desc.errors[0]
-                    error_message(error1,cls1)
-                    numerrs = len(desc.errors)-1
+                    error1, cls1 = desc.errors[0]
+                    error_message(error1, cls1)
+                    numerrs = len(desc.errors) - 1
                     numwarns = len(desc.warnings)
                     if numwarns:
-                        error_message("%d more errors and %d more warnings " \
-                            "for %s" % (numerrs,numwarns,desc.casual_name()))
+                        error_message("%d more errors and %d more warnings "
+                                      "for %s" % (numerrs, numwarns, desc.casual_name()))
                     else:
-                        error_message("%d more errors for %s " % \
-                            (numerrs,desc.casual_name()))
+                        error_message("%d more errors for %s " %
+                                      (numerrs, desc.casual_name()))
                 else:
-                    warning1,cls1 = desc.warnings[0]
-                    warning_message(warning1,cls1)
-                    warning_message("%d more errors for %s" % \
-                        (len(desc.warnings)-1, desc.casual_name()))
+                    warning1, cls1 = desc.warnings[0]
+                    warning_message(warning1, cls1)
+                    warning_message("%d more errors for %s" %
+                                    (len(desc.warnings) - 1, desc.casual_name()))
         if desc.errors:
             # process() will recalculate to take this into account
             desc.include_rule = "never"
-

+ 3 - 3
lib/python/ctypes/fix.sed

@@ -1,7 +1,7 @@
 #!/usr/bin/sed -f
 /^# End loader$/a\
-from ctypes_preamble import *\
-from ctypes_preamble import _variadic_function\
-from ctypes_loader import *
+from .ctypes_preamble import *\
+from .ctypes_preamble import _variadic_function\
+from .ctypes_loader import *
 /^# Begin preamble$/,/^# End preamble$/d
 /^# Begin loader$/,/^# End loader$/d

+ 69 - 49
lib/python/ctypes/loader.py

@@ -2,14 +2,14 @@
 # Copyright (c) 2008 David James
 # Copyright (c) 2006-2008 Alex Holkner
 # All rights reserved.
-# 
+#
 # Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions 
+# modification, are permitted provided that the following conditions
 # are met:
 #
 #  * Redistributions of source code must retain the above copyright
 #    notice, this list of conditions and the following disclaimer.
-#  * Redistributions in binary form must reproduce the above copyright 
+#  * Redistributions in binary form must reproduce the above copyright
 #    notice, this list of conditions and the following disclaimer in
 #    the documentation and/or other materials provided with the
 #    distribution.
@@ -32,31 +32,38 @@
 # POSSIBILITY OF SUCH DAMAGE.
 # ----------------------------------------------------------------------------
 
-import os.path, re, sys, glob
+import glob
+import os.path
+import re
+import sys
+
 import ctypes
 import ctypes.util
 
+
 def _environ_path(name):
     if name in os.environ:
         return os.environ[name].split(":")
     else:
         return []
 
+
 class LibraryLoader(object):
+
     def __init__(self):
-        self.other_dirs=[]
-    
-    def load_library(self,libname):
+        self.other_dirs = []
+
+    def load_library(self, libname):
         """Given the name of a library, load it."""
         paths = self.getpaths(libname)
-        
+
         for path in paths:
             if os.path.exists(path):
                 return self.load(path)
-        
-        raise ImportError,"%s not found." % libname
-    
-    def load(self,path):
+
+        raise ImportError("%s not found." % libname)
+
+    def load(self, path):
         """Given a path to a library, load it."""
         try:
             # Darwin requires dlopen to be called with mode RTLD_GLOBAL instead
@@ -68,42 +75,44 @@ class LibraryLoader(object):
             else:
                 return ctypes.cdll.LoadLibrary(path)
         except OSError as e:
-            raise ImportError,e
-    
-    def getpaths(self,libname):
+            raise ImportError(e)
+
+    def getpaths(self, libname):
         """Return a list of paths where the library might be found."""
         if os.path.isabs(libname):
             yield libname
-        
+
         else:
             for path in self.getplatformpaths(libname):
                 yield path
-            
+
             path = ctypes.util.find_library(libname)
-            if path: yield path
-    
+            if path:
+                yield path
+
     def getplatformpaths(self, libname):
         return []
 
 # Darwin (Mac OS X)
 
+
 class DarwinLibraryLoader(LibraryLoader):
     name_formats = ["lib%s.dylib", "lib%s.so", "lib%s.bundle", "%s.dylib",
-                "%s.so", "%s.bundle", "%s"]
-    
-    def getplatformpaths(self,libname):
+                    "%s.so", "%s.bundle", "%s"]
+
+    def getplatformpaths(self, libname):
         if os.path.pathsep in libname:
             names = [libname]
         else:
             names = [format % libname for format in self.name_formats]
-        
+
         for dir in self.getdirs(libname):
             for name in names:
-                yield os.path.join(dir,name)
-    
-    def getdirs(self,libname):
+                yield os.path.join(dir, name)
+
+    def getdirs(self, libname):
         '''Implements the dylib search as specified in Apple documentation:
-        
+
         http://developer.apple.com/documentation/DeveloperTools/Conceptual/
             DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html
 
@@ -116,9 +125,9 @@ class DarwinLibraryLoader(LibraryLoader):
         if not dyld_fallback_library_path:
             dyld_fallback_library_path = [os.path.expanduser('~/lib'),
                                           '/usr/local/lib', '/usr/lib']
-        
+
         dirs = []
-        
+
         if '/' in libname:
             dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
         else:
@@ -127,7 +136,7 @@ class DarwinLibraryLoader(LibraryLoader):
 
         dirs.extend(self.other_dirs)
         dirs.append(".")
-        
+
         if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
             dirs.append(os.path.join(
                 os.environ['RESOURCEPATH'],
@@ -135,14 +144,15 @@ class DarwinLibraryLoader(LibraryLoader):
                 'Frameworks'))
 
         dirs.extend(dyld_fallback_library_path)
-        
+
         return dirs
 
 # Posix
 
+
 class PosixLibraryLoader(LibraryLoader):
     _ld_so_cache = None
-    
+
     def _create_ld_so_cache(self):
         # Recreate search path followed by ld.so.  This is going to be
         # slow to build, and incorrect (ld.so uses ld.so.cache, which may
@@ -153,17 +163,19 @@ class PosixLibraryLoader(LibraryLoader):
 
         directories = []
         for name in ("LD_LIBRARY_PATH",
-                     "SHLIB_PATH", # HPUX
-                     "LIBPATH", # OS/2, AIX
-                     "LIBRARY_PATH", # BE/OS
-                    ):
+                     "SHLIB_PATH",  # HPUX
+                     "LIBPATH",  # OS/2, AIX
+                     "LIBRARY_PATH",  # BE/OS
+                     ):
             if name in os.environ:
                 directories.extend(os.environ[name].split(os.pathsep))
         directories.extend(self.other_dirs)
         directories.append(".")
 
-        try: directories.extend([dir.strip() for dir in open('/etc/ld.so.conf')])
-        except IOError: pass
+        try:
+            directories.extend([dir.strip() for dir in open('/etc/ld.so.conf')])
+        except IOError:
+            pass
 
         directories.extend(['/lib', '/usr/lib', '/lib64', '/usr/lib64'])
 
@@ -178,7 +190,7 @@ class PosixLibraryLoader(LibraryLoader):
                     # Index by filename
                     if file not in cache:
                         cache[file] = path
-                    
+
                     # Index by library name
                     match = lib_re.match(file)
                     if match:
@@ -189,37 +201,44 @@ class PosixLibraryLoader(LibraryLoader):
                 pass
 
         self._ld_so_cache = cache
-    
+
     def getplatformpaths(self, libname):
         if self._ld_so_cache is None:
             self._create_ld_so_cache()
 
         result = self._ld_so_cache.get(libname)
-        if result: yield result
+        if result:
+            yield result
 
         path = ctypes.util.find_library(libname)
-        if path: yield os.path.join("/lib",path)
+        if path:
+            yield os.path.join("/lib", path)
 
 # Windows
 
+
 class _WindowsLibrary(object):
+
     def __init__(self, path):
         self.cdll = ctypes.cdll.LoadLibrary(path)
         self.windll = ctypes.windll.LoadLibrary(path)
 
     def __getattr__(self, name):
-        try: return getattr(self.cdll,name)
+        try:
+            return getattr(self.cdll, name)
         except AttributeError:
-            try: return getattr(self.windll,name)
+            try:
+                return getattr(self.windll, name)
             except AttributeError:
                 raise
 
+
 class WindowsLibraryLoader(LibraryLoader):
     name_formats = ["%s.dll", "lib%s.dll"]
-    
+
     def load(self, path):
         return _WindowsLibrary(path)
-    
+
     def getplatformpaths(self, libname):
         if os.path.sep not in libname:
             for name in self.name_formats:
@@ -233,13 +252,14 @@ class WindowsLibraryLoader(LibraryLoader):
 # the Ctypesgen maintainers.
 
 loaderclass = {
-    "darwin":   DarwinLibraryLoader,
-    "cygwin":   WindowsLibraryLoader,
-    "win32":    WindowsLibraryLoader
+    "darwin": DarwinLibraryLoader,
+    "cygwin": WindowsLibraryLoader,
+    "win32": WindowsLibraryLoader
 }
 
 loader = loaderclass.get(sys.platform, PosixLibraryLoader)()
 
+
 def add_library_search_dirs(other_dirs):
     loader.other_dirs = other_dirs
 

+ 23 - 12
lib/python/ctypes/preamble.py

@@ -1,4 +1,7 @@
-import ctypes, os, sys
+import os
+import sys
+
+import ctypes
 from ctypes import *
 
 _int_types = (c_int16, c_int32)
@@ -13,12 +16,14 @@ for t in _int_types:
 del t
 del _int_types
 
+
 class c_void(Structure):
     # c_void_p is a buggy return type, converting to int, so
     # POINTER(None) == c_void_p is actually written as
     # POINTER(c_void), so it can be treated as a real pointer.
     _fields_ = [('dummy', c_int)]
 
+
 def POINTER(obj):
     p = ctypes.POINTER(obj)
 
@@ -44,29 +49,35 @@ ReturnString = c_char_p
 #
 # Non-primitive return values wrapped with UNCHECKED won't be
 # typechecked, and will be converted to c_void_p.
+
+
 def UNCHECKED(type):
     if (hasattr(type, "_type_") and isinstance(type._type_, str)
-        and type._type_ != "P"):
+            and type._type_ != "P"):
         return type
     else:
         return c_void_p
 
 # ctypes doesn't have direct support for variadic functions, so we have to write
 # our own wrapper class
+
+
 class _variadic_function(object):
-    def __init__(self,func,restype,argtypes):
-        self.func=func
-        self.func.restype=restype
-        self.argtypes=argtypes
+
+    def __init__(self, func, restype, argtypes):
+        self.func = func
+        self.func.restype = restype
+        self.argtypes = argtypes
+
     def _as_parameter_(self):
         # So we can pass this variadic function as a function pointer
         return self.func
-    def __call__(self,*args):
-        fixed_args=[]
-        i=0
+
+    def __call__(self, *args):
+        fixed_args = []
+        i = 0
         for argtype in self.argtypes:
             # Typecheck what we can
             fixed_args.append(argtype.from_param(args[i]))
-            i+=1
-        return self.func(*fixed_args+list(args[i:]))
-
+            i += 1
+        return self.func(*fixed_args + list(args[i:]))