Преглед на файлове

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',
     'stats',
     'vector',
     'vector',
     'vedit'
     'vedit'
-    ]
+]

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

@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 #!/usr/bin/env python
 
 
+
 def find_names_in_modules(modules):
 def find_names_in_modules(modules):
     names = set()
     names = set()
     for module in modules:
     for module in modules:
@@ -11,7 +12,12 @@ def find_names_in_modules(modules):
             names.union(dir(module))
             names.union(dir(module))
     return names
     return names
 
 
-import optparse, sys
+import optparse
+import sys
+
+import ctypesgencore
+import ctypesgencore.messages as msgs
+
 
 
 def option_callback_W(option, opt, value, parser):
 def option_callback_W(option, opt, value, parser):
     # Options preceded by a "-Wl," are simply treated as though the "-Wl,"
     # 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.
     # Push the linker option onto the list for further parsing.
     parser.rargs.insert(0, value)
     parser.rargs.insert(0, value)
 
 
+
 def option_callback_libdir(option, opt, value, parser):
 def option_callback_libdir(option, opt, value, parser):
     # There are two sets of linker search paths: those for use at compile time
     # 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
     # 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.compile_libdirs.append(value)
     parser.values.runtime_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 ...'
     usage = 'usage: %prog [options] /path/to/header.h ...'
     op = optparse.OptionParser(usage=usage)
     op = optparse.OptionParser(usage=usage)
