home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 July / maximum-cd-2011-07.iso / DiscContents / LibO_3.3.2_Win_x86_install_multi.exe / libreoffice1.cab / build_ext.py < prev    next >
Encoding:
Python Source  |  2011-03-15  |  31.2 KB  |  771 lines

  1. """distutils.command.build_ext
  2.  
  3. Implements the Distutils 'build_ext' command, for building extension
  4. modules (currently limited to C extensions, should accommodate C++
  5. extensions ASAP)."""
  6.  
  7. # This module should be kept compatible with Python 2.1.
  8.  
  9. __revision__ = "$Id: build_ext.py 65742 2008-08-17 04:16:04Z brett.cannon $"
  10.  
  11. import sys, os, string, re
  12. from types import *
  13. from site import USER_BASE, USER_SITE
  14. from distutils.core import Command
  15. from distutils.errors import *
  16. from distutils.sysconfig import customize_compiler, get_python_version
  17. from distutils.dep_util import newer_group
  18. from distutils.extension import Extension
  19. from distutils.util import get_platform
  20. from distutils import log
  21.  
  22. if os.name == 'nt':
  23.     from distutils.msvccompiler import get_build_version
  24.     MSVC_VERSION = int(get_build_version())
  25.  
  26. # An extension name is just a dot-separated list of Python NAMEs (ie.
  27. # the same as a fully-qualified module name).
  28. extension_name_re = re.compile \
  29.     (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
  30.  
  31.  
  32. def show_compilers ():
  33.     from distutils.ccompiler import show_compilers
  34.     show_compilers()
  35.  
  36.  
  37. class build_ext (Command):
  38.  
  39.     description = "build C/C++ extensions (compile/link to build directory)"
  40.  
  41.     # XXX thoughts on how to deal with complex command-line options like
  42.     # these, i.e. how to make it so fancy_getopt can suck them off the
  43.     # command line and make it look like setup.py defined the appropriate
  44.     # lists of tuples of what-have-you.
  45.     #   - each command needs a callback to process its command-line options
  46.     #   - Command.__init__() needs access to its share of the whole
  47.     #     command line (must ultimately come from
  48.     #     Distribution.parse_command_line())
  49.     #   - it then calls the current command class' option-parsing
  50.     #     callback to deal with weird options like -D, which have to
  51.     #     parse the option text and churn out some custom data
  52.     #     structure
  53.     #   - that data structure (in this case, a list of 2-tuples)
  54.     #     will then be present in the command object by the time
  55.     #     we get to finalize_options() (i.e. the constructor
  56.     #     takes care of both command-line and client options
  57.     #     in between initialize_options() and finalize_options())
  58.  
  59.     sep_by = " (separated by '%s')" % os.pathsep
  60.     user_options = [
  61.         ('build-lib=', 'b',
  62.          "directory for compiled extension modules"),
  63.         ('build-temp=', 't',
  64.          "directory for temporary files (build by-products)"),
  65.         ('plat-name=', 'p',
  66.          "platform name to cross-compile for, if supported "
  67.          "(default: %s)" % get_platform()),
  68.         ('inplace', 'i',
  69.          "ignore build-lib and put compiled extensions into the source " +
  70.          "directory alongside your pure Python modules"),
  71.         ('include-dirs=', 'I',
  72.          "list of directories to search for header files" + sep_by),
  73.         ('define=', 'D',
  74.          "C preprocessor macros to define"),
  75.         ('undef=', 'U',
  76.          "C preprocessor macros to undefine"),
  77.         ('libraries=', 'l',
  78.          "external C libraries to link with"),
  79.         ('library-dirs=', 'L',
  80.          "directories to search for external C libraries" + sep_by),
  81.         ('rpath=', 'R',
  82.          "directories to search for shared C libraries at runtime"),
  83.         ('link-objects=', 'O',
  84.          "extra explicit link objects to include in the link"),
  85.         ('debug', 'g',
  86.          "compile/link with debugging information"),
  87.         ('force', 'f',
  88.          "forcibly build everything (ignore file timestamps)"),
  89.         ('compiler=', 'c',
  90.          "specify the compiler type"),
  91.         ('swig-cpp', None,
  92.          "make SWIG create C++ files (default is C)"),
  93.         ('swig-opts=', None,
  94.          "list of SWIG command line options"),
  95.         ('swig=', None,
  96.          "path to the SWIG executable"),
  97.         ('user', None,
  98.          "add user include, library and rpath"),
  99.         ]
  100.  
  101.     boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
  102.  
  103.     help_options = [
  104.         ('help-compiler', None,
  105.          "list available compilers", show_compilers),
  106.         ]
  107.  
  108.     def initialize_options (self):
  109.         self.extensions = None
  110.         self.build_lib = None
  111.         self.plat_name = None
  112.         self.build_temp = None
  113.         self.inplace = 0
  114.         self.package = None
  115.  
  116.         self.include_dirs = None
  117.         self.define = None
  118.         self.undef = None
  119.         self.libraries = None
  120.         self.library_dirs = None
  121.         self.rpath = None
  122.         self.link_objects = None
  123.         self.debug = None
  124.         self.force = None
  125.         self.compiler = None
  126.         self.swig = None
  127.         self.swig_cpp = None
  128.         self.swig_opts = None
  129.         self.user = None
  130.  
  131.     def finalize_options (self):
  132.         from distutils import sysconfig
  133.  
  134.         self.set_undefined_options('build',
  135.                                    ('build_lib', 'build_lib'),
  136.                                    ('build_temp', 'build_temp'),
  137.                                    ('compiler', 'compiler'),
  138.                                    ('debug', 'debug'),
  139.                                    ('force', 'force'),
  140.                                    ('plat_name', 'plat_name'),
  141.                                    )
  142.  
  143.         if self.package is None:
  144.             self.package = self.distribution.ext_package
  145.  
  146.         self.extensions = self.distribution.ext_modules
  147.  
  148.  
  149.         # Make sure Python's include directories (for Python.h, pyconfig.h,
  150.         # etc.) are in the include search path.
  151.         py_include = sysconfig.get_python_inc()
  152.         plat_py_include = sysconfig.get_python_inc(plat_specific=1)
  153.         if self.include_dirs is None:
  154.             self.include_dirs = self.distribution.include_dirs or []
  155.         if type(self.include_dirs) is StringType:
  156.             self.include_dirs = string.split(self.include_dirs, os.pathsep)
  157.  
  158.         # Put the Python "system" include dir at the end, so that
  159.         # any local include dirs take precedence.
  160.         self.include_dirs.append(py_include)
  161.         if plat_py_include != py_include:
  162.             self.include_dirs.append(plat_py_include)
  163.  
  164.         if type(self.libraries) is StringType:
  165.             self.libraries = [self.libraries]
  166.  
  167.         # Life is easier if we're not forever checking for None, so
  168.         # simplify these options to empty lists if unset
  169.         if self.libraries is None:
  170.             self.libraries = []
  171.         if self.library_dirs is None:
  172.             self.library_dirs = []
  173.         elif type(self.library_dirs) is StringType:
  174.             self.library_dirs = string.split(self.library_dirs, os.pathsep)
  175.  
  176.         if self.rpath is None:
  177.             self.rpath = []
  178.         elif type(self.rpath) is StringType:
  179.             self.rpath = string.split(self.rpath, os.pathsep)
  180.  
  181.         # for extensions under windows use different directories
  182.         # for Release and Debug builds.
  183.         # also Python's library directory must be appended to library_dirs
  184.         if os.name == 'nt':
  185.             # the 'libs' directory is for binary installs - we assume that
  186.             # must be the *native* platform.  But we don't really support
  187.             # cross-compiling via a binary install anyway, so we let it go.
  188.             self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
  189.             if self.debug:
  190.                 self.build_temp = os.path.join(self.build_temp, "Debug")
  191.             else:
  192.                 self.build_temp = os.path.join(self.build_temp, "Release")
  193.  
  194.             # Append the source distribution include and library directories,
  195.             # this allows distutils on windows to work in the source tree
  196.             self.include_dirs.append(os.path.join(sys.exec_prefix, 'PC'))
  197.             if MSVC_VERSION == 9:
  198.                 # Use the .lib files for the correct architecture
  199.                 if self.plat_name == 'win32':
  200.                     suffix = ''
  201.                 else:
  202.                     # win-amd64 or win-ia64
  203.                     suffix = self.plat_name[4:]
  204.                 new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
  205.                 if suffix:
  206.                     new_lib = os.path.join(new_lib, suffix)
  207.                 self.library_dirs.append(new_lib)
  208.  
  209.             elif MSVC_VERSION == 8:
  210.                 self.library_dirs.append(os.path.join(sys.exec_prefix,
  211.                                          'PC', 'VS8.0', 'win32release'))
  212.             elif MSVC_VERSION == 7:
  213.                 self.library_dirs.append(os.path.join(sys.exec_prefix,
  214.                                          'PC', 'VS7.1'))
  215.             else:
  216.                 self.library_dirs.append(os.path.join(sys.exec_prefix,
  217.                                          'PC', 'VC6'))
  218.  
  219.         # OS/2 (EMX) doesn't support Debug vs Release builds, but has the
  220.         # import libraries in its "Config" subdirectory
  221.         if os.name == 'os2':
  222.             self.library_dirs.append(os.path.join(sys.exec_prefix, 'Config'))
  223.  
  224.         # for extensions under Cygwin and AtheOS Python's library directory must be
  225.         # appended to library_dirs
  226.         if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
  227.             if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
  228.                 # building third party extensions
  229.                 self.library_dirs.append(os.path.join(sys.prefix, "lib",
  230.                                                       "python" + get_python_version(),
  231.                                                       "config"))
  232.             else:
  233.                 # building python standard extensions
  234.                 self.library_dirs.append('.')
  235.  
  236.         # for extensions under Linux with a shared Python library,
  237.         # Python's library directory must be appended to library_dirs
  238.         if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \
  239.                 and sysconfig.get_config_var('Py_ENABLE_SHARED'):
  240.             if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
  241.                 # building third party extensions
  242.                 self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
  243.             else:
  244.                 # building python standard extensions
  245.                 self.library_dirs.append('.')
  246.  
  247.         # The argument parsing will result in self.define being a string, but
  248.         # it has to be a list of 2-tuples.  All the preprocessor symbols
  249.         # specified by the 'define' option will be set to '1'.  Multiple
  250.         # symbols can be separated with commas.
  251.  
  252.         if self.define:
  253.             defines = string.split(self.define, ',')
  254.             self.define = map(lambda symbol: (symbol, '1'), defines)
  255.  
  256.         # The option for macros to undefine is also a string from the
  257.         # option parsing, but has to be a list.  Multiple symbols can also
  258.         # be separated with commas here.
  259.         if self.undef:
  260.             self.undef = string.split(self.undef, ',')
  261.  
  262.         if self.swig_opts is None:
  263.             self.swig_opts = []
  264.         else:
  265.             self.swig_opts = self.swig_opts.split(' ')
  266.  
  267.         # Finally add the user include and library directories if requested
  268.         if self.user:
  269.             user_include = os.path.join(USER_BASE, "include")
  270.             user_lib = os.path.join(USER_BASE, "lib")
  271.             if os.path.isdir(user_include):
  272.                 self.include_dirs.append(user_include)
  273.             if os.path.isdir(user_lib):
  274.                 self.library_dirs.append(user_lib)
  275.                 self.rpath.append(user_lib)
  276.  
  277.     # finalize_options ()
  278.  
  279.  
  280.     def run (self):
  281.  
  282.         from distutils.ccompiler import new_compiler
  283.  
  284.         # 'self.extensions', as supplied by setup.py, is a list of
  285.         # Extension instances.  See the documentation for Extension (in
  286.         # distutils.extension) for details.
  287.         #
  288.         # For backwards compatibility with Distutils 0.8.2 and earlier, we
  289.         # also allow the 'extensions' list to be a list of tuples:
  290.         #    (ext_name, build_info)
  291.         # where build_info is a dictionary containing everything that
  292.         # Extension instances do except the name, with a few things being
  293.         # differently named.  We convert these 2-tuples to Extension
  294.         # instances as needed.
  295.  
  296.         if not self.extensions:
  297.             return
  298.  
  299.         # If we were asked to build any C/C++ libraries, make sure that the
  300.         # directory where we put them is in the library search path for
  301.         # linking extensions.
  302.         if self.distribution.has_c_libraries():
  303.             build_clib = self.get_finalized_command('build_clib')
  304.             self.libraries.extend(build_clib.get_library_names() or [])
  305.             self.library_dirs.append(build_clib.build_clib)
  306.  
  307.         # Setup the CCompiler object that we'll use to do all the
  308.         # compiling and linking
  309.         self.compiler = new_compiler(compiler=self.compiler,
  310.                                      verbose=self.verbose,
  311.                                      dry_run=self.dry_run,
  312.                                      force=self.force)
  313.         customize_compiler(self.compiler)
  314.         # If we are cross-compiling, init the compiler now (if we are not
  315.         # cross-compiling, init would not hurt, but people may rely on
  316.         # late initialization of compiler even if they shouldn't...)
  317.         if os.name == 'nt' and self.plat_name != get_platform():
  318.             self.compiler.initialize(self.plat_name)
  319.  
  320.         # And make sure that any compile/link-related options (which might
  321.         # come from the command-line or from the setup script) are set in
  322.         # that CCompiler object -- that way, they automatically apply to
  323.         # all compiling and linking done here.
  324.         if self.include_dirs is not None:
  325.             self.compiler.set_include_dirs(self.include_dirs)
  326.         if self.define is not None:
  327.             # 'define' option is a list of (name,value) tuples
  328.             for (name,value) in self.define:
  329.                 self.compiler.define_macro(name, value)
  330.         if self.undef is not None:
  331.             for macro in self.undef:
  332.                 self.compiler.undefine_macro(macro)
  333.         if self.libraries is not None:
  334.             self.compiler.set_libraries(self.libraries)
  335.         if self.library_dirs is not None:
  336.             self.compiler.set_library_dirs(self.library_dirs)
  337.         if self.rpath is not None:
  338.             self.compiler.set_runtime_library_dirs(self.rpath)
  339.         if self.link_objects is not None:
  340.             self.compiler.set_link_objects(self.link_objects)
  341.  
  342.         # Now actually compile and link everything.
  343.         self.build_extensions()
  344.  
  345.     # run ()
  346.  
  347.  
  348.     def check_extensions_list (self, extensions):
  349.         """Ensure that the list of extensions (presumably provided as a
  350.         command option 'extensions') is valid, i.e. it is a list of
  351.         Extension objects.  We also support the old-style list of 2-tuples,
  352.         where the tuples are (ext_name, build_info), which are converted to
  353.         Extension instances here.
  354.  
  355.         Raise DistutilsSetupError if the structure is invalid anywhere;
  356.         just returns otherwise.
  357.         """
  358.         if type(extensions) is not ListType:
  359.             raise DistutilsSetupError, \
  360.                   "'ext_modules' option must be a list of Extension instances"
  361.  
  362.         for i in range(len(extensions)):
  363.             ext = extensions[i]
  364.             if isinstance(ext, Extension):
  365.                 continue                # OK! (assume type-checking done
  366.                                         # by Extension constructor)
  367.  
  368.             (ext_name, build_info) = ext
  369.             log.warn(("old-style (ext_name, build_info) tuple found in "
  370.                       "ext_modules for extension '%s'"
  371.                       "-- please convert to Extension instance" % ext_name))
  372.             if type(ext) is not TupleType and len(ext) != 2:
  373.                 raise DistutilsSetupError, \
  374.                       ("each element of 'ext_modules' option must be an "
  375.                        "Extension instance or 2-tuple")
  376.  
  377.             if not (type(ext_name) is StringType and
  378.                     extension_name_re.match(ext_name)):
  379.                 raise DistutilsSetupError, \
  380.                       ("first element of each tuple in 'ext_modules' "
  381.                        "must be the extension name (a string)")
  382.  
  383.             if type(build_info) is not DictionaryType:
  384.                 raise DistutilsSetupError, \
  385.                       ("second element of each tuple in 'ext_modules' "
  386.                        "must be a dictionary (build info)")
  387.  
  388.             # OK, the (ext_name, build_info) dict is type-safe: convert it
  389.             # to an Extension instance.
  390.             ext = Extension(ext_name, build_info['sources'])
  391.  
  392.             # Easy stuff: one-to-one mapping from dict elements to
  393.             # instance attributes.
  394.             for key in ('include_dirs',
  395.                         'library_dirs',
  396.                         'libraries',
  397.                         'extra_objects',
  398.                         'extra_compile_args',
  399.                         'extra_link_args'):
  400.                 val = build_info.get(key)
  401.                 if val is not None:
  402.                     setattr(ext, key, val)
  403.  
  404.             # Medium-easy stuff: same syntax/semantics, different names.
  405.             ext.runtime_library_dirs = build_info.get('rpath')
  406.             if 'def_file' in build_info:
  407.                 log.warn("'def_file' element of build info dict "
  408.                          "no longer supported")
  409.  
  410.             # Non-trivial stuff: 'macros' split into 'define_macros'
  411.             # and 'undef_macros'.
  412.             macros = build_info.get('macros')
  413.             if macros:
  414.                 ext.define_macros = []
  415.                 ext.undef_macros = []
  416.                 for macro in macros:
  417.                     if not (type(macro) is TupleType and
  418.                             1 <= len(macro) <= 2):
  419.                         raise DistutilsSetupError, \
  420.                               ("'macros' element of build info dict "
  421.                                "must be 1- or 2-tuple")
  422.                     if len(macro) == 1:
  423.                         ext.undef_macros.append(macro[0])
  424.                     elif len(macro) == 2:
  425.                         ext.define_macros.append(macro)
  426.  
  427.             extensions[i] = ext
  428.  
  429.         # for extensions
  430.  
  431.     # check_extensions_list ()
  432.  
  433.  
  434.     def get_source_files (self):
  435.         self.check_extensions_list(self.extensions)
  436.         filenames = []
  437.  
  438.         # Wouldn't it be neat if we knew the names of header files too...
  439.         for ext in self.extensions:
  440.             filenames.extend(ext.sources)
  441.  
  442.         return filenames
  443.  
  444.  
  445.     def get_outputs (self):
  446.  
  447.         # Sanity check the 'extensions' list -- can't assume this is being
  448.         # done in the same run as a 'build_extensions()' call (in fact, we
  449.         # can probably assume that it *isn't*!).
  450.         self.check_extensions_list(self.extensions)
  451.  
  452.         # And build the list of output (built) filenames.  Note that this
  453.         # ignores the 'inplace' flag, and assumes everything goes in the
  454.         # "build" tree.
  455.         outputs = []
  456.         for ext in self.extensions:
  457.             fullname = self.get_ext_fullname(ext.name)
  458.             outputs.append(os.path.join(self.build_lib,
  459.                                         self.get_ext_filename(fullname)))
  460.         return outputs
  461.  
  462.     # get_outputs ()
  463.  
  464.     def build_extensions(self):
  465.         # First, sanity-check the 'extensions' list
  466.         self.check_extensions_list(self.extensions)
  467.  
  468.         for ext in self.extensions:
  469.             self.build_extension(ext)
  470.  
  471.     def build_extension(self, ext):
  472.         sources = ext.sources
  473.         if sources is None or type(sources) not in (ListType, TupleType):
  474.             raise DistutilsSetupError, \
  475.                   ("in 'ext_modules' option (extension '%s'), " +
  476.                    "'sources' must be present and must be " +
  477.                    "a list of source filenames") % ext.name
  478.         sources = list(sources)
  479.  
  480.         fullname = self.get_ext_fullname(ext.name)
  481.         if self.inplace:
  482.             # ignore build-lib -- put the compiled extension into
  483.             # the source tree along with pure Python modules
  484.  
  485.             modpath = string.split(fullname, '.')
  486.             package = string.join(modpath[0:-1], '.')
  487.             base = modpath[-1]
  488.  
  489.             build_py = self.get_finalized_command('build_py')
  490.             package_dir = build_py.get_package_dir(package)
  491.             ext_filename = os.path.join(package_dir,
  492.                                         self.get_ext_filename(base))
  493.         else:
  494.             ext_filename = os.path.join(self.build_lib,
  495.                                         self.get_ext_filename(fullname))
  496.         depends = sources + ext.depends
  497.         if not (self.force or newer_group(depends, ext_filename, 'newer')):
  498.             log.debug("skipping '%s' extension (up-to-date)", ext.name)
  499.             return
  500.         else:
  501.             log.info("building '%s' extension", ext.name)
  502.  
  503.         # First, scan the sources for SWIG definition files (.i), run
  504.         # SWIG on 'em to create .c files, and modify the sources list
  505.         # accordingly.
  506.         sources = self.swig_sources(sources, ext)
  507.  
  508.         # Next, compile the source code to object files.
  509.  
  510.         # XXX not honouring 'define_macros' or 'undef_macros' -- the
  511.         # CCompiler API needs to change to accommodate this, and I
  512.         # want to do one thing at a time!
  513.  
  514.         # Two possible sources for extra compiler arguments:
  515.         #   - 'extra_compile_args' in Extension object
  516.         #   - CFLAGS environment variable (not particularly
  517.         #     elegant, but people seem to expect it and I
  518.         #     guess it's useful)
  519.         # The environment variable should take precedence, and
  520.         # any sensible compiler will give precedence to later
  521.         # command line args.  Hence we combine them in order:
  522.         extra_args = ext.extra_compile_args or []
  523.  
  524.         macros = ext.define_macros[:]
  525.         for undef in ext.undef_macros:
  526.             macros.append((undef,))
  527.  
  528.         objects = self.compiler.compile(sources,
  529.                                         output_dir=self.build_temp,
  530.                                         macros=macros,
  531.                                         include_dirs=ext.include_dirs,
  532.                                         debug=self.debug,
  533.                                         extra_postargs=extra_args,
  534.                                         depends=ext.depends)
  535.  
  536.         # XXX -- this is a Vile HACK!
  537.         #
  538.         # The setup.py script for Python on Unix needs to be able to
  539.         # get this list so it can perform all the clean up needed to
  540.         # avoid keeping object files around when cleaning out a failed
  541.         # build of an extension module.  Since Distutils does not
  542.         # track dependencies, we have to get rid of intermediates to
  543.         # ensure all the intermediates will be properly re-built.
  544.         #
  545.         self._built_objects = objects[:]
  546.  
  547.         # Now link the object files together into a "shared object" --
  548.         # of course, first we have to figure out all the other things
  549.         # that go into the mix.
  550.         if ext.extra_objects:
  551.             objects.extend(ext.extra_objects)
  552.         extra_args = ext.extra_link_args or []
  553.  
  554.         # Detect target language, if not provided
  555.         language = ext.language or self.compiler.detect_language(sources)
  556.  
  557.         self.compiler.link_shared_object(
  558.             objects, ext_filename,
  559.             libraries=self.get_libraries(ext),
  560.             library_dirs=ext.library_dirs,
  561.             runtime_library_dirs=ext.runtime_library_dirs,
  562.             extra_postargs=extra_args,
  563.             export_symbols=self.get_export_symbols(ext),
  564.             debug=self.debug,
  565.             build_temp=self.build_temp,
  566.             target_lang=language)
  567.  
  568.  
  569.     def swig_sources (self, sources, extension):
  570.  
  571.         """Walk the list of source files in 'sources', looking for SWIG
  572.         interface (.i) files.  Run SWIG on all that are found, and
  573.         return a modified 'sources' list with SWIG source files replaced
  574.         by the generated C (or C++) files.
  575.         """
  576.  
  577.         new_sources = []
  578.         swig_sources = []
  579.         swig_targets = {}
  580.  
  581.         # XXX this drops generated C/C++ files into the source tree, which
  582.         # is fine for developers who want to distribute the generated
  583.         # source -- but there should be an option to put SWIG output in
  584.         # the temp dir.
  585.  
  586.         if self.swig_cpp:
  587.             log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
  588.  
  589.         if self.swig_cpp or ('-c++' in self.swig_opts) or \
  590.            ('-c++' in extension.swig_opts):
  591.             target_ext = '.cpp'
  592.         else:
  593.             target_ext = '.c'
  594.  
  595.         for source in sources:
  596.             (base, ext) = os.path.splitext(source)
  597.             if ext == ".i":             # SWIG interface file
  598.                 new_sources.append(base + '_wrap' + target_ext)
  599.                 swig_sources.append(source)
  600.                 swig_targets[source] = new_sources[-1]
  601.             else:
  602.                 new_sources.append(source)
  603.  
  604.         if not swig_sources:
  605.             return new_sources
  606.  
  607.         swig = self.swig or self.find_swig()
  608.         swig_cmd = [swig, "-python"]
  609.         swig_cmd.extend(self.swig_opts)
  610.         if self.swig_cpp:
  611.             swig_cmd.append("-c++")
  612.  
  613.         # Do not override commandline arguments
  614.         if not self.swig_opts:
  615.             for o in extension.swig_opts:
  616.                 swig_cmd.append(o)
  617.  
  618.         for source in swig_sources:
  619.             target = swig_targets[source]
  620.             log.info("swigging %s to %s", source, target)
  621.             self.spawn(swig_cmd + ["-o", target, source])
  622.  
  623.         return new_sources
  624.  
  625.     # swig_sources ()
  626.  
  627.     def find_swig (self):
  628.         """Return the name of the SWIG executable.  On Unix, this is
  629.         just "swig" -- it should be in the PATH.  Tries a bit harder on
  630.         Windows.
  631.         """
  632.  
  633.         if os.name == "posix":
  634.             return "swig"
  635.         elif os.name == "nt":
  636.  
  637.             # Look for SWIG in its standard installation directory on
  638.             # Windows (or so I presume!).  If we find it there, great;
  639.             # if not, act like Unix and assume it's in the PATH.
  640.             for vers in ("1.3", "1.2", "1.1"):
  641.                 fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
  642.                 if os.path.isfile(fn):
  643.                     return fn
  644.             else:
  645.                 return "swig.exe"
  646.  
  647.         elif os.name == "os2":
  648.             # assume swig available in the PATH.
  649.             return "swig.exe"
  650.  
  651.         else:
  652.             raise DistutilsPlatformError, \
  653.                   ("I don't know how to find (much less run) SWIG "
  654.                    "on platform '%s'") % os.name
  655.  
  656.     # find_swig ()
  657.  
  658.     # -- Name generators -----------------------------------------------
  659.     # (extension names, filenames, whatever)
  660.  
  661.     def get_ext_fullname (self, ext_name):
  662.         if self.package is None:
  663.             return ext_name
  664.         else:
  665.             return self.package + '.' + ext_name
  666.  
  667.     def get_ext_filename (self, ext_name):
  668.         r"""Convert the name of an extension (eg. "foo.bar") into the name
  669.         of the file from which it will be loaded (eg. "foo/bar.so", or
  670.         "foo\bar.pyd").
  671.         """
  672.  
  673.         from distutils.sysconfig import get_config_var
  674.         ext_path = string.split(ext_name, '.')
  675.         # OS/2 has an 8 character module (extension) limit :-(
  676.         if os.name == "os2":
  677.             ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8]
  678.         # extensions in debug_mode are named 'module_d.pyd' under windows
  679.         so_ext = get_config_var('SO')
  680.         if os.name == 'nt' and self.debug:
  681.             return apply(os.path.join, ext_path) + '_d' + so_ext
  682.         return os.path.join(*ext_path) + so_ext
  683.  
  684.     def get_export_symbols (self, ext):
  685.         """Return the list of symbols that a shared extension has to
  686.         export.  This either uses 'ext.export_symbols' or, if it's not
  687.         provided, "init" + module_name.  Only relevant on Windows, where
  688.         the .pyd file (DLL) must export the module "init" function.
  689.         """
  690.  
  691.         initfunc_name = "init" + string.split(ext.name,'.')[-1]
  692.         if initfunc_name not in ext.export_symbols:
  693.             ext.export_symbols.append(initfunc_name)
  694.         return ext.export_symbols
  695.  
  696.     def get_libraries (self, ext):
  697.         """Return the list of libraries to link against when building a
  698.         shared extension.  On most platforms, this is just 'ext.libraries';
  699.         on Windows and OS/2, we add the Python library (eg. python20.dll).
  700.         """
  701.         # The python library is always needed on Windows.  For MSVC, this
  702.         # is redundant, since the library is mentioned in a pragma in
  703.         # pyconfig.h that MSVC groks.  The other Windows compilers all seem
  704.         # to need it mentioned explicitly, though, so that's what we do.
  705.         # Append '_d' to the python import library on debug builds.
  706.         if sys.platform == "win32":
  707.             from distutils.msvccompiler import MSVCCompiler
  708.             if not isinstance(self.compiler, MSVCCompiler):
  709.                 template = "python%d%d"
  710.                 if self.debug:
  711.                     template = template + '_d'
  712.                 pythonlib = (template %
  713.                        (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  714.                 # don't extend ext.libraries, it may be shared with other
  715.                 # extensions, it is a reference to the original list
  716.                 return ext.libraries + [pythonlib]
  717.             else:
  718.                 return ext.libraries
  719.         elif sys.platform == "os2emx":
  720.             # EMX/GCC requires the python library explicitly, and I
  721.             # believe VACPP does as well (though not confirmed) - AIM Apr01
  722.             template = "python%d%d"
  723.             # debug versions of the main DLL aren't supported, at least
  724.             # not at this time - AIM Apr01
  725.             #if self.debug:
  726.             #    template = template + '_d'
  727.             pythonlib = (template %
  728.                    (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  729.             # don't extend ext.libraries, it may be shared with other
  730.             # extensions, it is a reference to the original list
  731.             return ext.libraries + [pythonlib]
  732.         elif sys.platform[:6] == "cygwin":
  733.             template = "python%d.%d"
  734.             pythonlib = (template %
  735.                    (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  736.             # don't extend ext.libraries, it may be shared with other
  737.             # extensions, it is a reference to the original list
  738.             return ext.libraries + [pythonlib]
  739.         elif sys.platform[:6] == "atheos":
  740.             from distutils import sysconfig
  741.  
  742.             template = "python%d.%d"
  743.             pythonlib = (template %
  744.                    (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  745.             # Get SHLIBS from Makefile
  746.             extra = []
  747.             for lib in sysconfig.get_config_var('SHLIBS').split():
  748.                 if lib.startswith('-l'):
  749.                     extra.append(lib[2:])
  750.                 else:
  751.                     extra.append(lib)
  752.             # don't extend ext.libraries, it may be shared with other
  753.             # extensions, it is a reference to the original list
  754.             return ext.libraries + [pythonlib, "m"] + extra
  755.  
  756.         elif sys.platform == 'darwin':
  757.             # Don't use the default code below
  758.             return ext.libraries
  759.  
  760.         else:
  761.             from distutils import sysconfig
  762.             if sysconfig.get_config_var('Py_ENABLE_SHARED'):
  763.                 template = "python%d.%d"
  764.                 pythonlib = (template %
  765.                              (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  766.                 return ext.libraries + [pythonlib]
  767.             else:
  768.                 return ext.libraries
  769.  
  770. # class build_ext
  771.