-    
+
     # Parameters
     # Parameters
     op.add_option('-o', '--output', dest='output', metavar='FILE',
     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',
     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',
     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',
     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',
     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,
     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",
     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",
     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",
     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
     # Parser options
     op.add_option('', '--cpp', dest='cpp', default='gcc -E',
     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',
     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
     # Processor options
     op.add_option('-a', '--all-headers', action='store_true',
     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',
     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',
     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',
     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',
     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
     # Printer options
     op.add_option('', '--header-template', dest='header_template', default=None,
     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',
     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=[],
     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
     # Error options
     op.add_option('', "--all-errors", action="store_true", default=False,
     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,
     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,
     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)
     op.set_defaults(**ctypesgencore.options.default_values)
-    
+
     (options, args) = op.parse_args(list(sys.argv[1:]))
     (options, args) = op.parse_args(list(sys.argv[1:]))
     options.headers = args
     options.headers = args
 
 
     # Figure out what names will be defined by imported Python modules
     # Figure out what names will be defined by imported Python modules
     options.other_known_names = find_names_in_modules(options.modules)
     options.other_known_names = find_names_in_modules(options.modules)
-    
+
     # Required parameters
     # Required parameters
     if len(args) < 1:
     if len(args) < 1:
         msgs.error_message('No header files specified', cls='usage')
         msgs.error_message('No header files specified', cls='usage')
@@ -129,22 +134,22 @@ if __name__=="__main__":
 
 
     if len(options.libraries) == 0:
     if len(options.libraries) == 0:
         msgs.warning_message('No libraries specified', cls='usage')
         msgs.warning_message('No libraries specified', cls='usage')
-    
+
     # Step 1: Parse
     # Step 1: Parse
-    descriptions=ctypesgencore.parser.parse(options.headers,options)
-    
+    descriptions = ctypesgencore.parser.parse(options.headers, options)
+
     # Step 2: Process
     # Step 2: Process
-    ctypesgencore.processor.process(descriptions,options)
-    
+    ctypesgencore.processor.process(descriptions, options)
+
     # Step 3: Print
     # Step 3: Print
-    ctypesgencore.printer.WrapperPrinter(options.output,options,descriptions)
-    
+    ctypesgencore.printer.WrapperPrinter(options.output, options, descriptions)
+
     msgs.status_message("Wrapping complete.")
     msgs.status_message("Wrapping complete.")
-    
+
     # Correct what may be a common mistake
     # Correct what may be a common mistake
     if descriptions.all == []:
     if descriptions.all == []:
         if not options.all_headers:
         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
 # Workhorse modules
 import parser
 import parser

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

@@ -24,68 +24,77 @@ import warnings
 __docformat__ = 'restructuredtext'
 __docformat__ = 'restructuredtext'
 
 
 ctypes_type_map = {
 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.
 # This protocol is used for walking type trees.
+
+
 class CtypesTypeVisitor(object):
 class CtypesTypeVisitor(object):
+
     def visit_struct(self, struct):
     def visit_struct(self, struct):
         pass
         pass
 
 
     def visit_enum(self, enum):
     def visit_enum(self, enum):
         pass
         pass
-    
+
     def visit_typedef(self, name):
     def visit_typedef(self, name):
         pass
         pass
-    
+
     def visit_error(self, error, cls):
     def visit_error(self, error, cls):
         pass
         pass
-    
+
     def visit_identifier(self, identifier):
     def visit_identifier(self, identifier):
         # This one comes from inside ExpressionNodes. There may be
         # This one comes from inside ExpressionNodes. There may be
         # ExpressionNode objects in array count expressions.
         # ExpressionNode objects in array count expressions.
         pass
         pass
 
 
+
 def visit_type_and_collect_info(ctype):
 def visit_type_and_collect_info(ctype):
     class Visitor(CtypesTypeVisitor):
     class Visitor(CtypesTypeVisitor):
-        def visit_struct(self,struct):
+
+        def visit_struct(self, struct):
             structs.append(struct)
             structs.append(struct)
-        def visit_enum(self,enum):
+
+        def visit_enum(self, enum):
             enums.append(enum)
             enums.append(enum)
-        def visit_typedef(self,typedef):
+
+        def visit_typedef(self, typedef):
             typedefs.append(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)
             identifiers.append(identifier)
     structs = []
     structs = []
     enums = []
     enums = []
@@ -94,35 +103,41 @@ def visit_type_and_collect_info(ctype):
     identifiers = []
     identifiers = []
     v = Visitor()
     v = Visitor()
     ctype.visit(v)
     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
 # Remove one level of indirection from funtion pointer; needed for typedefs
 # and function parameters.
 # and function parameters.
+
+
 def remove_function_pointer(t):
 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
         return t.destination
-    elif type(t) == CtypesPointer:
+    elif isinstance(t, CtypesPointer):
         t.destination = remove_function_pointer(t.destination)
         t.destination = remove_function_pointer(t.destination)
         return t
         return t
     else:
     else:
         return t
         return t
 
 
+
 class CtypesType(object):
 class CtypesType(object):
+
     def __init__(self):
     def __init__(self):
-        self.errors=[]
-    
+        self.errors = []
+
     def __repr__(self):
     def __repr__(self):
         return "<Ctype \"%s\">" % self.py_string()
         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):
 class CtypesSimple(CtypesType):
     """Represents a builtin type, like "char" or "int"."""
     """Represents a builtin type, like "char" or "int"."""
+
     def __init__(self, name, signed, longs):
     def __init__(self, name, signed, longs):
         CtypesType.__init__(self)
         CtypesType.__init__(self)
         self.name = name
         self.name = name
@@ -130,80 +145,92 @@ class CtypesSimple(CtypesType):
         self.longs = longs
         self.longs = longs
 
 
     def py_string(self):
     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):
 class CtypesSpecial(CtypesType):
-    def __init__(self,name):
+
+    def __init__(self, name):
         CtypesType.__init__(self)
         CtypesType.__init__(self)
         self.name = name
         self.name = name
-    
+
     def py_string(self):
     def py_string(self):
         return self.name
         return self.name
 
 
+
 class CtypesTypedef(CtypesType):
 class CtypesTypedef(CtypesType):
     """Represents a type defined by a typedef."""
     """Represents a type defined by a typedef."""
+
     def __init__(self, name):
     def __init__(self, name):
         CtypesType.__init__(self)
         CtypesType.__init__(self)
         self.name = name
         self.name = name
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         if not self.errors:
         if not self.errors:
             visitor.visit_typedef(self.name)
             visitor.visit_typedef(self.name)
-        CtypesType.visit(self,visitor)
-    
+        CtypesType.visit(self, visitor)
+
     def py_string(self):
     def py_string(self):
         return self.name
         return self.name
 
 
+
 class CtypesBitfield(CtypesType):
 class CtypesBitfield(CtypesType):
+
     def __init__(self, base, bitfield):
     def __init__(self, base, bitfield):
         CtypesType.__init__(self)
         CtypesType.__init__(self)
         self.base = base
         self.base = base
         self.bitfield = bitfield
         self.bitfield = bitfield
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         self.base.visit(visitor)
         self.base.visit(visitor)
-        CtypesType.visit(self,visitor)
-    
+        CtypesType.visit(self, visitor)
+
     def py_string(self):
     def py_string(self):
         return self.base.py_string()
         return self.base.py_string()
 
 
+
 class CtypesPointer(CtypesType):
 class CtypesPointer(CtypesType):
+
     def __init__(self, destination, qualifiers):
     def __init__(self, destination, qualifiers):
         CtypesType.__init__(self)
         CtypesType.__init__(self)
         self.destination = destination
         self.destination = destination
         self.qualifiers = qualifiers
         self.qualifiers = qualifiers
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         if self.destination:
         if self.destination:
             self.destination.visit(visitor)
             self.destination.visit(visitor)
-        CtypesType.visit(self,visitor)
+        CtypesType.visit(self, visitor)
 
 
     def py_string(self):
     def py_string(self):
         return 'POINTER(%s)' % self.destination.py_string()
         return 'POINTER(%s)' % self.destination.py_string()
 
 
+
 class CtypesArray(CtypesType):
 class CtypesArray(CtypesType):
+
     def __init__(self, base, count):
     def __init__(self, base, count):
         CtypesType.__init__(self)
         CtypesType.__init__(self)
         self.base = base
         self.base = base
         self.count = count
         self.count = count
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         self.base.visit(visitor)
         self.base.visit(visitor)
         if self.count:
         if self.count:
             self.count.visit(visitor)
             self.count.visit(visitor)
-        CtypesType.visit(self,visitor)
-    
+        CtypesType.visit(self, visitor)
+
     def py_string(self):
     def py_string(self):
         if self.count is None:
         if self.count is None:
             return 'POINTER(%s)' % self.base.py_string()
             return 'POINTER(%s)' % self.base.py_string()
-        if type(self.base) == CtypesArray:
+        if isinstance(self.base, CtypesArray):
             return '(%s) * %s' % (self.base.py_string(),
             return '(%s) * %s' % (self.base.py_string(),
                                   self.count.py_string(False))
                                   self.count.py_string(False))
         else:
         else:
             return '%s * %s' % (self.base.py_string(),
             return '%s * %s' % (self.base.py_string(),
                                 self.count.py_string(False))
                                 self.count.py_string(False))
 
 
+
 class CtypesFunction(CtypesType):
 class CtypesFunction(CtypesType):
+
     def __init__(self, restype, parameters, variadic=False):
     def __init__(self, restype, parameters, variadic=False):
         CtypesType.__init__(self)
         CtypesType.__init__(self)
         self.restype = restype
         self.restype = restype
@@ -212,8 +239,8 @@ class CtypesFunction(CtypesType):
         # when ctypes automagically returns it as an int.
         # when ctypes automagically returns it as an int.
         # Instead, convert to POINTER(c_void).  c_void is not a ctypes type,
         # Instead, convert to POINTER(c_void).  c_void is not a ctypes type,
         # you can make it any arbitrary 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.destination.name == 'None':
             self.restype = CtypesPointer(CtypesSpecial('c_void'), ())
             self.restype = CtypesPointer(CtypesSpecial('c_void'), ())
 
 
@@ -223,55 +250,59 @@ class CtypesFunction(CtypesType):
 
 
         self.argtypes = [remove_function_pointer(p) for p in parameters]
         self.argtypes = [remove_function_pointer(p) for p in parameters]
         self.variadic = variadic
         self.variadic = variadic
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         self.restype.visit(visitor)
         self.restype.visit(visitor)
         for a in self.argtypes:
         for a in self.argtypes:
             a.visit(visitor)
             a.visit(visitor)
-        CtypesType.visit(self,visitor)
+        CtypesType.visit(self, visitor)
 
 
     def py_string(self):
     def py_string(self):
         return 'CFUNCTYPE(UNCHECKED(%s), %s)' % (self.restype.py_string(),
         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
 last_tagnum = 0
+
+
 def anonymous_struct_tag():
 def anonymous_struct_tag():
     global last_tagnum
     global last_tagnum
     last_tagnum += 1
     last_tagnum += 1
     return 'anon_%d' % last_tagnum
     return 'anon_%d' % last_tagnum
 
 
+
 class CtypesStruct(CtypesType):
 class CtypesStruct(CtypesType):
+
     def __init__(self, tag, variety, members, src=None):
     def __init__(self, tag, variety, members, src=None):
         CtypesType.__init__(self)
         CtypesType.__init__(self)
         self.tag = tag
         self.tag = tag
-        self.variety = variety # "struct" or "union"
+        self.variety = variety  # "struct" or "union"
         self.members = members
         self.members = members
-        
+
         if not self.tag:
         if not self.tag:
             self.tag = anonymous_struct_tag()
             self.tag = anonymous_struct_tag()
             self.anonymous = True
             self.anonymous = True
         else:
         else:
             self.anonymous = False
             self.anonymous = False
-        
-        if self.members==None:
+
+        if self.members is None:
             self.opaque = True
             self.opaque = True
         else:
         else:
             self.opaque = False
             self.opaque = False
-        
-        self.src = src        
-    
+
+        self.src = src
+
     def get_required_types(self):
     def get_required_types(self):
         types = CtypesType.get_required_types(self)
         types = CtypesType.get_required_types(self)
-        types.add((self.variety,self.tag))
+        types.add((self.variety, self.tag))
         return types
         return types
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         visitor.visit_struct(self)
         visitor.visit_struct(self)
         if not self.opaque:
         if not self.opaque:
-            for name,ctype in self.members:
+            for name, ctype in self.members:
                 ctype.visit(visitor)
                 ctype.visit(visitor)
-        CtypesType.visit(self,visitor)
-    
+        CtypesType.visit(self, visitor)
+
     def get_subtypes(self):
     def get_subtypes(self):
         if self.opaque:
         if self.opaque:
             return set()
             return set()
@@ -279,36 +310,40 @@ class CtypesStruct(CtypesType):
             return set([m[1] for m in self.members])
             return set([m[1] for m in self.members])
 
 
     def py_string(self):
     def py_string(self):
-        return "%s_%s" % (self.variety,self.tag)
+        return "%s_%s" % (self.variety, self.tag)
 
 
 last_tagnum = 0
 last_tagnum = 0
+
+
 def anonymous_enum_tag():
 def anonymous_enum_tag():
     global last_tagnum
     global last_tagnum
     last_tagnum += 1
     last_tagnum += 1
     return 'anon_%d' % last_tagnum
     return 'anon_%d' % last_tagnum
 
 
+
 class CtypesEnum(CtypesType):
 class CtypesEnum(CtypesType):
+
     def __init__(self, tag, enumerators, src=None):
     def __init__(self, tag, enumerators, src=None):
         CtypesType.__init__(self)
         CtypesType.__init__(self)
         self.tag = tag
         self.tag = tag
         self.enumerators = enumerators
         self.enumerators = enumerators
-        
+
         if not self.tag:
         if not self.tag:
             self.tag = anonymous_enum_tag()
             self.tag = anonymous_enum_tag()
             self.anonymous = True
             self.anonymous = True
         else:
         else:
             self.anonymous = False
             self.anonymous = False
-        
-        if self.enumerators==None:
+
+        if self.enumerators is None:
             self.opaque = True
             self.opaque = True
         else:
         else:
             self.opaque = False
             self.opaque = False
-        
+
         self.src = src
         self.src = src
-        
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         visitor.visit_enum(self)
         visitor.visit_enum(self)
-        CtypesType.visit(self,visitor)
+        CtypesType.visit(self, visitor)
 
 
     def py_string(self):
     def py_string(self):
         return 'enum_%s' % self.tag
         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.
 lists of Description objects.
 """
 """
 
 
+
 class DescriptionCollection(object):
 class DescriptionCollection(object):
     """Represents a collection of Descriptions."""
     """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):
 class Description(object):
     """Represents a constant, typedef, struct, function, variable, enum,
     """Represents a constant, typedef, struct, function, variable, enum,
     or macro description. Description is an abstract base class."""
     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",
         # If object will be included in output file. Values are "yes", "never",
         # and "if_needed".
         # and "if_needed".
-        self.include_rule="yes" 
-        
+        self.include_rule = "yes"
+
         # A word about requirements, and dependents:
         # A word about requirements, and dependents:
         # If X requires Y, Y is in X.requirements.
         # If X requires Y, Y is in X.requirements.
         # If X is in Y.requirements, then Y is in X.dependents.
         # 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
         # If the processor module finds a fatal error that prevents a
         # a description from being output, then it appends a string describing
         # a description from being output, then it appends a string describing
         # the problem to 'errors'. If it finds a nonfatal error, it appends a
         # the problem to 'errors'. If it finds a nonfatal error, it appends a
         # string to 'warnings'. If the description would have been output, then
         # string to 'warnings'. If the description would have been output, then
         # the errors and warnings are printed.
         # the errors and warnings are printed.
-        
+
         # If there is anything in 'errors' after processing is complete, the
         # If there is anything in 'errors' after processing is complete, the
         # description is not output.
         # 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)
         self.requirements = self.requirements.union(reqs)
         for req in reqs:
         for req in reqs:
             req.dependents.add(self)
             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):
     def __repr__(self):
         return "<Description: %s>" % self.casual_name()
         return "<Description: %s>" % self.casual_name()
-    
+
     def casual_name(self):
     def casual_name(self):
         """Return a name to show the user."""
         """Return a name to show the user."""
+
     def py_name(self):
     def py_name(self):
         """Return the name associated with this description in Python code."""
         """Return the name associated with this description in Python code."""
+
     def c_name(self):
     def c_name(self):
         """Return the name associated with this description in C code."""
         """Return the name associated with this description in C code."""
 
 
+
 class ConstantDescription(Description):
 class ConstantDescription(Description):
     """Simple class to contain information about a constant."""
     """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
         # Name of constant, a string
-        self.name=name 
+        self.name = name
         # Value of constant, as an ExpressionNode object
         # Value of constant, as an ExpressionNode object
-        self.value=value 
+        self.value = value
+
     def casual_name(self):
     def casual_name(self):
-        return "Constant \"%s\""%self.name
+        return "Constant \"%s\"" % self.name
+
     def py_name(self):
     def py_name(self):
         return self.name
         return self.name
+
     def c_name(self):
     def c_name(self):
         return self.name
         return self.name
 
 
+
 class TypedefDescription(Description):
 class TypedefDescription(Description):
     """Simple container class for a type definition."""
     """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):
     def casual_name(self):
-        return "Typedef \"%s\""%self.name
+        return "Typedef \"%s\"" % self.name
+
     def py_name(self):
     def py_name(self):
         return self.name
         return self.name
+
     def c_name(self):
     def c_name(self):
         return self.name
         return self.name
 
 
+
 class StructDescription(Description):
 class StructDescription(Description):
     """Simple container class for a structure or union definition."""
     """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"
         # The name of the structure minus the "struct" or "union"
-        self.tag=tag 
+        self.tag = tag
         # A string "struct" or "union"
         # A string "struct" or "union"
-        self.variety=variety 
+        self.variety = variety
         # A list of pairs of (name,ctype)
         # A list of pairs of (name,ctype)
-        self.members=members 
+        self.members = members
         # True if struct body was not specified in header file
         # True if struct body was not specified in header file
-        self.opaque=opaque 
+        self.opaque = opaque
         # The original CtypeStruct that created the struct
         # The original CtypeStruct that created the struct
-        self.ctype=ctype 
+        self.ctype = ctype
+
     def casual_name(self):
     def casual_name(self):
-        return "%s \"%s\""%(self.variety.capitalize(),self.tag)
+        return "%s \"%s\"" % (self.variety.capitalize(), self.tag)
+
     def py_name(self):
     def py_name(self):
-        return "%s_%s"%(self.variety,self.tag)
+        return "%s_%s" % (self.variety, self.tag)
+
     def c_name(self):
     def c_name(self):
-        return "%s %s"%(self.variety,self.tag)
+        return "%s %s" % (self.variety, self.tag)
+
 
 
 class EnumDescription(Description):
 class EnumDescription(Description):
     """Simple container class for an enum definition."""
     """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"
         # 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
         # A list of (name,value) pairs where value is a number
-        self.members=members 
+        self.members = members
         # The original CtypeEnum that created the enum
         # The original CtypeEnum that created the enum
-        self.ctype=ctype 
+        self.ctype = ctype
+
     def casual_name(self):
     def casual_name(self):
-        return "Enum \"%s\""%self.tag
+        return "Enum \"%s\"" % self.tag
+
     def py_name(self):
     def py_name(self):
-        return "enum_%s"%self.tag
+        return "enum_%s" % self.tag
+
     def c_name(self):
     def c_name(self):
-        return "enum %s"%self.tag
+        return "enum %s" % self.tag
+
 
 
 class FunctionDescription(Description):
 class FunctionDescription(Description):
     """Simple container class for a C function."""
     """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
         # Name, a string
-        self.name=name 
+        self.name = name
         # Name according to C - stored in case description is renamed
         # Name according to C - stored in case description is renamed
-        self.cname=name 
+        self.cname = name
         # A ctype representing return type
         # A ctype representing return type
-        self.restype=restype 
+        self.restype = restype
         # A list of ctypes representing the argument types
         # A list of ctypes representing the argument types
-        self.argtypes=argtypes 
+        self.argtypes = argtypes
         # Does this function accept a variable number of arguments?
         # Does this function accept a variable number of arguments?
-        self.variadic=variadic 
+        self.variadic = variadic
+
     def casual_name(self):
     def casual_name(self):
-        return "Function \"%s\""%self.name
+        return "Function \"%s\"" % self.name
+
     def py_name(self):
     def py_name(self):
         return self.name
         return self.name
+
     def c_name(self):
     def c_name(self):
         return self.cname
         return self.cname
 
 
+
 class VariableDescription(Description):
 class VariableDescription(Description):
     """Simple container class for a C variable declaration."""
     """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
         # Name, a string
-        self.name=name 
+        self.name = name
         # Name according to C - stored in case description is renamed
         # Name according to C - stored in case description is renamed
-        self.cname=name 
+        self.cname = name
         # The type of the variable
         # The type of the variable
-        self.ctype=ctype 
+        self.ctype = ctype
+
     def casual_name(self):
     def casual_name(self):
-        return "Variable \"%s\""%self.name
+        return "Variable \"%s\"" % self.name
+
     def py_name(self):
     def py_name(self):
         return self.name
         return self.name
+
     def c_name(self):
     def c_name(self):
         return self.cname
         return self.cname
 
 
+
 class MacroDescription(Description):
 class MacroDescription(Description):
     """Simple container class for a C macro."""
     """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.name = name
         self.params = params
         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):
     def casual_name(self):
-        return "Macro \"%s\""%self.name
+        return "Macro \"%s\"" % self.name
+
     def py_name(self):
     def py_name(self):
         return self.name
         return self.name
+
     def c_name(self):
     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.
 # On the other hand, this would be a challenge to write.
 
 
+
 class EvaluationContext(object):
 class EvaluationContext(object):
     '''Interface for evaluating expression nodes.
     '''Interface for evaluating expression nodes.
     '''
     '''
+
     def evaluate_identifier(self, name):
     def evaluate_identifier(self, name):
         warnings.warn('Attempt to evaluate identifier "%s" failed' % name)
         warnings.warn('Attempt to evaluate identifier "%s" failed' % name)
         return 0
         return 0
@@ -33,38 +35,42 @@ class EvaluationContext(object):
     def evaluate_sizeof(self, type):
     def evaluate_sizeof(self, type):
         warnings.warn('Attempt to evaluate sizeof "%s" failed' % str(type))
         warnings.warn('Attempt to evaluate sizeof "%s" failed' % str(type))
         return 0
         return 0
-    
+
     def evaluate_sizeof(self, object):
     def evaluate_sizeof(self, object):
         warnings.warn('Attempt to evaluate sizeof object "%s" failed' % str(object))
         warnings.warn('Attempt to evaluate sizeof object "%s" failed' % str(object))
         return 0
         return 0
-    
+
     def evaluate_parameter(self, name):
     def evaluate_parameter(self, name):
         warnings.warn('Attempt to evaluate parameter "%s" failed' % name)
         warnings.warn('Attempt to evaluate parameter "%s" failed' % name)
         return 0
         return 0
 
 
+
 class ExpressionNode(object):
 class ExpressionNode(object):
+
     def __init__(self):
     def __init__(self):
         self.errors = []
         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):
     def __repr__(self):
         try:
         try:
             string = repr(self.py_string(True))
             string = repr(self.py_string(True))
         except ValueError:
         except ValueError:
             string = "<error in expression node>"
             string = "<error in expression node>"
         return "<ExpressionNode: %s>" % string
         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):
 class ConstantExpressionNode(ExpressionNode):
+
     def __init__(self, value):
     def __init__(self, value):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.value = value
         self.value = value
-    
+
     def evaluate(self, context):
     def evaluate(self, context):
         return self.value
         return self.value
 
 
@@ -82,40 +88,46 @@ class ConstantExpressionNode(ExpressionNode):
             return "float('-inf')"
             return "float('-inf')"
         return repr(self.value)
         return repr(self.value)
 
 
+
 class IdentifierExpressionNode(ExpressionNode):
 class IdentifierExpressionNode(ExpressionNode):
+
     def __init__(self, name):
     def __init__(self, name):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.name = name
         self.name = name
 
 
     def evaluate(self, context):
     def evaluate(self, context):
         return context.evaluate_identifier(self.name)
         return context.evaluate_identifier(self.name)
-    
+
     def visit(self, visitor):
     def visit(self, visitor):
         visitor.visit_identifier(self.name)
         visitor.visit_identifier(self.name)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def py_string(self, can_be_ctype):
     def py_string(self, can_be_ctype):
         # Errors will be thrown in generated code if identifier evaluates
         # Errors will be thrown in generated code if identifier evaluates
         # to a ctypes object, and can_be_ctype is False.
         # to a ctypes object, and can_be_ctype is False.
         return self.name
         return self.name
 
 
+
 class ParameterExpressionNode(ExpressionNode):
 class ParameterExpressionNode(ExpressionNode):
+
     def __init__(self, name):
     def __init__(self, name):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.name = name
         self.name = name
-    
+
     def evaluate(self, context):
     def evaluate(self, context):
         return context.evaluate_parameter(self.name)
         return context.evaluate_parameter(self.name)
-    
+
     def visit(self, visitor):
     def visit(self, visitor):
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def py_string(self, can_be_ctype):
     def py_string(self, can_be_ctype):
         # Errors will be thrown in generated code if parameter is
         # Errors will be thrown in generated code if parameter is
         # a ctypes object, and can_be_ctype is False.
         # a ctypes object, and can_be_ctype is False.
         return self.name
         return self.name
 
 
+
 class UnaryExpressionNode(ExpressionNode):
 class UnaryExpressionNode(ExpressionNode):
+
     def __init__(self, name, op, format, child_can_be_ctype, child):
     def __init__(self, name, op, format, child_can_be_ctype, child):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.name = name
         self.name = name
@@ -123,31 +135,33 @@ class UnaryExpressionNode(ExpressionNode):
         self.format = format
         self.format = format
         self.child_can_be_ctype = child_can_be_ctype
         self.child_can_be_ctype = child_can_be_ctype
         self.child = child
         self.child = child
-    
+
     def visit(self, visitor):
     def visit(self, visitor):
         self.child.visit(visitor)
         self.child.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
     def evaluate(self, context):
         if self.op:
         if self.op:
             return self.op(self.child.evaluate(context))
             return self.op(self.child.evaluate(context))
         else:
         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):
     def py_string(self, can_be_ctype):
         return self.format % \
         return self.format % \
             self.child.py_string(self.child_can_be_ctype and can_be_ctype)
             self.child.py_string(self.child_can_be_ctype and can_be_ctype)
 
 
+
 class SizeOfExpressionNode(ExpressionNode):
 class SizeOfExpressionNode(ExpressionNode):
+
     def __init__(self, child):
     def __init__(self, child):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.child = child
         self.child = child
-    
+
     def visit(self, visitor):
     def visit(self, visitor):
         self.child.visit(visitor)
         self.child.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
     def evaluate(self, context):
         if isinstance(self.child, CtypesType):
         if isinstance(self.child, CtypesType):
             return context.evaluate_sizeof(self.child)
             return context.evaluate_sizeof(self.child)
@@ -160,7 +174,9 @@ class SizeOfExpressionNode(ExpressionNode):
         else:
         else:
             return 'sizeof(%s)' % self.child.py_string(True)
             return 'sizeof(%s)' % self.child.py_string(True)
 
 
+
 class BinaryExpressionNode(ExpressionNode):
 class BinaryExpressionNode(ExpressionNode):
+
     def __init__(self, name, op, format, can_be_ctype, left, right):
     def __init__(self, name, op, format, can_be_ctype, left, right):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.name = name
         self.name = name
@@ -169,38 +185,40 @@ class BinaryExpressionNode(ExpressionNode):
         self.can_be_ctype = can_be_ctype
         self.can_be_ctype = can_be_ctype
         self.left = left
         self.left = left
         self.right = right
         self.right = right
-    
+
     def visit(self, visitor):
     def visit(self, visitor):
         self.left.visit(visitor)
         self.left.visit(visitor)
         self.right.visit(visitor)
         self.right.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
     def evaluate(self, context):
         if self.op:
         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:
         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):
     def py_string(self, can_be_ctype):
         return self.format % \
         return self.format % \
             (self.left.py_string(self.can_be_ctype[0] and can_be_ctype),
             (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))
              self.right.py_string(self.can_be_ctype[0] and can_be_ctype))
 
 
+
 class ConditionalExpressionNode(ExpressionNode):
 class ConditionalExpressionNode(ExpressionNode):
+
     def __init__(self, cond, yes, no):
     def __init__(self, cond, yes, no):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.cond = cond
         self.cond = cond
         self.yes = yes
         self.yes = yes
         self.no = no
         self.no = no
-    
+
     def visit(self, visitor):
     def visit(self, visitor):
         self.cond.visit(visitor)
         self.cond.visit(visitor)
         self.yes.visit(visitor)
         self.yes.visit(visitor)
         self.no.visit(visitor)
         self.no.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
     def evaluate(self, context):
         if self.cond.evaluate(context):
         if self.cond.evaluate(context):
             return self.yes.evaluate(context)
             return self.yes.evaluate(context)
@@ -213,100 +231,109 @@ class ConditionalExpressionNode(ExpressionNode):
              self.cond.py_string(True),
              self.cond.py_string(True),
              self.no.py_string(can_be_ctype))
              self.no.py_string(can_be_ctype))
 
 
+
 class AttributeExpressionNode(ExpressionNode):
 class AttributeExpressionNode(ExpressionNode):
+
     def __init__(self, op, format, base, attribute):
     def __init__(self, op, format, base, attribute):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.op = op
         self.op = op
         self.format = format
         self.format = format
         self.base = base
         self.base = base
         self.attribute = attribute
         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.
         # the struct member name.
         if self.attribute in keyword.kwlist:
         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)
         self.base.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
+        ExpressionNode.visit(self, visitor)
+
     def evaluate(self, context):
     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):
     def py_string(self, can_be_ctype):
         if can_be_ctype:
         if can_be_ctype:
             return self.format % (self.base.py_string(can_be_ctype),
             return self.format % (self.base.py_string(can_be_ctype),
                                   self.attribute)
                                   self.attribute)
         else:
         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):
 class CallExpressionNode(ExpressionNode):
-    def __init__(self,function,arguments):
+
+    def __init__(self, function, arguments):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.function = function
         self.function = function
         self.arguments = arguments
         self.arguments = arguments
-    
-    def visit(self,visitor):
+
+    def visit(self, visitor):
         self.function.visit(visitor)
         self.function.visit(visitor)
         for arg in self.arguments:
         for arg in self.arguments:
             arg.visit(visitor)
             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]
         arguments = [arg.evaluate(context) for arg in self.arguments]
         return self.function.evaluate(context)(*arguments)
         return self.function.evaluate(context)(*arguments)
-    
+
     def py_string(self, can_be_ctype):
     def py_string(self, can_be_ctype):
         function = self.function.py_string(can_be_ctype)
         function = self.function.py_string(can_be_ctype)
         arguments = [x.py_string(can_be_ctype) for x in self.arguments]
         arguments = [x.py_string(can_be_ctype) for x in self.arguments]
         if can_be_ctype:
         if can_be_ctype:
-            return '(%s (%s))' % (function,", ".join(arguments))
+            return '(%s (%s))' % (function, ", ".join(arguments))
         else:
         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
 # 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.
 # into Python. Ctypesgen doesn't try, except for the special case of NULL.
+
+
 class TypeCastExpressionNode(ExpressionNode):
 class TypeCastExpressionNode(ExpressionNode):
+
     def __init__(self, base, ctype):
     def __init__(self, base, ctype):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.base = base
         self.base = base
         self.ctype = ctype
         self.ctype = ctype
         self.isnull = isinstance(ctype, CtypesPointer) and \
         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
         # No need to visit ctype because it isn't actually used
         self.base.visit(visitor)
         self.base.visit(visitor)
-        ExpressionNode.visit(self,visitor)
-    
-    def evaluate(self,context):
+        ExpressionNode.visit(self, visitor)
+
+    def evaluate(self, context):
         if self.isnull:
         if self.isnull:
             return None
             return None
         else:
         else:
             return self.base.evaluate(context)
             return self.base.evaluate(context)
-    
+
     def py_string(self, can_be_ctype):
     def py_string(self, can_be_ctype):
         if self.isnull:
         if self.isnull:
             return "None"
             return "None"
         else:
         else:
             return self.base.py_string(can_be_ctype)
             return self.base.py_string(can_be_ctype)
 
 
+
 class UnsupportedExpressionNode(ExpressionNode):
 class UnsupportedExpressionNode(ExpressionNode):
-    def __init__(self,message):
+
+    def __init__(self, message):
         ExpressionNode.__init__(self)
         ExpressionNode.__init__(self)
         self.message = message
         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):
     def __repr__(self):
         return "<UnsupportedExpressionNode>"
         return "<UnsupportedExpressionNode>"
-    
+
     def py_string(self, can_be_ctype):
     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) 2008 David James
 # Copyright (c) 2006-2008 Alex Holkner
 # Copyright (c) 2006-2008 Alex Holkner
 # All rights reserved.
 # All rights reserved.
-# 
+#
 # Redistribution and use in source and binary forms, with or without
 # 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:
 # are met:
 #
 #
 #  * Redistributions of source code must retain the above copyright
 #  * Redistributions of source code must retain the above copyright
 #    notice, this list of conditions and the following disclaimer.
 #    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
 #    notice, this list of conditions and the following disclaimer in
 #    the documentation and/or other materials provided with the
 #    the documentation and/or other materials provided with the
 #    distribution.
 #    distribution.
@@ -32,31 +32,37 @@
 # POSSIBILITY OF SUCH DAMAGE.
 # POSSIBILITY OF SUCH DAMAGE.
 # ----------------------------------------------------------------------------
 # ----------------------------------------------------------------------------
 
 
-import os.path, re, sys, glob
+import os.path
+import re
+import sys
+import glob
 import ctypes
 import ctypes
 import ctypes.util
 import ctypes.util
 
 
+
 def _environ_path(name):
 def _environ_path(name):
     if name in os.environ:
     if name in os.environ:
         return os.environ[name].split(":")
         return os.environ[name].split(":")
     else:
     else:
         return []
         return []
 
 
+
 class LibraryLoader(object):
 class LibraryLoader(object):
+
     def __init__(self):
     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."""
         """Given the name of a library, load it."""
         paths = self.getpaths(libname)
         paths = self.getpaths(libname)
-        
+
         for path in paths:
         for path in paths:
             if os.path.exists(path):
             if os.path.exists(path):
                 return self.load(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."""
         """Given a path to a library, load it."""
         try:
         try:
             # Darwin requires dlopen to be called with mode RTLD_GLOBAL instead
             # Darwin requires dlopen to be called with mode RTLD_GLOBAL instead
@@ -68,42 +74,44 @@ class LibraryLoader(object):
             else:
             else:
                 return ctypes.cdll.LoadLibrary(path)
                 return ctypes.cdll.LoadLibrary(path)
         except OSError as e:
         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."""
         """Return a list of paths where the library might be found."""
         if os.path.isabs(libname):
         if os.path.isabs(libname):
             yield libname
             yield libname
-        
+
         else:
         else:
             for path in self.getplatformpaths(libname):
             for path in self.getplatformpaths(libname):
                 yield path
                 yield path
-            
+
             path = ctypes.util.find_library(libname)
             path = ctypes.util.find_library(libname)
-            if path: yield path
-    
+            if path:
+                yield path
+
     def getplatformpaths(self, libname):
     def getplatformpaths(self, libname):
         return []
         return []
 
 
 # Darwin (Mac OS X)
 # Darwin (Mac OS X)
 
 
+
 class DarwinLibraryLoader(LibraryLoader):
 class DarwinLibraryLoader(LibraryLoader):
     name_formats = ["lib%s.dylib", "lib%s.so", "lib%s.bundle", "%s.dylib",
     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:
         if os.path.pathsep in libname:
             names = [libname]
             names = [libname]
         else:
         else:
             names = [format % libname for format in self.name_formats]
             names = [format % libname for format in self.name_formats]
-        
+
         for dir in self.getdirs(libname):
         for dir in self.getdirs(libname):
             for name in names:
             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:
         '''Implements the dylib search as specified in Apple documentation:
-        
+
         http://developer.apple.com/documentation/DeveloperTools/Conceptual/
         http://developer.apple.com/documentation/DeveloperTools/Conceptual/
             DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html
             DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html
 
 
@@ -116,9 +124,9 @@ class DarwinLibraryLoader(LibraryLoader):
         if not dyld_fallback_library_path:
         if not dyld_fallback_library_path:
             dyld_fallback_library_path = [os.path.expanduser('~/lib'),
             dyld_fallback_library_path = [os.path.expanduser('~/lib'),
                                           '/usr/local/lib', '/usr/lib']
                                           '/usr/local/lib', '/usr/lib']
-        
+
         dirs = []
         dirs = []
-        
+
         if '/' in libname:
         if '/' in libname:
             dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
             dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
         else:
         else:
@@ -127,7 +135,7 @@ class DarwinLibraryLoader(LibraryLoader):
 
 
         dirs.extend(self.other_dirs)
         dirs.extend(self.other_dirs)
         dirs.append(".")
         dirs.append(".")
-        
+
         if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
         if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
             dirs.append(os.path.join(
             dirs.append(os.path.join(
                 os.environ['RESOURCEPATH'],
                 os.environ['RESOURCEPATH'],
@@ -135,14 +143,15 @@ class DarwinLibraryLoader(LibraryLoader):
                 'Frameworks'))
                 'Frameworks'))
 
 
         dirs.extend(dyld_fallback_library_path)
         dirs.extend(dyld_fallback_library_path)
-        
+
         return dirs
         return dirs
 
 
 # Posix
 # Posix
 
 
+
 class PosixLibraryLoader(LibraryLoader):
 class PosixLibraryLoader(LibraryLoader):
     _ld_so_cache = None
     _ld_so_cache = None
-    
+
     def _create_ld_so_cache(self):
     def _create_ld_so_cache(self):
         # Recreate search path followed by ld.so.  This is going to be
         # 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
         # slow to build, and incorrect (ld.so uses ld.so.cache, which may
@@ -153,17 +162,19 @@ class PosixLibraryLoader(LibraryLoader):
 
 
         directories = []
         directories = []
         for name in ("LD_LIBRARY_PATH",
         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:
             if name in os.environ:
                 directories.extend(os.environ[name].split(os.pathsep))
                 directories.extend(os.environ[name].split(os.pathsep))
         directories.extend(self.other_dirs)
         directories.extend(self.other_dirs)
         directories.append(".")
         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'])
         directories.extend(['/lib', '/usr/lib', '/lib64', '/usr/lib64'])
 
 
@@ -178,7 +189,7 @@ class PosixLibraryLoader(LibraryLoader):
                     # Index by filename
                     # Index by filename
                     if file not in cache:
                     if file not in cache:
                         cache[file] = path
                         cache[file] = path
-                    
+
                     # Index by library name
                     # Index by library name
                     match = lib_re.match(file)
                     match = lib_re.match(file)
                     if match:
                     if match:
@@ -189,37 +200,44 @@ class PosixLibraryLoader(LibraryLoader):
                 pass
                 pass
 
 
         self._ld_so_cache = cache
         self._ld_so_cache = cache
-    
+
     def getplatformpaths(self, libname):
     def getplatformpaths(self, libname):
         if self._ld_so_cache is None:
         if self._ld_so_cache is None:
             self._create_ld_so_cache()
             self._create_ld_so_cache()
 
 
         result = self._ld_so_cache.get(libname)
         result = self._ld_so_cache.get(libname)
-        if result: yield result
+        if result:
+            yield result
 
 
         path = ctypes.util.find_library(libname)
         path = ctypes.util.find_library(libname)
-        if path: yield os.path.join("/lib",path)
+        if path:
+            yield os.path.join("/lib", path)
 
 
 # Windows
 # Windows
 
 
+
 class _WindowsLibrary(object):
 class _WindowsLibrary(object):
+
     def __init__(self, path):
     def __init__(self, path):
         self.cdll = ctypes.cdll.LoadLibrary(path)
         self.cdll = ctypes.cdll.LoadLibrary(path)
         self.windll = ctypes.windll.LoadLibrary(path)
         self.windll = ctypes.windll.LoadLibrary(path)
 
 
     def __getattr__(self, name):
     def __getattr__(self, name):
-        try: return getattr(self.cdll,name)
+        try:
+            return getattr(self.cdll, name)
         except AttributeError:
         except AttributeError:
-            try: return getattr(self.windll,name)
+            try:
+                return getattr(self.windll, name)
             except AttributeError:
             except AttributeError:
                 raise
                 raise
 
 
+
 class WindowsLibraryLoader(LibraryLoader):
 class WindowsLibraryLoader(LibraryLoader):
     name_formats = ["%s.dll", "lib%s.dll"]
     name_formats = ["%s.dll", "lib%s.dll"]
-    
+
     def load(self, path):
     def load(self, path):
         return _WindowsLibrary(path)
         return _WindowsLibrary(path)
-    
+
     def getplatformpaths(self, libname):
     def getplatformpaths(self, libname):
         if os.path.sep not in libname:
         if os.path.sep not in libname:
             for name in self.name_formats:
             for name in self.name_formats:
@@ -233,13 +251,14 @@ class WindowsLibraryLoader(LibraryLoader):
 # the Ctypesgen maintainers.
 # the Ctypesgen maintainers.
 
 
 loaderclass = {
 loaderclass = {
-    "darwin":   DarwinLibraryLoader,
-    "cygwin":   WindowsLibraryLoader,
-    "win32":    WindowsLibraryLoader
+    "darwin": DarwinLibraryLoader,
+    "cygwin": WindowsLibraryLoader,
+    "win32": WindowsLibraryLoader
 }
 }
 
 
 loader = loaderclass.get(sys.platform, PosixLibraryLoader)()
 loader = loaderclass.get(sys.platform, PosixLibraryLoader)()
 
 
+
 def add_library_search_dirs(other_dirs):
 def add_library_search_dirs(other_dirs):
     loader.other_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
 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
     print "Error: %s" % msg
 
 
-def warning_message(msg,cls=None):
+
+def warning_message(msg, cls=None):
     print "Warning: %s" % msg
     print "Warning: %s" % msg
 
 
+
 def status_message(msg):
 def status_message(msg):
     print "Status: %s" % 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.
 for convenience.
 """
 """
 
 
-import optparse, copy
+import optparse
+import copy
 
 
-default_values={
+default_values = {
     "other_headers": [],
     "other_headers": [],
     "modules": [],
     "modules": [],
     "include_search_paths": [],
     "include_search_paths": [],
@@ -33,5 +34,6 @@ default_values={
     "strip_build_path": None
     "strip_build_path": None
 }
 }
 
 
+
 def get_default_options():
 def get_default_options():
     return optparse.Values(copy.deepcopy(default_values))
     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
 from datacollectingparser import DataCollectingParser
 
 
+
 def parse(headers, options):
 def parse(headers, options):
-    parser=DataCollectingParser(headers, options)
+    parser = DataCollectingParser(headers, options)
     parser.parse()
     parser.parse()
     return parser.data()
     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
 # C Object Model
 # --------------------------------------------------------------------------
 # --------------------------------------------------------------------------
 
 
+
 class Declaration(object):
 class Declaration(object):
+
     def __init__(self):
     def __init__(self):
         self.declarator = None
         self.declarator = None
         self.type = Type()
         self.type = Type()
@@ -28,8 +30,10 @@ class Declaration(object):
         l = ['%s=%r' % (k, v) for k, v in d.items()]
         l = ['%s=%r' % (k, v) for k, v in d.items()]
         return 'Declaration(%s)' % ', '.join(l)
         return 'Declaration(%s)' % ', '.join(l)
 
 
+
 class Declarator(object):
 class Declarator(object):
     pointer = None
     pointer = None
+
     def __init__(self):
     def __init__(self):
         self.identifier = None
         self.identifier = None
         self.initializer = None
         self.initializer = None
@@ -52,8 +56,10 @@ class Declarator(object):
             s += '(' + ', '.join([repr(p) for p in self.parameters]) + ')'
             s += '(' + ', '.join([repr(p) for p in self.parameters]) + ')'
         return s
         return s
 
 
+
 class Pointer(Declarator):
 class Pointer(Declarator):
     pointer = None
     pointer = None
+
     def __init__(self):
     def __init__(self):
         super(Pointer, self).__init__()
         super(Pointer, self).__init__()
         self.qualifiers = []
         self.qualifiers = []
@@ -65,14 +71,16 @@ class Pointer(Declarator):
         return 'POINTER%s(%r)' % (q, self.pointer) + \
         return 'POINTER%s(%r)' % (q, self.pointer) + \
             super(Pointer, self).__repr__()
             super(Pointer, self).__repr__()
 
 
+
 class Array(object):
 class Array(object):
+
     def __init__(self):
     def __init__(self):
         self.size = None
         self.size = None
         self.array = None
         self.array = None
 
 
     def __repr__(self):
     def __repr__(self):
         if self.size:
         if self.size:
-            a =  '[%r]' % self.size
+            a = '[%r]' % self.size
         else:
         else:
             a = '[]'
             a = '[]'
         if self.array:
         if self.array:
@@ -80,7 +88,9 @@ class Array(object):
         else:
         else:
             return a
             return a
 
 
+
 class Parameter(object):
 class Parameter(object):
+
     def __init__(self):
     def __init__(self):
         self.type = Type()
         self.type = Type()
         self.storage = None
         self.storage = None
@@ -99,6 +109,7 @@ class Parameter(object):
 
 
 
 
 class Type(object):
 class Type(object):
+
     def __init__(self):
     def __init__(self):
         self.qualifiers = []
         self.qualifiers = []
         self.specifiers = []
         self.specifiers = []
@@ -108,13 +119,17 @@ class Type(object):
 
 
 # These are used only internally.
 # These are used only internally.
 
 
+
 class StorageClassSpecifier(str):
 class StorageClassSpecifier(str):
     pass
     pass
 
 
+
 class TypeSpecifier(str):
 class TypeSpecifier(str):
     pass
     pass
 
 
+
 class StructTypeSpecifier(object):
 class StructTypeSpecifier(object):
+
     def __init__(self, is_union, tag, declarations):
     def __init__(self, is_union, tag, declarations):
         self.is_union = is_union
         self.is_union = is_union
         self.tag = tag
         self.tag = tag
@@ -131,11 +146,13 @@ class StructTypeSpecifier(object):
             s += ' {%s}' % '; '.join([repr(d) for d in self.declarations])
             s += ' {%s}' % '; '.join([repr(d) for d in self.declarations])
         return s
         return s
 
 
+
 class EnumSpecifier(object):
 class EnumSpecifier(object):
+
     def __init__(self, tag, enumerators, src=None):
     def __init__(self, tag, enumerators, src=None):
         self.tag = tag
         self.tag = tag
         self.enumerators = enumerators
         self.enumerators = enumerators
-        self.src=src
+        self.src = src
 
 
     def __repr__(self):
     def __repr__(self):
         s = 'enum'
         s = 'enum'
@@ -145,7 +162,9 @@ class EnumSpecifier(object):
             s += ' {%s}' % ', '.join([repr(e) for e in self.enumerators])
             s += ' {%s}' % ', '.join([repr(e) for e in self.enumerators])
         return s
         return s
 
 
+
 class Enumerator(object):
 class Enumerator(object):
+
     def __init__(self, name, expression):
     def __init__(self, name, expression):
         self.name = name
         self.name = name
         self.expression = expression
         self.expression = expression
@@ -156,19 +175,21 @@ class Enumerator(object):
             s += ' = %r' % self.expression
             s += ' = %r' % self.expression
         return s
         return s
 
 
+
 class TypeQualifier(str):
 class TypeQualifier(str):
     pass
     pass
 
 
+
 def apply_specifiers(specifiers, declaration):
 def apply_specifiers(specifiers, declaration):
     '''Apply specifiers to the declaration (declaration may be
     '''Apply specifiers to the declaration (declaration may be
     a Parameter instead).'''
     a Parameter instead).'''
     for s in specifiers:
     for s in specifiers:
-        if type(s) == StorageClassSpecifier:
+        if isinstance(s, StorageClassSpecifier):
             if declaration.storage:
             if declaration.storage:
                 # Multiple storage classes, technically an error... ignore it
                 # Multiple storage classes, technically an error... ignore it
                 pass
                 pass
             declaration.storage = s
             declaration.storage = s
         elif type(s) in (TypeSpecifier, StructTypeSpecifier, EnumSpecifier):
         elif type(s) in (TypeSpecifier, StructTypeSpecifier, EnumSpecifier):
             declaration.type.specifiers.append(s)
             declaration.type.specifiers.append(s)
-        elif type(s) == TypeQualifier:
+        elif isinstance(s, TypeQualifier):
             declaration.type.qualifiers.append(s)
             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
 # Lexer
 # --------------------------------------------------------------------------
 # --------------------------------------------------------------------------
 
 
+
 class CLexer(object):
 class CLexer(object):
+
     def __init__(self, cparser):
     def __init__(self, cparser):
         self.cparser = cparser
         self.cparser = cparser
         self.type_names = set()
         self.type_names = set()
@@ -38,17 +40,17 @@ class CLexer(object):
     def token(self):
     def token(self):
         while self.pos < len(self.tokens):
         while self.pos < len(self.tokens):
             t = self.tokens[self.pos]
             t = self.tokens[self.pos]
-            
+
             self.pos += 1
             self.pos += 1
 
 
             if not t:
             if not t:
                 break
                 break
-            
+
             if t.type == 'PP_DEFINE':
             if t.type == 'PP_DEFINE':
                 self.in_define = True
                 self.in_define = True
             elif t.type == 'PP_END_DEFINE':
             elif t.type == 'PP_END_DEFINE':
                 self.in_define = False
                 self.in_define = False
-            
+
             # Transform PP tokens into C tokens
             # Transform PP tokens into C tokens
             elif t.type == 'LPAREN':
             elif t.type == 'LPAREN':
                 t.type = '('
                 t.type = '('
@@ -57,36 +59,38 @@ class CLexer(object):
             elif t.type == 'IDENTIFIER' and t.value in cgrammar.keywords:
             elif t.type == 'IDENTIFIER' and t.value in cgrammar.keywords:
                 t.type = t.value.upper()
                 t.type = t.value.upper()
             elif t.type == 'IDENTIFIER' and t.value in self.type_names:
             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.type = 'TYPE_NAME'
-            
+
             t.lexer = self
             t.lexer = self
             t.clexpos = self.pos - 1
             t.clexpos = self.pos - 1
-            
+
             return t
             return t
         return None
         return None
-        
+
 # --------------------------------------------------------------------------
 # --------------------------------------------------------------------------
 # Parser
 # Parser
 # --------------------------------------------------------------------------
 # --------------------------------------------------------------------------
 
 
+
 class CParser(object):
 class CParser(object):
     '''Parse a C source file.
     '''Parse a C source file.
 
 
     Subclass and override the handle_* methods.  Call `parse` with a string
     Subclass and override the handle_* methods.  Call `parse` with a string
     to parse.
     to parse.
     '''
     '''
+
     def __init__(self, options, stddef_types=True, gnu_types=True):
     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()
         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
         # If yacc is reading tables from a file, then it won't find the error
         # function... need to set it manually
         # function... need to set it manually
         prototype.errorfunc = cgrammar.p_error
         prototype.errorfunc = cgrammar.p_error
@@ -102,7 +106,7 @@ class CParser(object):
             self.lexer.type_names.add('__builtin_va_list')
             self.lexer.type_names.add('__builtin_va_list')
         if sys.platform == 'win32':
         if sys.platform == 'win32':
             self.lexer.type_names.add('__int64')
             self.lexer.type_names.add('__int64')
-        
+
     def parse(self, filename, debug=False):
     def parse(self, filename, debug=False):
         '''Parse a file.
         '''Parse a file.
 
 
@@ -120,22 +124,22 @@ class CParser(object):
     # ----------------------------------------------------------------------
     # ----------------------------------------------------------------------
 
 
     def handle_error(self, message, filename, lineno):
     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 default implementation prints `lineno` and `message` to stderr.
         The parser will try to recover from errors by synchronising at the
         The parser will try to recover from errors by synchronising at the
         next semicolon.
         next semicolon.
         '''
         '''
         print >> sys.stderr, '%s:%s %s' % (filename, lineno, message)
         print >> sys.stderr, '%s:%s %s' % (filename, lineno, message)
-    
+
     def handle_pp_error(self, message):
     def handle_pp_error(self, message):
         '''The C preprocessor emitted an error.
         '''The C preprocessor emitted an error.
-        
+
         The default implementatin prints the error to stderr. If processing
         The default implementatin prints the error to stderr. If processing
         can continue, it will.
         can continue, it will.
         '''
         '''
         print >> sys.stderr, 'Preprocessor:', message
         print >> sys.stderr, 'Preprocessor:', message
-    
+
     def handle_status(self, message):
     def handle_status(self, message):
         '''Progress information.
         '''Progress information.
 
 
@@ -144,7 +148,7 @@ class CParser(object):
         print >> sys.stderr, message
         print >> sys.stderr, message
 
 
     def handle_define(self, name, params, value, filename, lineno):
     def handle_define(self, name, params, value, filename, lineno):
-        '''#define `name` `value` 
+        '''#define `name` `value`
         or #define `name`(`params`) `value`
         or #define `name`(`params`) `value`
 
 
         name is a string
         name is a string
@@ -154,19 +158,19 @@ class CParser(object):
 
 
     def handle_define_constant(self, name, value, filename, lineno):
     def handle_define_constant(self, name, value, filename, lineno):
         '''#define `name` `value`
         '''#define `name` `value`
-        
+
         name is a string
         name is a string
         value is an ExpressionNode or None
         value is an ExpressionNode or None
         '''
         '''
-    
+
     def handle_define_macro(self, name, params, value, filename, lineno):
     def handle_define_macro(self, name, params, value, filename, lineno):
         '''#define `name`(`params`) `value`
         '''#define `name`(`params`) `value`
-        
+
         name is a string
         name is a string
         params is a list of strings
         params is a list of strings
         value is an ExpressionNode or None
         value is an ExpressionNode or None
         '''
         '''
-    
+
     def impl_handle_declaration(self, declaration, filename, lineno):
     def impl_handle_declaration(self, declaration, filename, lineno):
         '''Internal method that calls `handle_declaration`.  This method
         '''Internal method that calls `handle_declaration`.  This method
         also adds any new type definitions to the lexer's list of valid type
         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)
         self.handle_declaration(declaration, filename, lineno)
 
 
     def handle_declaration(self, 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
         `declaration` is an instance of Declaration.  Where a declaration has
         multiple initialisers, each is returned as a separate declaration.
         multiple initialisers, each is returned as a separate declaration.
         '''
         '''
         pass
         pass
 
 
+
 class DebugCParser(CParser):
 class DebugCParser(CParser):
     '''A convenience class that prints each invocation of a handle_* method to
     '''A convenience class that prints each invocation of a handle_* method to
     stdout.
     stdout.
@@ -203,6 +208,6 @@ class DebugCParser(CParser):
 
 
     def handle_declaration(self, declaration, filename, lineno):
     def handle_declaration(self, declaration, filename, lineno):
         print declaration
         print declaration
-        
+
 if __name__ == '__main__':
 if __name__ == '__main__':
     DebugCParser().parse(sys.argv[1], debug=True)
     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 cdeclarations import *
 from ctypesgencore.expressions 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
     signed = True
     typename = 'int'
     typename = 'int'
     longs = 0
     longs = 0
     t = None
     t = None
-    
+
     for specifier in typ.specifiers:
     for specifier in typ.specifiers:
         if isinstance(specifier, StructTypeSpecifier):
         if isinstance(specifier, StructTypeSpecifier):
             t = make_struct_from_specifier(specifier)
             t = make_struct_from_specifier(specifier)
@@ -36,15 +37,15 @@ def get_ctypes_type(typ, declarator, check_qualifiers=False):
             longs += 1
             longs += 1
         else:
         else:
             typename = str(specifier)
             typename = str(specifier)
-    
+
     if not t:
     if not t:
         # It is a numeric type of some sort
         # 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:
         elif signed and not longs:
             t = CtypesTypedef(typename)
             t = CtypesTypedef(typename)
-        
+
         else:
         else:
             name = " ".join(typ.specifiers)
             name = " ".join(typ.specifiers)
             if typename in [x[0] for x in ctypes_type_map.keys()]:
             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 " \
                 error = "Ctypes does not support adding additional " \
                     "specifiers to typedefs, such as \"%s\"" % name
                     "specifiers to typedefs, such as \"%s\"" % name
             t = CtypesTypedef(name)
             t = CtypesTypedef(name)
-            t.error(error,cls='unsupported-type')
-        
+            t.error(error, cls='unsupported-type')
+
         if declarator and declarator.bitfield:
         if declarator and declarator.bitfield:
-            t = CtypesBitfield(t,declarator.bitfield)
+            t = CtypesBitfield(t, declarator.bitfield)
 
 
     qualifiers = []
     qualifiers = []
     qualifiers.extend(typ.qualifiers)
     qualifiers.extend(typ.qualifiers)
@@ -67,50 +68,51 @@ def get_ctypes_type(typ, declarator, check_qualifiers=False):
 
 
             params = []
             params = []
             for param in declarator.parameters:
             for param in declarator.parameters:
-                if param=="...":
+                if param == "...":
                     break
                     break
                 params.append(get_ctypes_type(param.type, param.declarator))
                 params.append(get_ctypes_type(param.type, param.declarator))
             t = CtypesFunction(t, params, variadic)
             t = CtypesFunction(t, params, variadic)
-        
+
         a = declarator.array
         a = declarator.array
         while a:
         while a:
             t = CtypesArray(t, a.size)
             t = CtypesArray(t, a.size)
             a = a.array
             a = a.array
 
 
         qualifiers.extend(declarator.qualifiers)
         qualifiers.extend(declarator.qualifiers)
-        
+
         t = CtypesPointer(t, declarator.qualifiers)
         t = CtypesPointer(t, declarator.qualifiers)
-        
+
         declarator = declarator.pointer
         declarator = declarator.pointer
-    
+
     if declarator and declarator.parameters is not None:
     if declarator and declarator.parameters is not None:
         variadic = "..." in declarator.parameters
         variadic = "..." in declarator.parameters
 
 
         params = []
         params = []
         for param in declarator.parameters:
         for param in declarator.parameters:
-            if param=="...":
+            if param == "...":
                 break
                 break
             params.append(get_ctypes_type(param.type, param.declarator))
             params.append(get_ctypes_type(param.type, param.declarator))
         t = CtypesFunction(t, params, variadic)
         t = CtypesFunction(t, params, variadic)
-    
+
     if declarator:
     if declarator:
         a = declarator.array
         a = declarator.array
         while a:
         while a:
             t = CtypesArray(t, a.size)
             t = CtypesArray(t, a.size)
             a = a.array
             a = a.array
-    
+
     if isinstance(t, CtypesPointer) and \
     if isinstance(t, CtypesPointer) and \
        isinstance(t.destination, CtypesSimple) and \
        isinstance(t.destination, CtypesSimple) and \
-       t.destination.name=="char" and \
+       t.destination.name == "char" and \
        t.destination.signed:
        t.destination.signed:
-       t = CtypesSpecial("String")
+        t = CtypesSpecial("String")
 
 
     return t
     return t
 
 
+
 def make_struct_from_specifier(specifier):
 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
     tag = specifier.tag
-    
+
     if specifier.declarations:
     if specifier.declarations:
         members = []
         members = []
         for declaration in specifier.declarations:
         for declaration in specifier.declarations:
@@ -127,13 +129,14 @@ def make_struct_from_specifier(specifier):
             members.append((name, remove_function_pointer(t)))
             members.append((name, remove_function_pointer(t)))
     else:
     else:
         members = None
         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):
 def make_enum_from_specifier(specifier):
     tag = specifier.tag
     tag = specifier.tag
-    
+
     enumerators = []
     enumerators = []
     last_name = None
     last_name = None
     for e in specifier.enumerators:
     for e in specifier.enumerators:
@@ -141,32 +144,33 @@ def make_enum_from_specifier(specifier):
             value = e.expression
             value = e.expression
         else:
         else:
             if last_name:
             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:
             else:
                 value = ConstantExpressionNode(0)
                 value = ConstantExpressionNode(0)
-        
-        enumerators.append((e.name,value))
+
+        enumerators.append((e.name, value))
         last_name = e.name
         last_name = e.name
-    
+
     return CtypesEnum(tag, enumerators,
     return CtypesEnum(tag, enumerators,
-                      src=(specifier.filename,specifier.lineno))
+                      src=(specifier.filename, specifier.lineno))
+
 
 
 class CtypesParser(CParser):
 class CtypesParser(CParser):
     '''Parse a C file for declarations that can be used by ctypes.
     '''Parse a C file for declarations that can be used by ctypes.
-    
+
     Subclass and override the handle_ctypes_* methods.
     Subclass and override the handle_ctypes_* methods.
     '''
     '''
 
 
     def handle_declaration(self, declaration, filename, lineno):
     def handle_declaration(self, declaration, filename, lineno):
         t = get_ctypes_type(declaration.type, declaration.declarator)
         t = get_ctypes_type(declaration.type, declaration.declarator)
-        
+
         if type(t) in (CtypesStruct, CtypesEnum):
         if type(t) in (CtypesStruct, CtypesEnum):
             self.handle_ctypes_new_type(
             self.handle_ctypes_new_type(
                 remove_function_pointer(t), filename, lineno)
                 remove_function_pointer(t), filename, lineno)
-        
+
         declarator = declaration.declarator
         declarator = declaration.declarator
         if declarator is None:
         if declarator is None:
             # XXX TEMPORARY while struct with no typedef not filled in
             # XXX TEMPORARY while struct with no typedef not filled in
@@ -177,17 +181,17 @@ class CtypesParser(CParser):
         if declaration.storage == 'typedef':
         if declaration.storage == 'typedef':
             self.handle_ctypes_typedef(
             self.handle_ctypes_typedef(
                 name, remove_function_pointer(t), filename, lineno)
                 name, remove_function_pointer(t), filename, lineno)
-        elif type(t) == CtypesFunction:
+        elif isinstance(t, CtypesFunction):
             self.handle_ctypes_function(
             self.handle_ctypes_function(
                 name, t.restype, t.argtypes, t.variadic, filename, lineno)
                 name, t.restype, t.argtypes, t.variadic, filename, lineno)
         elif declaration.storage != 'static':
         elif declaration.storage != 'static':
             self.handle_ctypes_variable(name, t, filename, lineno)
             self.handle_ctypes_variable(name, t, filename, lineno)
 
 
     # ctypes parser interface.  Override these methods in your subclass.
     # ctypes parser interface.  Override these methods in your subclass.
-    
+
     def handle_ctypes_new_type(self, ctype, filename, lineno):
     def handle_ctypes_new_type(self, ctype, filename, lineno):
         pass
         pass
-    
+
     def handle_ctypes_typedef(self, name, ctype, filename, lineno):
     def handle_ctypes_typedef(self, name, ctype, filename, lineno):
         pass
         pass
 
 

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

@@ -4,7 +4,7 @@
 DataCollectingParser subclasses ctypesparser.CtypesParser and builds Description
 DataCollectingParser subclasses ctypesparser.CtypesParser and builds Description
 objects from the CtypesType objects and other information from CtypesParser.
 objects from the CtypesType objects and other information from CtypesParser.
 After parsing is complete, a DescriptionCollection object can be retrieved by
 After parsing is complete, a DescriptionCollection object can be retrieved by
-calling DataCollectingParser.data(). 
+calling DataCollectingParser.data().
 """
 """
 
 
 import ctypesparser
 import ctypesparser
@@ -15,6 +15,7 @@ from ctypesgencore.messages import *
 from tempfile import mkstemp
 from tempfile import mkstemp
 import os
 import os
 
 
+
 class DataCollectingParser(ctypesparser.CtypesParser,
 class DataCollectingParser(ctypesparser.CtypesParser,
                            ctypesparser.CtypesTypeVisitor):
                            ctypesparser.CtypesTypeVisitor):
     """Main class for the Parser component. Steps for use:
     """Main class for the Parser component. Steps for use:
@@ -22,41 +23,42 @@ class DataCollectingParser(ctypesparser.CtypesParser,
     p.parse()
     p.parse()
     data=p.data() #A dictionary of constants, enums, structs, functions, etc.
     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 is a useful macro to have defined
         null = ConstantExpressionNode(None)
         null = ConstantExpressionNode(None)
-        nullmacro = ConstantDescription("NULL",null,("<built-in>",1))
+        nullmacro = ConstantDescription("NULL", null, ("<built-in>", 1))
         self.constants.append(nullmacro)
         self.constants.append(nullmacro)
         self.all.append(nullmacro)
         self.all.append(nullmacro)
         self.output_order.append(("constant", nullmacro))
         self.output_order.append(("constant", nullmacro))
-        
+
         # A list of tuples describing macros; saved to be processed after
         # A list of tuples describing macros; saved to be processed after
         # everything else has been parsed
         # everything else has been parsed
         self.saved_macros = []
         self.saved_macros = []
         # A set of structs that are already known
         # 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
         # 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
         # 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
         # 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):
     def parse(self):
         fd, fname = mkstemp(suffix=".h")
         fd, fname = mkstemp(suffix=".h")
         f = os.fdopen(fd, 'w+b')
         f = os.fdopen(fd, 'w+b')
@@ -66,17 +68,17 @@ class DataCollectingParser(ctypesparser.CtypesParser,
             print >>f, '#include "%s"' % os.path.abspath(header)
             print >>f, '#include "%s"' % os.path.abspath(header)
         f.flush()
         f.flush()
         f.close()
         f.close()
-        ctypesparser.CtypesParser.parse(self,fname,None)
+        ctypesparser.CtypesParser.parse(self, fname, None)
         os.remove(fname)
         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)
             self.handle_macro(name, params, expr, filename, lineno)
-            
+
     def handle_define_constant(self, name, expr, filename, lineno):
     def handle_define_constant(self, name, expr, filename, lineno):
         # Called by CParser
         # Called by CParser
         # Save to handle later
         # Save to handle later
         self.saved_macros.append((name, None, expr, (filename, lineno)))
         self.saved_macros.append((name, None, expr, (filename, lineno)))
-    
+
     def handle_define_unparseable(self, name, params, value, filename, lineno):
     def handle_define_unparseable(self, name, params, value, filename, lineno):
         # Called by CParser
         # Called by CParser
         if params:
         if params:
@@ -86,66 +88,66 @@ class DataCollectingParser(ctypesparser.CtypesParser,
             original_string = "#define %s %s" % \
             original_string = "#define %s %s" % \
                 (name, " ".join(value))
                 (name, " ".join(value))
         macro = MacroDescription(name, params, None,
         macro = MacroDescription(name, params, None,
-                                 src = (filename,lineno))
+                                 src=(filename, lineno))
         macro.error("Could not parse macro \"%s\"" % original_string,
         macro.error("Could not parse macro \"%s\"" % original_string,
-                    cls = 'macro')
+                    cls='macro')
         macro.original_string = original_string
         macro.original_string = original_string
         self.macros.append(macro)
         self.macros.append(macro)
         self.all.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):
     def handle_define_macro(self, name, params, expr, filename, lineno):
         # Called by CParser
         # Called by CParser
         # Save to handle later
         # 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):
     def handle_ctypes_typedef(self, name, ctype, filename, lineno):
         # Called by CtypesParser
         # Called by CtypesParser
         ctype.visit(self)
         ctype.visit(self)
-        
-        typedef=TypedefDescription(name,
-                                   ctype,
-                                   src=(filename,repr(lineno)))
-        
+
+        typedef = TypedefDescription(name,
+                                     ctype,
+                                     src=(filename, repr(lineno)))
+
         self.typedefs.append(typedef)
         self.typedefs.append(typedef)
         self.all.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):
     def handle_ctypes_new_type(self, ctype, filename, lineno):
         # Called by CtypesParser
         # Called by CtypesParser
-        if isinstance(ctype,ctypesparser.CtypesEnum):
+        if isinstance(ctype, ctypesparser.CtypesEnum):
             self.handle_enum(ctype, filename, lineno)
             self.handle_enum(ctype, filename, lineno)
         else:
         else:
             self.handle_struct(ctype, filename, lineno)
             self.handle_struct(ctype, filename, lineno)
-    
+
     def handle_ctypes_function(self, name, restype, argtypes, variadic,
     def handle_ctypes_function(self, name, restype, argtypes, variadic,
                                filename, lineno):
                                filename, lineno):
         # Called by CtypesParser
         # Called by CtypesParser
         restype.visit(self)
         restype.visit(self)
         for argtype in argtypes:
         for argtype in argtypes:
             argtype.visit(self)
             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.functions.append(function)
         self.all.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):
     def handle_ctypes_variable(self, name, ctype, filename, lineno):
         # Called by CtypesParser
         # Called by CtypesParser
         ctype.visit(self)
         ctype.visit(self)
-        
-        variable=VariableDescription(name,
-                                     ctype,
-                                     src=(filename,repr(lineno)))
-        
+
+        variable = VariableDescription(name,
+                                       ctype,
+                                       src=(filename, repr(lineno)))
+
         self.variables.append(variable)
         self.variables.append(variable)
         self.all.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):
     def handle_struct(self, ctypestruct, filename, lineno):
         # Called from within DataCollectingParser
         # Called from within DataCollectingParser
@@ -155,79 +157,79 @@ class DataCollectingParser(ctypesparser.CtypesParser,
         # find a transparent struct with the same tag, we fill in the
         # find a transparent struct with the same tag, we fill in the
         # opaque struct with the information from the transparent struct and
         # opaque struct with the information from the transparent struct and
         # move the opaque struct to the end of the struct list.
         # 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:
         if name in self.already_seen_structs:
             return
             return
-        
+
         if ctypestruct.opaque:
         if ctypestruct.opaque:
             if name not in self.already_seen_opaque_structs:
             if name not in self.already_seen_opaque_structs:
                 struct = StructDescription(ctypestruct.tag,
                 struct = StructDescription(ctypestruct.tag,
                                            ctypestruct.variety,
                                            ctypestruct.variety,
-                                           None, # No members
-                                           True, # Opaque
+                                           None,  # No members
+                                           True,  # Opaque
                                            ctypestruct,
                                            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.structs.append(struct)
                 self.all.append(struct)
                 self.all.append(struct)
-                self.output_order.append(('struct',struct))
-        
+                self.output_order.append(('struct', struct))
+
         else:
         else:
-            for (membername,ctype) in ctypestruct.members:
+            for (membername, ctype) in ctypestruct.members:
                 ctype.visit(self)
                 ctype.visit(self)
-            
+
             if name in self.already_seen_opaque_structs:
             if name in self.already_seen_opaque_structs:
                 # Fill in older version
                 # Fill in older version
-                struct=self.already_seen_opaque_structs[name]
+                struct = self.already_seen_opaque_structs[name]
                 struct.opaque = False
                 struct.opaque = False
                 struct.members = ctypestruct.members
                 struct.members = ctypestruct.members
                 struct.ctype = ctypestruct
                 struct.ctype = ctypestruct
                 struct.src = ctypestruct.src
                 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]
                 del self.already_seen_opaque_structs[name]
-            
+
             else:
             else:
                 struct = StructDescription(ctypestruct.tag,
                 struct = StructDescription(ctypestruct.tag,
                                            ctypestruct.variety,
                                            ctypestruct.variety,
                                            ctypestruct.members,
                                            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.structs.append(struct)
                 self.all.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)
             self.already_seen_structs.add(name)
-    
+
     def handle_enum(self, ctypeenum, filename, lineno):
     def handle_enum(self, ctypeenum, filename, lineno):
         # Called from within DataCollectingParser.
         # Called from within DataCollectingParser.
-        
+
         # Process for handling opaque enums is the same as process for opaque
         # Process for handling opaque enums is the same as process for opaque
         # structs. See handle_struct() for more details.
         # structs. See handle_struct() for more details.
-        
+
         tag = ctypeenum.tag
         tag = ctypeenum.tag
         if tag in self.already_seen_enums:
         if tag in self.already_seen_enums:
             return
             return
-            
+
         if ctypeenum.opaque:
         if ctypeenum.opaque:
             if tag not in self.already_seen_opaque_enums:
             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
                 enum.opaque = True
-                
-                self.already_seen_opaque_enums[tag]=enum
+
+                self.already_seen_opaque_enums[tag] = enum
                 self.enums.append(enum)
                 self.enums.append(enum)
                 self.all.append(enum)
                 self.all.append(enum)
-                self.output_order.append(('enum',enum))
-                
+                self.output_order.append(('enum', enum))
+
         else:
         else:
             if tag in self.already_seen_opaque_enums:
             if tag in self.already_seen_opaque_enums:
                 # Fill in older opaque version
                 # Fill in older opaque version
@@ -235,87 +237,87 @@ class DataCollectingParser(ctypesparser.CtypesParser,
                 enum.opaque = False
                 enum.opaque = False
                 enum.ctype = ctypeenum
                 enum.ctype = ctypeenum
                 enum.src = ctypeenum.src
                 enum.src = ctypeenum.src
-            
+
                 del self.already_seen_opaque_enums[tag]
                 del self.already_seen_opaque_enums[tag]
-            
+
             else:
             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
                 enum.opaque = False
-                
+
                 self.enums.append(enum)
                 self.enums.append(enum)
                 self.all.append(enum)
                 self.all.append(enum)
-                self.output_order.append(('enum',enum))
-            
+                self.output_order.append(('enum', enum))
+
             self.already_seen_enums.add(tag)
             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.constants.append(constant)
                 self.all.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):
     def handle_macro(self, name, params, expr, filename, lineno):
         # Called from within DataCollectingParser
         # Called from within DataCollectingParser
-        src = (filename,lineno)
-        
-        if expr==None:
+        src = (filename, lineno)
+
+        if expr is None:
             expr = ConstantExpressionNode(True)
             expr = ConstantExpressionNode(True)
             constant = ConstantDescription(name, expr, src)
             constant = ConstantDescription(name, expr, src)
             self.constants.append(constant)
             self.constants.append(constant)
             self.all.append(constant)
             self.all.append(constant)
             return
             return
-        
+
         expr.visit(self)
         expr.visit(self)
-        
-        if isinstance(expr,CtypesType):
+
+        if isinstance(expr, CtypesType):
             if params:
             if params:
                 macro = MacroDescription(name, "", src)
                 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.macros.append(macro)
                 self.all.append(macro)
                 self.all.append(macro)
-                self.output_order.append(('macro',macro))
-            
+                self.output_order.append(('macro', macro))
+
             else:
             else:
                 typedef = TypedefDescription(name, expr, src)
                 typedef = TypedefDescription(name, expr, src)
                 self.typedefs.append(typedef)
                 self.typedefs.append(typedef)
                 self.all.append(typedef)
                 self.all.append(typedef)
-                self.output_order.append(('typedef',typedef))
-        
+                self.output_order.append(('typedef', typedef))
+
         else:
         else:
             macro = MacroDescription(name, params, expr, src)
             macro = MacroDescription(name, params, expr, src)
             self.macros.append(macro)
             self.macros.append(macro)
             self.all.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...
         # Macros could possibly contain things like __FILE__, __LINE__, etc...
         # This could be supported, but it would be a lot of work. It would
         # This could be supported, but it would be a lot of work. It would
         # probably also bloat the Preamble considerably.
         # probably also bloat the Preamble considerably.
-        
+
     def handle_error(self, message, filename, lineno):
     def handle_error(self, message, filename, lineno):
         # Called by CParser
         # 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):
     def handle_pp_error(self, message):
         # Called by PreprocessorParser
         # 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):
     def handle_status(self, message):
         # Called by CParser
         # Called by CParser
         status_message(message)
         status_message(message)
-    
+
     def visit_struct(self, struct):
     def visit_struct(self, struct):
         self.handle_struct(struct, struct.src[0], struct.src[1])
         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])
         self.handle_enum(enum, enum.src[0], enum.src[1])
-    
+
     def data(self):
     def data(self):
         return DescriptionCollection(self.constants,
         return DescriptionCollection(self.constants,
                                      self.typedefs,
                                      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'
 __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
 import ctypes
 from lex import TOKEN
 from lex import TOKEN
 
 
@@ -21,15 +28,15 @@ tokens = (
     'PTR_OP', 'INC_OP', 'DEC_OP', 'LEFT_OP', 'RIGHT_OP', 'LE_OP', 'GE_OP',
     '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',
     'EQ_OP', 'NE_OP', 'AND_OP', 'OR_OP', 'MUL_ASSIGN', 'DIV_ASSIGN',
     'MOD_ASSIGN', 'ADD_ASSIGN', 'SUB_ASSIGN', 'LEFT_ASSIGN', 'RIGHT_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',
     'LPAREN', 'NEWLINE',
-    
+
     'PP_DEFINE', 'PP_DEFINE_NAME', 'PP_DEFINE_MACRO_NAME', 'PP_MACRO_PARAM',
     'PP_DEFINE', 'PP_DEFINE_NAME', 'PP_DEFINE_MACRO_NAME', 'PP_MACRO_PARAM',
     'PP_STRINGIFY', 'PP_IDENTIFIER_PASTE', 'PP_END_DEFINE'
     'PP_STRINGIFY', 'PP_IDENTIFIER_PASTE', 'PP_END_DEFINE'
 )
 )
 
 
-states = [('DEFINE',"exclusive")]
+states = [('DEFINE', "exclusive")]
 
 
 subs = {
 subs = {
     'D': '[0-9]',
     'D': '[0-9]',
@@ -41,8 +48,12 @@ subs = {
 }
 }
 # Helper: substitute {foo} with subs[foo] in string (makes regexes more lexy)
 # Helper: substitute {foo} with subs[foo] in string (makes regexes more lexy)
 sub_pattern = re.compile('{([^}]*)}')
 sub_pattern = re.compile('{([^}]*)}')
+
+
 def sub_repl_match(m):
 def sub_repl_match(m):
     return subs[m.groups()[0]]
     return subs[m.groups()[0]]
+
+
 def sub(s):
 def sub(s):
     return sub_pattern.sub(sub_repl_match, s)
     return sub_pattern.sub(sub_repl_match, s)
 
 
@@ -53,7 +64,9 @@ def sub(s):
 # Numbers represented as int and float types.
 # Numbers represented as int and float types.
 # For all other tokens, type is just str representation.
 # For all other tokens, type is just str representation.
 
 
+
 class StringLiteral(str):
 class StringLiteral(str):
+
     def __new__(cls, value):
     def __new__(cls, value):
         assert value[0] == '"' and value[-1] == '"'
         assert value[0] == '"' and value[-1] == '"'
         # Unescaping probably not perfect but close enough.
         # Unescaping probably not perfect but close enough.
@@ -125,6 +138,7 @@ punctuators = {
     r'?': (r'\?', '?')
     r'?': (r'\?', '?')
 }
 }
 
 
+
 def punctuator_regex(punctuators):
 def punctuator_regex(punctuators):
     punctuator_regexes = [v[0] for v in punctuators.values()]
     punctuator_regexes = [v[0] for v in punctuators.values()]
     punctuator_regexes.sort(lambda a, b: -cmp(len(a), len(b)))
     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
 # Process line-number directives from the preprocessor
 # See http://docs.freebsd.org/info/cpp/cpp.info.Output.html
 # See http://docs.freebsd.org/info/cpp/cpp.info.Output.html
 DIRECTIVE = r'\#\s+(\d+)\s+"([^"]+)"[ \d]*\n'
 DIRECTIVE = r'\#\s+(\d+)\s+"([^"]+)"[ \d]*\n'
+
+
 @TOKEN(DIRECTIVE)
 @TOKEN(DIRECTIVE)
 def t_ANY_directive(t):
 def t_ANY_directive(t):
     t.lexer.filename = t.groups[2]
     t.lexer.filename = t.groups[2]
     t.lexer.lineno = int(t.groups[1])
     t.lexer.lineno = int(t.groups[1])
     return None
     return None
 
 
+
 @TOKEN(punctuator_regex(punctuators))
 @TOKEN(punctuator_regex(punctuators))
 def t_ANY_punctuator(t):
 def t_ANY_punctuator(t):
     t.type = punctuators[t.value][1]
     t.type = punctuators[t.value][1]
     return t
     return t
 
 
 IDENTIFIER = sub('{L}({L}|{D})*')
 IDENTIFIER = sub('{L}({L}|{D})*')
+
+
 @TOKEN(IDENTIFIER)
 @TOKEN(IDENTIFIER)
 def t_INITIAL_identifier(t):
 def t_INITIAL_identifier(t):
     t.type = 'IDENTIFIER'
     t.type = 'IDENTIFIER'
     return t
     return t
 
 
+
 @TOKEN(IDENTIFIER)
 @TOKEN(IDENTIFIER)
 def t_DEFINE_identifier(t):
 def t_DEFINE_identifier(t):
     if t.lexer.next_is_define_name:
     if t.lexer.next_is_define_name:
         # This identifier is the name of a macro
         # This identifier is the name of a macro
         # We need to look ahead and see if this macro takes parameters or not.
         # We need to look ahead and see if this macro takes parameters or not.
         if t.lexpos + len(t.value) < t.lexer.lexlen and \
         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'
             t.type = 'PP_DEFINE_MACRO_NAME'
-            
+
             # Look ahead and read macro parameter list
             # Look ahead and read macro parameter list
             lexdata = t.lexer.lexdata
             lexdata = t.lexer.lexdata
             pos = t.lexpos + len(t.value) + 1
             pos = t.lexpos + len(t.value) + 1
             while lexdata[pos] not in '\n)':
             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()]
             paramlist = [x.strip() for x in params.split(",") if x.strip()]
             t.lexer.macro_params = paramlist
             t.lexer.macro_params = paramlist
-                    
+
         else:
         else:
             t.type = 'PP_DEFINE_NAME'
             t.type = 'PP_DEFINE_NAME'
-        
+
         t.lexer.next_is_define_name = False
         t.lexer.next_is_define_name = False
     elif t.value in t.lexer.macro_params:
     elif t.value in t.lexer.macro_params:
         t.type = 'PP_MACRO_PARAM'
         t.type = 'PP_MACRO_PARAM'
@@ -179,19 +199,21 @@ def t_DEFINE_identifier(t):
         t.type = 'IDENTIFIER'
         t.type = 'IDENTIFIER'
     return t
     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)")
                     r"(?P<exp>(?:[Ee][+-]?{D}+)?)(?P<suf>{FS}?)(?!\w)")
+
+
 @TOKEN(FLOAT_LITERAL)
 @TOKEN(FLOAT_LITERAL)
 def t_ANY_float(t):
 def t_ANY_float(t):
     t.type = 'PP_NUMBER'
     t.type = 'PP_NUMBER'
     m = t.lexer.lexmatch
     m = t.lexer.lexmatch
-    
+
     p1 = m.group("p1")
     p1 = m.group("p1")
     dp = m.group("dp")
     dp = m.group("dp")
     p2 = m.group("p2")
     p2 = m.group("p2")
     exp = m.group("exp")
     exp = m.group("exp")
     suf = m.group("suf")
     suf = m.group("suf")
-    
+
     if dp or exp or (suf and suf in ("Ff")):
     if dp or exp or (suf and suf in ("Ff")):
         s = m.group(0)
         s = m.group(0)
         if suf:
         if suf:
@@ -203,58 +225,67 @@ def t_ANY_float(t):
         t.value = "l" + p1
         t.value = "l" + p1
     else:
     else:
         t.value = "i" + p1
         t.value = "i" + p1
-        
+
     return t
     return t
 
 
 INT_LITERAL = sub(r"(?P<p1>(?:0x{H}+)|(?:{D}+))(?P<suf>{IS})")
 INT_LITERAL = sub(r"(?P<p1>(?:0x{H}+)|(?:{D}+))(?P<suf>{IS})")
+
+
 @TOKEN(INT_LITERAL)
 @TOKEN(INT_LITERAL)
 def t_ANY_int(t):
 def t_ANY_int(t):
     t.type = 'PP_NUMBER'
     t.type = 'PP_NUMBER'
     m = t.lexer.lexmatch
     m = t.lexer.lexmatch
-    
+
     if "L" in m.group(3) or "l" in m.group(2):
     if "L" in m.group(3) or "l" in m.group(2):
         prefix = "l"
         prefix = "l"
     else:
     else:
         prefix = "i"
         prefix = "i"
-    
+
     g1 = m.group(2)
     g1 = m.group(2)
     if g1.startswith("0x"):
     if g1.startswith("0x"):
         # Convert base from hexadecimal
         # 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
         # Convert base from octal
-        g1 = str(long(g1,8))
-    
+        g1 = str(long(g1, 8))
+
     t.value = prefix + g1
     t.value = prefix + g1
-        
+
     return t
     return t
 
 
 CHARACTER_CONSTANT = sub(r"L?'(\\.|[^\\'])+'")
 CHARACTER_CONSTANT = sub(r"L?'(\\.|[^\\'])+'")
+
+
 @TOKEN(CHARACTER_CONSTANT)
 @TOKEN(CHARACTER_CONSTANT)
 def t_ANY_character_constant(t):
 def t_ANY_character_constant(t):
     t.type = 'CHARACTER_CONSTANT'
     t.type = 'CHARACTER_CONSTANT'
     return t
     return t
 
 
 STRING_LITERAL = sub(r'L?"(\\.|[^\\"])*"')
 STRING_LITERAL = sub(r'L?"(\\.|[^\\"])*"')
+
+
 @TOKEN(STRING_LITERAL)
 @TOKEN(STRING_LITERAL)
 def t_ANY_string_literal(t):
 def t_ANY_string_literal(t):
     t.type = 'STRING_LITERAL'
     t.type = 'STRING_LITERAL'
     t.value = StringLiteral(t.value)
     t.value = StringLiteral(t.value)
     return t
     return t
 
 
+
 @TOKEN(r'\(')
 @TOKEN(r'\(')
 def t_ANY_lparen(t):
 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'
         t.type = 'LPAREN'
     else:
     else:
         t.type = '('
         t.type = '('
     return t
     return t
 
 
+
 @TOKEN(r'\n')
 @TOKEN(r'\n')
 def t_INITIAL_newline(t):
 def t_INITIAL_newline(t):
     t.lexer.lineno += 1
     t.lexer.lineno += 1
     return None
     return None
 
 
+
 @TOKEN(r'\#define')
 @TOKEN(r'\#define')
 def t_INITIAL_pp_define(t):
 def t_INITIAL_pp_define(t):
     t.type = 'PP_DEFINE'
     t.type = 'PP_DEFINE'
@@ -263,33 +294,37 @@ def t_INITIAL_pp_define(t):
     t.lexer.macro_params = set()
     t.lexer.macro_params = set()
     return t
     return t
 
 
+
 @TOKEN(r'\n')
 @TOKEN(r'\n')
 def t_DEFINE_newline(t):
 def t_DEFINE_newline(t):
     t.type = 'PP_END_DEFINE'
     t.type = 'PP_END_DEFINE'
     t.lexer.begin("INITIAL")
     t.lexer.begin("INITIAL")
     del t.lexer.macro_params
     del t.lexer.macro_params
-    
+
     # Damage control in case the token immediately after the #define failed
     # Damage control in case the token immediately after the #define failed
     # to handle this
     # to handle this
     t.lexer.next_is_define_name = False
     t.lexer.next_is_define_name = False
     return t
     return t
 
 
+
 @TOKEN(r'(\#\#)|(\#)')
 @TOKEN(r'(\#\#)|(\#)')
 def t_DEFINE_pp_param_op(t):
 def t_DEFINE_pp_param_op(t):
-    if t.value=='#':
+    if t.value == '#':
         t.type = 'PP_STRINGIFY'
         t.type = 'PP_STRINGIFY'
     else:
     else:
         t.type = 'PP_IDENTIFIER_PASTE'
         t.type = 'PP_IDENTIFIER_PASTE'
     return t
     return t
 
 
+
 def t_INITIAL_error(t):
 def t_INITIAL_error(t):
     t.type = 'OTHER'
     t.type = 'OTHER'
     return t
     return t
 
 
+
 def t_DEFINE_error(t):
 def t_DEFINE_error(t):
     t.type = 'OTHER'
     t.type = 'OTHER'
     t.value = t.value[0]
     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
     return t
 
 
 t_ANY_ignore = ' \t\v\f\r'
 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'
 __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
 import ctypes
 from lex import TOKEN
 from lex import TOKEN
 import pplexer
 import pplexer
@@ -19,7 +27,9 @@ import pplexer
 # Lexers
 # Lexers
 # --------------------------------------------------------------------------
 # --------------------------------------------------------------------------
 
 
+
 class PreprocessorLexer(lex.Lexer):
 class PreprocessorLexer(lex.Lexer):
+
     def __init__(self):
     def __init__(self):
         lex.Lexer.__init__(self)
         lex.Lexer.__init__(self)
         self.filename = '<input>'
         self.filename = '<input>'
@@ -27,7 +37,7 @@ class PreprocessorLexer(lex.Lexer):
 
 
     def input(self, data, filename=None):
     def input(self, data, filename=None):
         if filename:
         if filename:
-            self.filename = filename 
+            self.filename = filename
         self.lasttoken = None
         self.lasttoken = None
         self.input_stack = []
         self.input_stack = []
 
 
@@ -61,7 +71,9 @@ class PreprocessorLexer(lex.Lexer):
 
 
         return result
         return result
 
 
+
 class TokenListLexer(object):
 class TokenListLexer(object):
+
     def __init__(self, tokens):
     def __init__(self, tokens):
         self.tokens = tokens
         self.tokens = tokens
         self.pos = 0
         self.pos = 0
@@ -74,6 +86,7 @@ class TokenListLexer(object):
         else:
         else:
             return None
             return None
 
 
+
 def symbol_to_token(sym):
 def symbol_to_token(sym):
     if isinstance(sym, yacc.YaccSymbol):
     if isinstance(sym, yacc.YaccSymbol):
         return sym.value
         return sym.value
@@ -82,6 +95,7 @@ def symbol_to_token(sym):
     else:
     else:
         assert False, 'Not a symbol: %r' % sym
         assert False, 'Not a symbol: %r' % sym
 
 
+
 def create_token(type, value, production=None):
 def create_token(type, value, production=None):
     '''Create a token of type and value, at the position where 'production'
     '''Create a token of type and value, at the position where 'production'
     was reduced.  Don`t specify production if the token is built-in'''
     was reduced.  Don`t specify production if the token is built-in'''
@@ -101,8 +115,10 @@ def create_token(type, value, production=None):
 # Grammars
 # Grammars
 # --------------------------------------------------------------------------
 # --------------------------------------------------------------------------
 
 
+
 class PreprocessorParser(object):
 class PreprocessorParser(object):
-    def __init__(self,options,cparser):
+
+    def __init__(self, options, cparser):
         self.defines = ["inline=", "__inline__=", "__extension__=",
         self.defines = ["inline=", "__inline__=", "__extension__=",
                         "_Bool=uint8_t", "__const=const", "__asm__(x)=",
                         "_Bool=uint8_t", "__const=const", "__asm__(x)=",
                         "__asm(x)=", "CTYPESGEN=1"]
                         "__asm(x)=", "CTYPESGEN=1"]
@@ -121,45 +137,45 @@ class PreprocessorParser(object):
                              lextab='lextab',
                              lextab='lextab',
                              outputdir=os.path.dirname(__file__),
                              outputdir=os.path.dirname(__file__),
                              module=pplexer)
                              module=pplexer)
-        
+
         self.options = options
         self.options = options
-        self.cparser = cparser # An instance of CParser
+        self.cparser = cparser  # An instance of CParser
 
 
     def parse(self, filename):
     def parse(self, filename):
         """Parse a file and save its output"""
         """Parse a file and save its output"""
-        
+
         cmd = self.options.cpp
         cmd = self.options.cpp
         if sys.platform == 'darwin':
         if sys.platform == 'darwin':
             cmd += " -U __BLOCKS__"
             cmd += " -U __BLOCKS__"
         cmd += " -U __GNUC__"
         cmd += " -U __GNUC__"
         cmd += " -dD"
         cmd += " -dD"
         for path in self.options.include_search_paths:
         for path in self.options.include_search_paths:
-            cmd += " -I%s" % path 
+            cmd += " -I%s" % path
         for define in self.defines:
         for define in self.defines:
             cmd += ' "-D%s"' % define
             cmd += ' "-D%s"' % define
-        cmd += " " + filename.replace('\\','/')
+        cmd += " " + filename.replace('\\', '/')
 
 
         self.cparser.handle_status(cmd)
         self.cparser.handle_status(cmd)
-        
+
         if sys.platform == 'win32':
         if sys.platform == 'win32':
             cmd = ['sh.exe', '-c', cmd]
             cmd = ['sh.exe', '-c', cmd]
 
 
         pp = subprocess.Popen(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()
         ppout, pperr = pp.communicate()
-        
+
         for line in pperr.split("\n"):
         for line in pperr.split("\n"):
             if line:
             if line:
                 self.cparser.handle_pp_error(line)
                 self.cparser.handle_pp_error(line)
-        
+
         # We separate lines that are #defines and lines that are source code
         # We separate lines that are #defines and lines that are source code
         # We put all the source lines first, then all the #define lines.
         # We put all the source lines first, then all the #define lines.
-        
-        source_lines= []
+
+        source_lines = []
         define_lines = []
         define_lines = []
-        
+
         for line in ppout.split("\n"):
         for line in ppout.split("\n"):
             line = line.rstrip('\r')
             line = line.rstrip('\r')
             line = line + "\n"
             line = line + "\n"
@@ -167,35 +183,35 @@ class PreprocessorParser(object):
                 # Line number information has to go with both groups
                 # Line number information has to go with both groups
                 source_lines.append(line)
                 source_lines.append(line)
                 define_lines.append(line)
                 define_lines.append(line)
-            
+
             elif line.startswith("#define"):
             elif line.startswith("#define"):
                 source_lines.append("\n")
                 source_lines.append("\n")
                 define_lines.append(line)
                 define_lines.append(line)
-            
+
             elif line.startswith("#"):
             elif line.startswith("#"):
                 # It's a directive, but not a #define. Remove it
                 # It's a directive, but not a #define. Remove it
                 source_lines.append("\n")
                 source_lines.append("\n")
                 define_lines.append("\n")
                 define_lines.append("\n")
-            
+
             else:
             else:
                 source_lines.append(line)
                 source_lines.append(line)
                 define_lines.append("\n")
                 define_lines.append("\n")
-        
+
         text = "".join(source_lines + define_lines)
         text = "".join(source_lines + define_lines)
-        
+
         if self.options.save_preprocessed_headers:
         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:
             try:
                 f = file(self.options.save_preprocessed_headers, "w")
                 f = file(self.options.save_preprocessed_headers, "w")
                 f.write(text)
                 f.write(text)
                 f.close()
                 f.close()
             except IOError:
             except IOError:
                 self.cparser.handle_error("Couldn't save headers.")
                 self.cparser.handle_error("Couldn't save headers.")
-        
+
         self.lexer.input(text)
         self.lexer.input(text)
         self.output = []
         self.output = []
-        
+
         while True:
         while True:
             token = self.lexer.token()
             token = self.lexer.token()
             if token is not None:
             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
 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.
 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 *
 from ctypes import *
 
 
 _int_types = (c_int16, c_int32)
 _int_types = (c_int16, c_int32)
@@ -13,12 +15,14 @@ for t in _int_types:
 del t
 del t
 del _int_types
 del _int_types
 
 
+
 class c_void(Structure):
 class c_void(Structure):
     # c_void_p is a buggy return type, converting to int, so
     # c_void_p is a buggy return type, converting to int, so
     # POINTER(None) == c_void_p is actually written as
     # POINTER(None) == c_void_p is actually written as
     # POINTER(c_void), so it can be treated as a real pointer.
     # POINTER(c_void), so it can be treated as a real pointer.
     _fields_ = [('dummy', c_int)]
     _fields_ = [('dummy', c_int)]
 
 
+
 def POINTER(obj):
 def POINTER(obj):
     p = ctypes.POINTER(obj)
     p = ctypes.POINTER(obj)
 
 
@@ -34,7 +38,9 @@ def POINTER(obj):
 
 
     return p
     return p
 
 
+
 class UserString:
 class UserString:
+
     def __init__(self, seq):
     def __init__(self, seq):
         if isinstance(seq, basestring):
         if isinstance(seq, basestring):
             self.data = seq
             self.data = seq
@@ -42,12 +48,19 @@ class UserString:
             self.data = seq.data[:]
             self.data = seq.data[:]
         else:
         else:
             self.data = str(seq)
             self.data = str(seq)
+
     def __str__(self): return str(self.data)
     def __str__(self): return str(self.data)
+
     def __repr__(self): return repr(self.data)
     def __repr__(self): return repr(self.data)
+
     def __int__(self): return int(self.data)
     def __int__(self): return int(self.data)
+
     def __long__(self): return long(self.data)
     def __long__(self): return long(self.data)
+
     def __float__(self): return float(self.data)
     def __float__(self): return float(self.data)
+
     def __complex__(self): return complex(self.data)
     def __complex__(self): return complex(self.data)
+
     def __hash__(self): return hash(self.data)
     def __hash__(self): return hash(self.data)
 
 
     def __cmp__(self, string):
     def __cmp__(self, string):
@@ -55,13 +68,17 @@ class UserString:
             return cmp(self.data, string.data)
             return cmp(self.data, string.data)
         else:
         else:
             return cmp(self.data, string)
             return cmp(self.data, string)
+
     def __contains__(self, char):
     def __contains__(self, char):
         return char in self.data
         return char in self.data
 
 
     def __len__(self): return len(self.data)
     def __len__(self): return len(self.data)
+
     def __getitem__(self, index): return self.__class__(self.data[index])
     def __getitem__(self, index): return self.__class__(self.data[index])
+
     def __getslice__(self, start, end):
     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])
         return self.__class__(self.data[start:end])
 
 
     def __add__(self, other):
     def __add__(self, other):
@@ -71,24 +88,30 @@ class UserString:
             return self.__class__(self.data + other)
             return self.__class__(self.data + other)
         else:
         else:
             return self.__class__(self.data + str(other))
             return self.__class__(self.data + str(other))
+
     def __radd__(self, other):
     def __radd__(self, other):
         if isinstance(other, basestring):
         if isinstance(other, basestring):
             return self.__class__(other + self.data)
             return self.__class__(other + self.data)
         else:
         else:
             return self.__class__(str(other) + self.data)
             return self.__class__(str(other) + self.data)
+
     def __mul__(self, n):
     def __mul__(self, n):
-        return self.__class__(self.data*n)
+        return self.__class__(self.data * n)
     __rmul__ = __mul__
     __rmul__ = __mul__
+
     def __mod__(self, args):
     def __mod__(self, args):
         return self.__class__(self.data % args)
         return self.__class__(self.data % args)
 
 
     # the following methods are defined in alphabetical order:
     # the following methods are defined in alphabetical order:
     def capitalize(self): return self.__class__(self.data.capitalize())
     def capitalize(self): return self.__class__(self.data.capitalize())
+
     def center(self, width, *args):
     def center(self, width, *args):
         return self.__class__(self.data.center(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)
         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 encoding:
             if errors:
             if errors:
                 return self.__class__(self.data.decode(encoding, errors))
                 return self.__class__(self.data.decode(encoding, errors))
@@ -96,7 +119,8 @@ class UserString:
                 return self.__class__(self.data.decode(encoding))
                 return self.__class__(self.data.decode(encoding))
         else:
         else:
             return self.__class__(self.data.decode())
             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 encoding:
             if errors:
             if errors:
                 return self.__class__(self.data.encode(encoding, errors))
                 return self.__class__(self.data.encode(encoding, errors))
@@ -104,56 +128,91 @@ class UserString:
                 return self.__class__(self.data.encode(encoding))
                 return self.__class__(self.data.encode(encoding))
         else:
         else:
             return self.__class__(self.data.encode())
             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)
         return self.data.endswith(suffix, start, end)
+
     def expandtabs(self, tabsize=8):
     def expandtabs(self, tabsize=8):
         return self.__class__(self.data.expandtabs(tabsize))
         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)
         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)
         return self.data.index(sub, start, end)
+
     def isalpha(self): return self.data.isalpha()
     def isalpha(self): return self.data.isalpha()
+
     def isalnum(self): return self.data.isalnum()
     def isalnum(self): return self.data.isalnum()
+
     def isdecimal(self): return self.data.isdecimal()
     def isdecimal(self): return self.data.isdecimal()
+
     def isdigit(self): return self.data.isdigit()
     def isdigit(self): return self.data.isdigit()
+
     def islower(self): return self.data.islower()
     def islower(self): return self.data.islower()
+
     def isnumeric(self): return self.data.isnumeric()
     def isnumeric(self): return self.data.isnumeric()
+
     def isspace(self): return self.data.isspace()
     def isspace(self): return self.data.isspace()
+
     def istitle(self): return self.data.istitle()
     def istitle(self): return self.data.istitle()
+
     def isupper(self): return self.data.isupper()
     def isupper(self): return self.data.isupper()
+
     def join(self, seq): return self.data.join(seq)
     def join(self, seq): return self.data.join(seq)
+
     def ljust(self, width, *args):
     def ljust(self, width, *args):
         return self.__class__(self.data.ljust(width, *args))
         return self.__class__(self.data.ljust(width, *args))
+
     def lower(self): return self.__class__(self.data.lower())
     def lower(self): return self.__class__(self.data.lower())
+
     def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
     def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
+
     def partition(self, sep):
     def partition(self, sep):
         return self.data.partition(sep)
         return self.data.partition(sep)
+
     def replace(self, old, new, maxsplit=-1):
     def replace(self, old, new, maxsplit=-1):
         return self.__class__(self.data.replace(old, new, maxsplit))
         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)
         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)
         return self.data.rindex(sub, start, end)
+
     def rjust(self, width, *args):
     def rjust(self, width, *args):
         return self.__class__(self.data.rjust(width, *args))
         return self.__class__(self.data.rjust(width, *args))
+
     def rpartition(self, sep):
     def rpartition(self, sep):
         return self.data.rpartition(sep)
         return self.data.rpartition(sep)
+
     def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars))
     def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars))
+
     def split(self, sep=None, maxsplit=-1):
     def split(self, sep=None, maxsplit=-1):
         return self.data.split(sep, maxsplit)
         return self.data.split(sep, maxsplit)
+
     def rsplit(self, sep=None, maxsplit=-1):
     def rsplit(self, sep=None, maxsplit=-1):
         return self.data.rsplit(sep, maxsplit)
         return self.data.rsplit(sep, maxsplit)
+
     def splitlines(self, keepends=0): return self.data.splitlines(keepends)
     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)
         return self.data.startswith(prefix, start, end)
+
     def strip(self, chars=None): return self.__class__(self.data.strip(chars))
     def strip(self, chars=None): return self.__class__(self.data.strip(chars))
+
     def swapcase(self): return self.__class__(self.data.swapcase())
     def swapcase(self): return self.__class__(self.data.swapcase())
+
     def title(self): return self.__class__(self.data.title())
     def title(self): return self.__class__(self.data.title())
+
     def translate(self, *args):
     def translate(self, *args):
         return self.__class__(self.data.translate(*args))
         return self.__class__(self.data.translate(*args))
+
     def upper(self): return self.__class__(self.data.upper())
     def upper(self): return self.__class__(self.data.upper())
+
     def zfill(self, width): return self.__class__(self.data.zfill(width))
     def zfill(self, width): return self.__class__(self.data.zfill(width))
 
 
+
 class MutableString(UserString):
 class MutableString(UserString):
     """mutable string objects
     """mutable string objects
 
 
@@ -169,33 +228,45 @@ class MutableString(UserString):
     errors that would be very hard to track down.
     errors that would be very hard to track down.
 
 
     A faster and better solution is to rewrite your program using lists."""
     A faster and better solution is to rewrite your program using lists."""
+
     def __init__(self, string=""):
     def __init__(self, string=""):
         self.data = string
         self.data = string
+
     def __hash__(self):
     def __hash__(self):
-        raise TypeError, "unhashable type (it is mutable)"
+        raise TypeError("unhashable type (it is mutable)")
+
     def __setitem__(self, index, sub):
     def __setitem__(self, index, sub):
         if index < 0:
         if index < 0:
             index += len(self.data)
             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):
     def __delitem__(self, index):
         if index < 0:
         if index < 0:
             index += len(self.data)
             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):
     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):
         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):
         elif isinstance(sub, basestring):
-            self.data = self.data[:start]+sub+self.data[end:]
+            self.data = self.data[:start] + sub + self.data[end:]
         else:
         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):
     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:]
         self.data = self.data[:start] + self.data[end:]
+
     def immutable(self):
     def immutable(self):
         return UserString(self.data)
         return UserString(self.data)
+
     def __iadd__(self, other):
     def __iadd__(self, other):
         if isinstance(other, UserString):
         if isinstance(other, UserString):
             self.data += other.data
             self.data += other.data
@@ -204,10 +275,12 @@ class MutableString(UserString):
         else:
         else:
             self.data += str(other)
             self.data += str(other)
         return self
         return self
+
     def __imul__(self, n):
     def __imul__(self, n):
         self.data *= n
         self.data *= n
         return self
         return self
 
 
+
 class String(MutableString, Union):
 class String(MutableString, Union):
 
 
     _fields_ = [('raw', POINTER(c_char)),
     _fields_ = [('raw', POINTER(c_char)),
@@ -221,7 +294,7 @@ class String(MutableString, Union):
 
 
     def __len__(self):
     def __len__(self):
         return self.data and len(self.data) or 0
         return self.data and len(self.data) or 0
-    
+
     def from_param(cls, obj):
     def from_param(cls, obj):
         # Convert None or 0
         # Convert None or 0
         if obj is None or obj == 0:
         if obj is None or obj == 0:
@@ -234,15 +307,15 @@ class String(MutableString, Union):
         # Convert from str
         # Convert from str
         elif isinstance(obj, str):
         elif isinstance(obj, str):
             return cls(obj)
             return cls(obj)
-        
+
         # Convert from c_char_p
         # Convert from c_char_p
         elif isinstance(obj, c_char_p):
         elif isinstance(obj, c_char_p):
             return obj
             return obj
-        
+
         # Convert from POINTER(c_char)
         # Convert from POINTER(c_char)
         elif isinstance(obj, POINTER(c_char)):
         elif isinstance(obj, POINTER(c_char)):
             return obj
             return obj
-        
+
         # Convert from raw pointer
         # Convert from raw pointer
         elif isinstance(obj, int):
         elif isinstance(obj, int):
             return cls(cast(obj, POINTER(c_char)))
             return cls(cast(obj, POINTER(c_char)))
@@ -252,6 +325,7 @@ class String(MutableString, Union):
             return String.from_param(obj._as_parameter_)
             return String.from_param(obj._as_parameter_)
     from_param = classmethod(from_param)
     from_param = classmethod(from_param)
 
 
+
 def ReturnString(obj):
 def ReturnString(obj):
     return String.from_param(obj)
     return String.from_param(obj)
 
 
@@ -262,29 +336,35 @@ def ReturnString(obj):
 #
 #
 # Non-primitive return values wrapped with UNCHECKED won't be
 # Non-primitive return values wrapped with UNCHECKED won't be
 # typechecked, and will be converted to c_void_p.
 # typechecked, and will be converted to c_void_p.
+
+
 def UNCHECKED(type):
 def UNCHECKED(type):
     if (hasattr(type, "_type_") and isinstance(type._type_, str)
     if (hasattr(type, "_type_") and isinstance(type._type_, str)
-        and type._type_ != "P"):
+            and type._type_ != "P"):
         return type
         return type
     else:
     else:
         return c_void_p
         return c_void_p
 
 
 # ctypes doesn't have direct support for variadic functions, so we have to write
 # ctypes doesn't have direct support for variadic functions, so we have to write
 # our own wrapper class
 # our own wrapper class
+
+
 class _variadic_function(object):
 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):
     def _as_parameter_(self):
         # So we can pass this variadic function as a function pointer
         # So we can pass this variadic function as a function pointer
         return self.func
         return self.func
-    def __call__(self,*args):
-        fixed_args=[]
-        i=0
+
+    def __call__(self, *args):
+        fixed_args = []
+        i = 0
         for argtype in self.argtypes:
         for argtype in self.argtypes:
             # Typecheck what we can
             # Typecheck what we can
             fixed_args.append(argtype.from_param(args[i]))
             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
 #!/usr/bin/env python
 
 
-import os, sys, time
+import os
+import sys
+import time
 from ctypesgencore.descriptions import *
 from ctypesgencore.descriptions import *
 from ctypesgencore.ctypedescs import *
 from ctypesgencore.ctypedescs import *
 from ctypesgencore.messages 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:
 class WrapperPrinter:
-    def __init__(self,outpath,options,data):
+
+    def __init__(self, outpath, options, data):
         status_message("Writing to %s." % outpath)
         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 \
         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.options.strip_build_path += os.path.sep
-        
+
         self.print_header()
         self.print_header()
         print >>self.file
         print >>self.file
-        
+
         self.print_preamble()
         self.print_preamble()
         print >>self.file
         print >>self.file
-        
+
         self.print_loader()
         self.print_loader()
         print >>self.file
         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 = {
         method_table = {
             'function': self.print_function,
             'function': self.print_function,
             'macro': self.print_macro,
             'macro': self.print_macro,
@@ -45,89 +50,89 @@ class WrapperPrinter:
             'enum': self.print_enum,
             'enum': self.print_enum,
             'constant': self.print_constant
             'constant': self.print_constant
         }
         }
-        
-        for kind,desc in data.output_order:
+
+        for kind, desc in data.output_order:
             if desc.included:
             if desc.included:
                 method_table[kind](desc)
                 method_table[kind](desc)
                 print >>self.file
                 print >>self.file
-        
-        self.print_group(self.options.inserted_files,"inserted files",
+
+        self.print_group(self.options.inserted_files, "inserted files",
                          self.insert_file)
                          self.insert_file)
-    
-    def print_group(self,list,name,function):
+
+    def print_group(self, list, name, function):
         if list:
         if list:
-            print >>self.file,"# Begin %s" % name
+            print >>self.file, "# Begin %s" % name
             print >>self.file
             print >>self.file
             for obj in list:
             for obj in list:
                 function(obj)
                 function(obj)
             print >>self.file
             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:
         else:
-            print >>self.file,"# No %s" % name
+            print >>self.file, "# No %s" % name
         print >>self.file
         print >>self.file
-    
-    def srcinfo(self,src):
-        if src==None:
+
+    def srcinfo(self, src):
+        if src is None:
             print >>self.file
             print >>self.file
         else:
         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
                 print >>self.file, "# %s" % filename
             else:
             else:
                 if self.options.strip_build_path and \
                 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):]
                     filename = filename[len(self.options.strip_build_path):]
                 print >>self.file, "# %s: %s" % (filename, lineno)
                 print >>self.file, "# %s: %s" % (filename, lineno)
-    
+
     def template_subs(self):
     def template_subs(self):
-        template_subs={
+        template_subs = {
             'date': time.ctime(),
             'date': time.ctime(),
             'argv': ' '.join([x for x in sys.argv if not x.startswith("--strip-build-path")]),
             'argv': ' '.join([x for x in sys.argv if not x.startswith("--strip-build-path")]),
             'name': os.path.basename(self.options.headers[0])
             '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:
             else:
-                template_subs[opt]=repr(value)
-        
+                template_subs[opt] = repr(value)
+
         return template_subs
         return template_subs
-    
+
     def print_header(self):
     def print_header(self):
         template_file = None
         template_file = None
-        
+
         if self.options.header_template:
         if self.options.header_template:
             path = self.options.header_template
             path = self.options.header_template
             try:
             try:
-                template_file = file(path,"r")
+                template_file = file(path, "r")
             except IOError:
             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:
         if not template_file:
             path = path_to_local_file("defaultheader.py")
             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)
         self.file.write(template_file.read() % template_subs)
-        
+
         template_file.close()
         template_file.close()
-    
+
     def print_preamble(self):
     def print_preamble(self):
         path = path_to_local_file("preamble.py")
         path = path_to_local_file("preamble.py")
-        
+
         print >>self.file, "# Begin preamble"
         print >>self.file, "# Begin preamble"
         print >>self.file
         print >>self.file
-        preamble_file=file(path,"r")
+        preamble_file = file(path, "r")
         self.file.write(preamble_file.read())
         self.file.write(preamble_file.read())
         preamble_file.close()
         preamble_file.close()
         print >>self.file
         print >>self.file
         print >>self.file, "# End preamble"
         print >>self.file, "# End preamble"
-    
+
     def print_loader(self):
     def print_loader(self):
         print >>self.file, "_libs = {}"
         print >>self.file, "_libs = {}"
         print >>self.file, "_libdirs = %s" % self.options.compile_libdirs
         print >>self.file, "_libdirs = %s" % self.options.compile_libdirs
@@ -135,92 +140,95 @@ class WrapperPrinter:
         print >>self.file, "# Begin loader"
         print >>self.file, "# Begin loader"
         print >>self.file
         print >>self.file
         path = path_to_local_file("libraryloader.py",
         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())
         self.file.write(loader_file.read())
         loader_file.close()
         loader_file.close()
         print >>self.file
         print >>self.file
         print >>self.file, "# End loader"
         print >>self.file, "# End loader"
         print >>self.file
         print >>self.file
         print >>self.file, "add_library_search_dirs([%s])" % \
         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
         print >>self.file, 'from %s import *' % name
-    
-    def print_constant(self,constant):
+
+    def print_constant(self, constant):
         print >>self.file, '%s = %s' % \
         print >>self.file, '%s = %s' % \
-            (constant.name,constant.value.py_string(False)),
+            (constant.name, constant.value.py_string(False)),
         self.srcinfo(constant.src)
         self.srcinfo(constant.src)
-    
-    def print_typedef(self,typedef):
+
+    def print_typedef(self, typedef):
         print >>self.file, '%s = %s' % \
         print >>self.file, '%s = %s' % \
-            (typedef.name,typedef.ctype.py_string()),
+            (typedef.name, typedef.ctype.py_string()),
         self.srcinfo(typedef.src)
         self.srcinfo(typedef.src)
-    
+
     def print_struct(self, struct):
     def print_struct(self, struct):
         self.srcinfo(struct.src)
         self.srcinfo(struct.src)
         base = {'union': 'Union', 'struct': 'Structure'}[struct.variety]
         base = {'union': 'Union', 'struct': 'Structure'}[struct.variety]
         print >>self.file, 'class %s_%s(%s):' % \
         print >>self.file, 'class %s_%s(%s):' % \
             (struct.variety, struct.tag, base)
             (struct.variety, struct.tag, base)
         print >>self.file, '    pass'
         print >>self.file, '    pass'
-    
+
     def print_struct_members(self, struct):
     def print_struct_members(self, struct):
-        if struct.opaque: return
+        if struct.opaque:
+            return
         print >>self.file, '%s_%s.__slots__ = [' % (struct.variety, struct.tag)
         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, "    '%s'," % name
         print >>self.file, ']'
         print >>self.file, ']'
         print >>self.file, '%s_%s._fields_ = [' % (struct.variety, struct.tag)
         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)," % \
                 print >>self.file, "    ('%s', %s, %s)," % \
                     (name, ctype.py_string(), ctype.bitfield.py_string(False))
                     (name, ctype.py_string(), ctype.bitfield.py_string(False))
             else:
             else:
                 print >>self.file, "    ('%s', %s)," % (name, ctype.py_string())
                 print >>self.file, "    ('%s', %s)," % (name, ctype.py_string())
         print >>self.file, ']'
         print >>self.file, ']'
-    
-    def print_enum(self,enum):
+
+    def print_enum(self, enum):
         print >>self.file, 'enum_%s = c_int' % enum.tag,
         print >>self.file, 'enum_%s = c_int' % enum.tag,
         self.srcinfo(enum.src)
         self.srcinfo(enum.src)
         # Values of enumerator are output as constants.
         # Values of enumerator are output as constants.
-    
+
     def print_function(self, function):
     def print_function(self, function):
         if function.variadic:
         if function.variadic:
             self.print_variadic_function(function)
             self.print_variadic_function(function)
         else:
         else:
             self.print_fixed_function(function)
             self.print_fixed_function(function)
-    
+
     def print_fixed_function(self, function):
     def print_fixed_function(self, function):
         self.srcinfo(function.src)
         self.srcinfo(function.src)
         if function.source_library:
         if function.source_library:
             print >>self.file, "if hasattr(_libs[%r], %r):" % \
             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" % \
             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" % \
             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]))
                 ', '.join([a.py_string() for a in function.argtypes]))
         else:
         else:
             print >>self.file, "for _lib in _libs.values():"
             print >>self.file, "for _lib in _libs.values():"
             print >>self.file, "    if hasattr(_lib, %r):" % function.c_name()
             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"
             print >>self.file, "        break"
-    
-    def print_variadic_function(self,function):
+
+    def print_variadic_function(self, function):
         self.srcinfo(function.src)
         self.srcinfo(function.src)
         if function.source_library:
         if function.source_library:
             print >>self.file, "if hasattr(_libs[%r], %r):" % \
             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" % \
             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, "    _restype = %s" % function.restype.py_string()
             print >>self.file, "    _argtypes = [%s]" % \
             print >>self.file, "    _argtypes = [%s]" % \
                 ', '.join([a.py_string() for a in function.argtypes])
                 ', '.join([a.py_string() for a in function.argtypes])
@@ -237,7 +245,6 @@ class WrapperPrinter:
             print >>self.file, "        %s = _variadic_function(_func,_restype,_argtypes)" % \
             print >>self.file, "        %s = _variadic_function(_func,_restype,_argtypes)" % \
                 function.py_name()
                 function.py_name()
 
 
-    
     def print_variable(self, variable):
     def print_variable(self, variable):
         self.srcinfo(variable.src)
         self.srcinfo(variable.src)
         if variable.source_library:
         if variable.source_library:
@@ -259,40 +266,40 @@ class WrapperPrinter:
             print >>self.file, "        break"
             print >>self.file, "        break"
             print >>self.file, '    except:'
             print >>self.file, '    except:'
             print >>self.file, '        pass'
             print >>self.file, '        pass'
-    
+
     def print_macro(self, macro):
     def print_macro(self, macro):
         if macro.params:
         if macro.params:
             self.print_func_macro(macro)
             self.print_func_macro(macro)
         else:
         else:
             self.print_simple_macro(macro)
             self.print_simple_macro(macro)
-    
+
     def print_simple_macro(self, macro):
     def print_simple_macro(self, macro):
         # The macro translator makes heroic efforts but it occasionally fails.
         # The macro translator makes heroic efforts but it occasionally fails.
         # We want to contain the failures as much as possible.
         # We want to contain the failures as much as possible.
         # Hence the try statement.
         # Hence the try statement.
         self.srcinfo(macro.src)
         self.srcinfo(macro.src)
         print >>self.file, "try:"
         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, "except:"
         print >>self.file, "    pass"
         print >>self.file, "    pass"
-    
+
     def print_func_macro(self, macro):
     def print_func_macro(self, macro):
         self.srcinfo(macro.src)
         self.srcinfo(macro.src)
         print >>self.file, "def %s(%s):" % \
         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)
         print >>self.file, "    return %s" % macro.expr.py_string(True)
-    
-    def insert_file(self,filename):
+
+    def insert_file(self, filename):
         try:
         try:
-            inserted_file = file(filename,"r")
+            inserted_file = file(filename, "r")
         except IOError:
         except IOError:
             error_message("Cannot open file \"%s\". Skipped it." % filename,
             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
         print >>self.file
         self.file.write(inserted_file.read())
         self.file.write(inserted_file.read())
         print >>self.file
         print >>self.file
-        print >>self.file,"# End \"%s\"" % filename
-              
+        print >>self.file, "# End \"%s\"" % filename
+
         inserted_file.close()
         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.
 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"]
 __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.ctypedescs import *
 from ctypesgencore.messages import *
 from ctypesgencore.messages import *
 
 
+
 def find_dependencies(data, opts):
 def find_dependencies(data, opts):
     """Visit each description in `data` and figure out which other descriptions
     """Visit each description in `data` and figure out which other descriptions
 it depends on, putting the results in desc.requirements. Also find errors in
 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
 ctypedecls or expressions attached to the description and transfer them to the
 description."""
 description."""
-    
+
     struct_names = {}
     struct_names = {}
     enum_names = {}
     enum_names = {}
     typedef_names = {}
     typedef_names = {}
     ident_names = {}
     ident_names = {}
-    
+
     # Start the lookup tables with names from imported modules
     # Start the lookup tables with names from imported modules
-    
+
     for name in opts.other_known_names:
     for name in opts.other_known_names:
         typedef_names[name] = None
         typedef_names[name] = None
         ident_names[name] = None
         ident_names[name] = None
         if name.startswith("struct_") or name.startswith("enum_"):
         if name.startswith("struct_") or name.startswith("enum_"):
             variety = name.split("_")[0]
             variety = name.split("_")[0]
             tag = "_".join(name.split("_")[1:])
             tag = "_".join(name.split("_")[1:])
-            struct_names[(variety,tag)] = None
+            struct_names[(variety, tag)] = None
         if name.startswith("enum_"):
         if name.startswith("enum_"):
             enum_names[name] = None
             enum_names[name] = None
-    
+
     def depend(desc, nametable, name):
     def depend(desc, nametable, name):
         """Try to add `name` as a requirement for `desc`, looking `name` up in
         """Try to add `name` as a requirement for `desc`, looking `name` up in
 `nametable`. Returns True if found."""
 `nametable`. Returns True if found."""
 
 
         if name in nametable:
         if name in nametable:
             requirement = nametable[name]
             requirement = nametable[name]
-            if requirement: desc.add_requirements([requirement])
+            if requirement:
+                desc.add_requirements([requirement])
             return True
             return True
         else:
         else:
             return False
             return False
-    
+
     def find_dependencies_for(desc, kind):
     def find_dependencies_for(desc, kind):
         """Find all the descriptions that `desc` depends on and add them as
         """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."""
 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 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:
         for root in roots:
             s, e, t, errs, i = visit_type_and_collect_info(root)
             s, e, t, errs, i = visit_type_and_collect_info(root)
             cstructs.extend(s)
             cstructs.extend(s)
@@ -68,42 +79,42 @@ convert unlocateable descriptions into error messages."""
             ctypedefs.extend(t)
             ctypedefs.extend(t)
             errors.extend(errs)
             errors.extend(errs)
             identifiers.extend(i)
             identifiers.extend(i)
-        
+
         unresolvables = []
         unresolvables = []
-        
+
         for cstruct in cstructs:
         for cstruct in cstructs:
             if kind == "struct" and desc.variety == cstruct.variety and \
             if kind == "struct" and desc.variety == cstruct.variety and \
-                desc.tag == cstruct.tag:
+                    desc.tag == cstruct.tag:
                 continue
                 continue
             if not depend(desc, struct_names, (cstruct.variety, cstruct.tag)):
             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:
         for cenum in cenums:
             if kind == "enum" and desc.tag == cenum.tag:
             if kind == "enum" and desc.tag == cenum.tag:
                 continue
                 continue
             if not depend(desc, enum_names, cenum.tag):
             if not depend(desc, enum_names, cenum.tag):
                 unresolvables.append("enum \"%s\"" % cenum.tag)
                 unresolvables.append("enum \"%s\"" % cenum.tag)
-        
+
         for ctypedef in ctypedefs:
         for ctypedef in ctypedefs:
             if not depend(desc, typedef_names, ctypedef):
             if not depend(desc, typedef_names, ctypedef):
                 unresolvables.append("typedef \"%s\"" % ctypedef)
                 unresolvables.append("typedef \"%s\"" % ctypedef)
-        
+
         for ident in identifiers:
         for ident in identifiers:
             if isinstance(desc, MacroDescription) and \
             if isinstance(desc, MacroDescription) and \
-                desc.params and ident in desc.params:
+                    desc.params and ident in desc.params:
                 continue
                 continue
             if not depend(desc, ident_names, ident):
             if not depend(desc, ident_names, ident):
                 unresolvables.append("identifier \"%s\"" % ident)
                 unresolvables.append("identifier \"%s\"" % ident)
-        
+
         for u in unresolvables:
         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:
         for err, cls in errors:
             err += " %s will not be output" % desc.casual_name()
             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):
     def add_to_lookup_table(desc, kind):
         """Add `desc` to the lookup table so that other descriptions that use
         """Add `desc` to the lookup table so that other descriptions that use
 it can find it."""
 it can find it."""
@@ -125,13 +136,13 @@ it can find it."""
     # no other type of description can look ahead like that.
     # no other type of description can look ahead like that.
 
 
     for kind, desc in data.output_order:
     for kind, desc in data.output_order:
-        if kind!="macro":
+        if kind != "macro":
             find_dependencies_for(desc, kind)
             find_dependencies_for(desc, kind)
             add_to_lookup_table(desc, kind)
             add_to_lookup_table(desc, kind)
 
 
     for kind, desc in data.output_order:
     for kind, desc in data.output_order:
-        if kind=="macro":
+        if kind == "macro":
             add_to_lookup_table(desc, kind)
             add_to_lookup_table(desc, kind)
     for kind, desc in data.output_order:
     for kind, desc in data.output_order:
-        if kind=="macro":
+        if kind == "macro":
             find_dependencies_for(desc, kind)
             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.
 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.descriptions import *
 from ctypesgencore.messages import *
 from ctypesgencore.messages import *
 import ctypesgencore.libraryloader
 import ctypesgencore.libraryloader
 
 
 # Processor functions
 # Processor functions
 
 
-def automatically_typedef_structs(data,options):
+
+def automatically_typedef_structs(data, options):
     """automatically_typedef_structs() aliases "struct_<tag>" to "<tag>" for
     """automatically_typedef_structs() aliases "struct_<tag>" to "<tag>" for
     every struct and union."""
     every struct and union."""
     # XXX Check if it has already been aliased in the C code.
     # XXX Check if it has already been aliased in the C code.
-    
+
     for struct in data.structs:
     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]))
             typedef.add_requirements(set([struct]))
-            
+
             data.typedefs.append(typedef)
             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))
             data.output_order.append(("typedef", typedef))
 
 
+
 def remove_NULL(data, options):
 def remove_NULL(data, options):
     """remove_NULL() removes any NULL definitions from the C headers because
     """remove_NULL() removes any NULL definitions from the C headers because
 ctypesgen supplies its own NULL definition."""
 ctypesgen supplies its own NULL definition."""
-    
+
     for macro in data.macros:
     for macro in data.macros:
-        if macro.name=="NULL":
+        if macro.name == "NULL":
             macro.include_rule = "never"
             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
     """remove_descriptions_in_system_headers() removes descriptions if they came
     from files outside of the header files specified from the command line."""
     from files outside of the header files specified from the command line."""
-    
+
     known_headers = [os.path.basename(x) for x in opts.headers]
     known_headers = [os.path.basename(x) for x in opts.headers]
-    
+
     for description in data.all:
     for description in data.all:
-        if description.src!=None:
+        if description.src is not None:
             if description.src[0] == "<command line>":
             if description.src[0] == "<command line>":
                 description.include_rule = "if_needed"
                 description.include_rule = "if_needed"
             elif description.src[0] == "<built-in>":
             elif description.src[0] == "<built-in>":
                 if not opts.builtin_symbols:
                 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:
             elif os.path.basename(description.src[0]) not in known_headers:
                 if not opts.all_headers:
                 if not opts.all_headers:
                     # If something else requires this, include it even though
                     # If something else requires this, include it even though
                     # it is in a system header file.
                     # 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."""
     """remove_macros() removes macros if --no-macros is set."""
     if not opts.include_macros:
     if not opts.include_macros:
         for macro in data.macros:
         for macro in data.macros:
             macro.include_rule = "never"
             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
     """filter_by_regexes_exclude() uses regular expressions specified by options
     dictionary to filter symbols."""
     dictionary to filter symbols."""
     if opts.exclude_symbols:
     if opts.exclude_symbols:
-        expr=re.compile(opts.exclude_symbols)
+        expr = re.compile(opts.exclude_symbols)
         for object in data.all:
         for object in data.all:
             if expr.match(object.py_name()):
             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
     """filter_by_regexes_include() uses regular expressions specified by options
     dictionary to re-include symbols previously rejected by other operations."""
     dictionary to re-include symbols previously rejected by other operations."""
     if opts.include_symbols:
     if opts.include_symbols:
-        expr=re.compile(opts.include_symbols)
+        expr = re.compile(opts.include_symbols)
         for object in data.all:
         for object in data.all:
-            if object.include_rule!="never":
+            if object.include_rule != "never":
                 if expr.match(object.py_name()):
                 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
     """If any descriptions from the C code would overwrite Python builtins or
     other important names, fix_conflicting_names() adds underscores to resolve
     other important names, fix_conflicting_names() adds underscores to resolve
     the name conflict."""
     the name conflict."""
-    
+
     # This is the order of priority for names
     # This is the order of priority for names
     descriptions = data.functions + data.variables + data.structs + \
     descriptions = data.functions + data.variables + data.structs + \
         data.typedefs + data.enums + data.constants + data.macros
         data.typedefs + data.enums + data.constants + data.macros
-    
+
     # This dictionary maps names to a string representing where the name
     # This dictionary maps names to a string representing where the name
     # came from.
     # 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:
     for name in preamble_names:
         important_names[name] = "a name needed by ctypes or ctypesgen"
         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:
     for name in opts.other_known_names:
         important_names[name] = "a name from an included Python module"
         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:
     for description in descriptions:
         if description.py_name() in important_names:
         if description.py_name() in important_names:
             conflict_name = important_names[description.py_name()]
             conflict_name = important_names[description.py_name()]
-            
-            original_name=description.casual_name()
+
+            original_name = description.casual_name()
             while description.py_name() in important_names:
             while description.py_name() in important_names:
                 if isinstance(description,
                 if isinstance(description,
-                                (StructDescription, EnumDescription)):
-                    description.tag+="_"
+                              (StructDescription, EnumDescription)):
+                    description.tag += "_"
                 else:
                 else:
-                    description.name="_"+description.name
-            
+                    description.name = "_" + description.name
+
             if not description.dependents:
             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:
             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:
                 for dependent in description.dependents:
                     dependent.include_rule = "never"
                     dependent.include_rule = "never"
-            
-            if description.include_rule=="yes":
+
+            if description.include_rule == "yes":
                 important_names[description.py_name()] = \
                 important_names[description.py_name()] = \
                     description.casual_name()
                     description.casual_name()
-    
+
     # Names of struct members don't conflict with much, but they can conflict
     # Names of struct members don't conflict with much, but they can conflict
     # with Python keywords.
     # with Python keywords.
-    
+
     for struct in data.structs:
     for struct in data.structs:
         if not struct.opaque:
         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:
                 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.
     # Macro arguments may be have names that conflict with Python keywords.
     # In a perfect world, this would simply rename the parameter instead
     # In a perfect world, this would simply rename the parameter instead
     # of throwing an error message.
     # of throwing an error message.
-    
+
     for macro in data.macros:
     for macro in data.macros:
         if macro.params:
         if macro.params:
             for param in macro.params:
             for param in macro.params:
                 if param in keyword.kwlist:
                 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
     """find_source_libraries() determines which library contains each function
     and variable."""
     and variable."""
-    
-    all_symbols=data.functions+data.variables
-    
+
+    all_symbols = data.functions + data.variables
+
     for symbol in all_symbols:
     for symbol in all_symbols:
-        symbol.source_library=None
-    
+        symbol.source_library = None
+
     ctypesgencore.libraryloader.add_library_search_dirs(opts.compile_libdirs)
     ctypesgencore.libraryloader.add_library_search_dirs(opts.compile_libdirs)
-    
+
     for library_name in opts.libraries:
     for library_name in opts.libraries:
         try:
         try:
-            library=ctypesgencore.libraryloader.load_library(library_name)
+            library = ctypesgencore.libraryloader.load_library(library_name)
         except ImportError as e:
         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
             continue
         for symbol in all_symbols:
         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
 #!/usr/bin/env python
 
 
-import ctypes, re, os
+import ctypes
+import re
+import os
 from ctypesgencore.processor.operations import *
 from ctypesgencore.processor.operations import *
 from ctypesgencore.processor.dependencies import find_dependencies
 from ctypesgencore.processor.dependencies import find_dependencies
 from ctypesgencore.ctypedescs import *
 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.")
     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_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
     """calculate_final_inclusion() calculates which descriptions will be included in the
     output library.
     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
     An object with include_rule="if_needed" is included if an object to be
         included requires it and if its requirements can be included.
         included requires it and if its requirements can be included.
     """
     """
-    
+
     def can_include_desc(desc):
     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:
                 for req in desc.requirements:
                     if not can_include_desc(req):
                     if not can_include_desc(req):
-                        desc.can_include=False
+                        desc.can_include = False
         return desc.can_include
         return desc.can_include
-        
+
     def do_include_desc(desc):
     def do_include_desc(desc):
         if desc.included:
         if desc.included:
-            return # We've already been here
+            return  # We've already been here
         desc.included = True
         desc.included = True
         for req in desc.requirements:
         for req in desc.requirements:
             do_include_desc(req)
             do_include_desc(req)
-    
+
     for desc in data.all:
     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:
     for desc in data.all:
-        if desc.include_rule=="yes":
+        if desc.include_rule == "yes":
             if can_include_desc(desc):
             if can_include_desc(desc):
                 do_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
     # See descriptions.py for an explanation of the error-handling mechanism
     for desc in data.all:
     for desc in data.all:
         # If description would not have been included, dont bother user by
         # If description would not have been included, dont bother user by
         # printing warnings.
         # printing warnings.
         if desc.included or opts.show_all_errors:
         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.
                     # Macro errors will always be displayed as warnings.
                     if isinstance(desc, MacroDescription):
                     if isinstance(desc, MacroDescription):
                         if opts.show_macro_warnings:
                         if opts.show_macro_warnings:
-                            warning_message(error,cls)
+                            warning_message(error, cls)
                     else:
                     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:
             else:
                 if desc.errors:
                 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)
                     numwarns = len(desc.warnings)
                     if numwarns:
                     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:
                     else:
-                        error_message("%d more errors for %s " % \
-                            (numerrs,desc.casual_name()))
+                        error_message("%d more errors for %s " %
+                                      (numerrs, desc.casual_name()))
                 else:
                 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:
         if desc.errors:
             # process() will recalculate to take this into account
             # process() will recalculate to take this into account
             desc.include_rule = "never"
             desc.include_rule = "never"
-

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

@@ -1,7 +1,7 @@
 #!/usr/bin/sed -f
 #!/usr/bin/sed -f
 /^# End loader$/a\
 /^# 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 preamble$/,/^# End preamble$/d
 /^# Begin loader$/,/^# End loader$/d
 /^# Begin loader$/,/^# End loader$/d

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

@@ -2,14 +2,14 @@
 # Copyright (c) 2008 David James
 # Copyright (c) 2008 David James
 # Copyright (c) 2006-2008 Alex Holkner
 # Copyright (c) 2006-2008 Alex Holkner
 # All rights reserved.
 # All rights reserved.
-# 
+#
 # Redistribution and use in source and binary forms, with or without
 # 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:
 # are met:
 #
 #
 #  * Redistributions of source code must retain the above copyright
 #  * Redistributions of source code must retain the above copyright
 #    notice, this list of conditions and the following disclaimer.
 #    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
 #    notice, this list of conditions and the following disclaimer in
 #    the documentation and/or other materials provided with the
 #    the documentation and/or other materials provided with the
 #    distribution.
 #    distribution.
@@ -32,31 +32,38 @@
 # POSSIBILITY OF SUCH DAMAGE.
 # POSSIBILITY OF SUCH DAMAGE.
 # ----------------------------------------------------------------------------
 # ----------------------------------------------------------------------------
 
 
-import os.path, re, sys, glob
+import glob
+import os.path
+import re
+import sys
+
 import ctypes
 import ctypes
 import ctypes.util
 import ctypes.util
 
 
+
 def _environ_path(name):
 def _environ_path(name):
     if name in os.environ:
     if name in os.environ:
         return os.environ[name].split(":")
         return os.environ[name].split(":")
     else:
     else:
         return []
         return []
 
 
+
 class LibraryLoader(object):
 class LibraryLoader(object):
+
     def __init__(self):
     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."""
         """Given the name of a library, load it."""
         paths = self.getpaths(libname)
         paths = self.getpaths(libname)
-        
+
         for path in paths:
         for path in paths:
             if os.path.exists(path):
             if os.path.exists(path):
                 return self.load(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."""
         """Given a path to a library, load it."""
         try:
         try:
             # Darwin requires dlopen to be called with mode RTLD_GLOBAL instead
             # Darwin requires dlopen to be called with mode RTLD_GLOBAL instead
@@ -68,42 +75,44 @@ class LibraryLoader(object):
             else:
             else:
                 return ctypes.cdll.LoadLibrary(path)
                 return ctypes.cdll.LoadLibrary(path)
         except OSError as e:
         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."""
         """Return a list of paths where the library might be found."""
         if os.path.isabs(libname):
         if os.path.isabs(libname):
             yield libname
             yield libname
-        
+
         else:
         else:
             for path in self.getplatformpaths(libname):
             for path in self.getplatformpaths(libname):
                 yield path
                 yield path
-            
+
             path = ctypes.util.find_library(libname)
             path = ctypes.util.find_library(libname)
-            if path: yield path
-    
+            if path:
+                yield path
+
     def getplatformpaths(self, libname):
     def getplatformpaths(self, libname):
         return []
         return []
 
 
 # Darwin (Mac OS X)
 # Darwin (Mac OS X)
 
 
+
 class DarwinLibraryLoader(LibraryLoader):
 class DarwinLibraryLoader(LibraryLoader):
     name_formats = ["lib%s.dylib", "lib%s.so", "lib%s.bundle", "%s.dylib",
     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:
         if os.path.pathsep in libname:
             names = [libname]
             names = [libname]
         else:
         else:
             names = [format % libname for format in self.name_formats]
             names = [format % libname for format in self.name_formats]
-        
+
         for dir in self.getdirs(libname):
         for dir in self.getdirs(libname):
             for name in names:
             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:
         '''Implements the dylib search as specified in Apple documentation:
-        
+
         http://developer.apple.com/documentation/DeveloperTools/Conceptual/
         http://developer.apple.com/documentation/DeveloperTools/Conceptual/
             DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html
             DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html
 
 
@@ -116,9 +125,9 @@ class DarwinLibraryLoader(LibraryLoader):
         if not dyld_fallback_library_path:
         if not dyld_fallback_library_path:
             dyld_fallback_library_path = [os.path.expanduser('~/lib'),
             dyld_fallback_library_path = [os.path.expanduser('~/lib'),
                                           '/usr/local/lib', '/usr/lib']
                                           '/usr/local/lib', '/usr/lib']
-        
+
         dirs = []
         dirs = []
-        
+
         if '/' in libname:
         if '/' in libname:
             dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
             dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
         else:
         else:
@@ -127,7 +136,7 @@ class DarwinLibraryLoader(LibraryLoader):
 
 
         dirs.extend(self.other_dirs)
         dirs.extend(self.other_dirs)
         dirs.append(".")
         dirs.append(".")
-        
+
         if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
         if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
             dirs.append(os.path.join(
             dirs.append(os.path.join(
                 os.environ['RESOURCEPATH'],
                 os.environ['RESOURCEPATH'],
@@ -135,14 +144,15 @@ class DarwinLibraryLoader(LibraryLoader):
                 'Frameworks'))
                 'Frameworks'))
 
 
         dirs.extend(dyld_fallback_library_path)
         dirs.extend(dyld_fallback_library_path)
-        
+
         return dirs
         return dirs
 
 
 # Posix
 # Posix
 
 
+
 class PosixLibraryLoader(LibraryLoader):
 class PosixLibraryLoader(LibraryLoader):
     _ld_so_cache = None
     _ld_so_cache = None
-    
+
     def _create_ld_so_cache(self):
     def _create_ld_so_cache(self):
         # Recreate search path followed by ld.so.  This is going to be
         # 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
         # slow to build, and incorrect (ld.so uses ld.so.cache, which may
@@ -153,17 +163,19 @@ class PosixLibraryLoader(LibraryLoader):
 
 
         directories = []
         directories = []
         for name in ("LD_LIBRARY_PATH",
         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:
             if name in os.environ:
                 directories.extend(os.environ[name].split(os.pathsep))
                 directories.extend(os.environ[name].split(os.pathsep))
         directories.extend(self.other_dirs)
         directories.extend(self.other_dirs)
         directories.append(".")
         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'])
         directories.extend(['/lib', '/usr/lib', '/lib64', '/usr/lib64'])
 
 
@@ -178,7 +190,7 @@ class PosixLibraryLoader(LibraryLoader):
                     # Index by filename
                     # Index by filename
                     if file not in cache:
                     if file not in cache:
                         cache[file] = path
                         cache[file] = path
-                    
+
                     # Index by library name
                     # Index by library name
                     match = lib_re.match(file)
                     match = lib_re.match(file)
                     if match:
                     if match:
@@ -189,37 +201,44 @@ class PosixLibraryLoader(LibraryLoader):
                 pass
                 pass
 
 
         self._ld_so_cache = cache
         self._ld_so_cache = cache
-    
+
     def getplatformpaths(self, libname):
     def getplatformpaths(self, libname):
         if self._ld_so_cache is None:
         if self._ld_so_cache is None:
             self._create_ld_so_cache()
             self._create_ld_so_cache()
 
 
         result = self._ld_so_cache.get(libname)
         result = self._ld_so_cache.get(libname)
-        if result: yield result
+        if result:
+            yield result
 
 
         path = ctypes.util.find_library(libname)
         path = ctypes.util.find_library(libname)
-        if path: yield os.path.join("/lib",path)
+        if path:
+            yield os.path.join("/lib", path)
 
 
 # Windows
 # Windows
 
 
+
 class _WindowsLibrary(object):
 class _WindowsLibrary(object):
+
     def __init__(self, path):
     def __init__(self, path):
         self.cdll = ctypes.cdll.LoadLibrary(path)
         self.cdll = ctypes.cdll.LoadLibrary(path)
         self.windll = ctypes.windll.LoadLibrary(path)
         self.windll = ctypes.windll.LoadLibrary(path)
 
 
     def __getattr__(self, name):
     def __getattr__(self, name):
-        try: return getattr(self.cdll,name)
+        try:
+            return getattr(self.cdll, name)
         except AttributeError:
         except AttributeError:
-            try: return getattr(self.windll,name)
+            try:
+                return getattr(self.windll, name)
             except AttributeError:
             except AttributeError:
                 raise
                 raise
 
 
+
 class WindowsLibraryLoader(LibraryLoader):
 class WindowsLibraryLoader(LibraryLoader):
     name_formats = ["%s.dll", "lib%s.dll"]
     name_formats = ["%s.dll", "lib%s.dll"]
-    
+
     def load(self, path):
     def load(self, path):
         return _WindowsLibrary(path)
         return _WindowsLibrary(path)
-    
+
     def getplatformpaths(self, libname):
     def getplatformpaths(self, libname):
         if os.path.sep not in libname:
         if os.path.sep not in libname:
             for name in self.name_formats:
             for name in self.name_formats:
@@ -233,13 +252,14 @@ class WindowsLibraryLoader(LibraryLoader):
 # the Ctypesgen maintainers.
 # the Ctypesgen maintainers.
 
 
 loaderclass = {
 loaderclass = {
-    "darwin":   DarwinLibraryLoader,
-    "cygwin":   WindowsLibraryLoader,
-    "win32":    WindowsLibraryLoader
+    "darwin": DarwinLibraryLoader,
+    "cygwin": WindowsLibraryLoader,
+    "win32": WindowsLibraryLoader
 }
 }
 
 
 loader = loaderclass.get(sys.platform, PosixLibraryLoader)()
 loader = loaderclass.get(sys.platform, PosixLibraryLoader)()
 
 
+
 def add_library_search_dirs(other_dirs):
 def add_library_search_dirs(other_dirs):
     loader.other_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 *
 from ctypes import *
 
 
 _int_types = (c_int16, c_int32)
 _int_types = (c_int16, c_int32)
@@ -13,12 +16,14 @@ for t in _int_types:
 del t
 del t
 del _int_types
 del _int_types
 
 
+
 class c_void(Structure):
 class c_void(Structure):
     # c_void_p is a buggy return type, converting to int, so
     # c_void_p is a buggy return type, converting to int, so
     # POINTER(None) == c_void_p is actually written as
     # POINTER(None) == c_void_p is actually written as
     # POINTER(c_void), so it can be treated as a real pointer.
     # POINTER(c_void), so it can be treated as a real pointer.
     _fields_ = [('dummy', c_int)]
     _fields_ = [('dummy', c_int)]
 
 
+
 def POINTER(obj):
 def POINTER(obj):
     p = ctypes.POINTER(obj)
     p = ctypes.POINTER(obj)
 
 
@@ -44,29 +49,35 @@ ReturnString = c_char_p
 #
 #
 # Non-primitive return values wrapped with UNCHECKED won't be
 # Non-primitive return values wrapped with UNCHECKED won't be
 # typechecked, and will be converted to c_void_p.
 # typechecked, and will be converted to c_void_p.
+
+
 def UNCHECKED(type):
 def UNCHECKED(type):
     if (hasattr(type, "_type_") and isinstance(type._type_, str)
     if (hasattr(type, "_type_") and isinstance(type._type_, str)
-        and type._type_ != "P"):
+            and type._type_ != "P"):
         return type
         return type
     else:
     else:
         return c_void_p
         return c_void_p
 
 
 # ctypes doesn't have direct support for variadic functions, so we have to write
 # ctypes doesn't have direct support for variadic functions, so we have to write
 # our own wrapper class
 # our own wrapper class
+
+
 class _variadic_function(object):
 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):
     def _as_parameter_(self):
         # So we can pass this variadic function as a function pointer
         # So we can pass this variadic function as a function pointer
         return self.func
         return self.func
-    def __call__(self,*args):
-        fixed_args=[]
-        i=0
+
+    def __call__(self, *args):
+        fixed_args = []
+        i = 0
         for argtype in self.argtypes:
         for argtype in self.argtypes:
             # Typecheck what we can
             # Typecheck what we can
             fixed_args.append(argtype.from_param(args[i]))
             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:]))