1268 lines · 50.8 KB · Python
RawDownload
"""distutils.ccompiler Contains CCompiler, an abstract base class that defines the interfacefor the Distutils compiler abstraction model.""" # This module should be kept compatible with Python 2.1. __revision__ = "$Id: ccompiler.py 46331 2006-05-26 14:07:23Z bob.ippolito $" import sys, os, refrom types import *from copy import copyfrom distutils.errors import *from distutils.spawn import spawnfrom distutils.file_util import move_filefrom distutils.dir_util import mkpathfrom distutils.dep_util import newer_pairwise, newer_groupfrom distutils.util import split_quoted, executefrom distutils import log class CCompiler:    """Abstract base class to define the interface that must be implemented    by real compiler classes.  Also has some utility methods used by    several compiler classes.     The basic idea behind a compiler abstraction class is that each    instance can be used for all the compile/link steps in building a    single project.  Thus, attributes common to all of those compile and    link steps -- include directories, macros to define, libraries to link    against, etc. -- are attributes of the compiler instance.  To allow for    variability in how individual files are treated, most of those    attributes may be varied on a per-compilation or per-link basis.    """     # 'compiler_type' is a class attribute that identifies this class.  It    # keeps code that wants to know what kind of compiler it's dealing with    # from having to import all possible compiler classes just to do an    # 'isinstance'.  In concrete CCompiler subclasses, 'compiler_type'    # should really, really be one of the keys of the 'compiler_class'    # dictionary (see below -- used by the 'new_compiler()' factory    # function) -- authors of new compiler interface classes are    # responsible for updating 'compiler_class'!    compiler_type = None     # XXX things not handled by this compiler abstraction model:    #   * client can't provide additional options for a compiler,    #     e.g. warning, optimization, debugging flags.  Perhaps this    #     should be the domain of concrete compiler abstraction classes    #     (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base    #     class should have methods for the common ones.    #   * can't completely override the include or library searchg    #     path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".    #     I'm not sure how widely supported this is even by Unix    #     compilers, much less on other platforms.  And I'm even less    #     sure how useful it is; maybe for cross-compiling, but    #     support for that is a ways off.  (And anyways, cross    #     compilers probably have a dedicated binary with the    #     right paths compiled in.  I hope.)    #   * can't do really freaky things with the library list/library    #     dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against    #     different versions of libfoo.a in different locations.  I    #     think this is useless without the ability to null out the    #     library search path anyways.      # Subclasses that rely on the standard filename generation methods    # implemented below should override these; see the comment near    # those methods ('object_filenames()' et. al.) for details:    src_extensions = None               # list of strings    obj_extension = None                # string    static_lib_extension = None    shared_lib_extension = None         # string    static_lib_format = None            # format string    shared_lib_format = None            # prob. same as static_lib_format    exe_extension = None                # string     # Default language settings. language_map is used to detect a source    # file or Extension target language, checking source filenames.    # language_order is used to detect the language precedence, when deciding    # what language to use when mixing source types. For example, if some    # extension has two files with ".c" extension, and one with ".cpp", it    # is still linked as c++.    language_map = {".c"   : "c",                    ".cc"  : "c++",                    ".cpp" : "c++",                    ".cxx" : "c++",                    ".m"   : "objc",                   }    language_order = ["c++", "objc", "c"]     def __init__ (self,                  verbose=0,                  dry_run=0,                  force=0):         self.dry_run = dry_run        self.force = force        self.verbose = verbose         # 'output_dir': a common output directory for object, library,        # shared object, and shared library files        self.output_dir = None         # 'macros': a list of macro definitions (or undefinitions).  A        # macro definition is a 2-tuple (name, value), where the value is        # either a string or None (no explicit value).  A macro        # undefinition is a 1-tuple (name,).        self.macros = []         # 'include_dirs': a list of directories to search for include files        self.include_dirs = []         # 'libraries': a list of libraries to include in any link        # (library names, not filenames: eg. "foo" not "libfoo.a")        self.libraries = []         # 'library_dirs': a list of directories to search for libraries        self.library_dirs = []         # 'runtime_library_dirs': a list of directories to search for        # shared libraries/objects at runtime        self.runtime_library_dirs = []         # 'objects': a list of object files (or similar, such as explicitly        # named library files) to include on any link        self.objects = []         for key in self.executables.keys():            self.set_executable(key, self.executables[key])     # __init__ ()      def set_executables (self, **args):         """Define the executables (and options for them) that will be run        to perform the various stages of compilation.  The exact set of        executables that may be specified here depends on the compiler        class (via the 'executables' class attribute), but most will have:          compiler      the C/C++ compiler          linker_so     linker used to create shared objects and libraries          linker_exe    linker used to create binary executables          archiver      static library creator         On platforms with a command-line (Unix, DOS/Windows), each of these        is a string that will be split into executable name and (optional)        list of arguments.  (Splitting the string is done similarly to how        Unix shells operate: words are delimited by spaces, but quotes and        backslashes can override this.  See        'distutils.util.split_quoted()'.)        """         # Note that some CCompiler implementation classes will define class        # attributes 'cpp', 'cc', etc. with hard-coded executable names;        # this is appropriate when a compiler class is for exactly one        # compiler/OS combination (eg. MSVCCompiler).  Other compiler        # classes (UnixCCompiler, in particular) are driven by information        # discovered at run-time, since there are many different ways to do        # basically the same things with Unix C compilers.         for key in args.keys():            if not self.executables.has_key(key):                raise ValueError, \                      "unknown executable '%s' for class %s" % \                      (key, self.__class__.__name__)            self.set_executable(key, args[key])     # set_executables ()     def set_executable(self, key, value):        if type(value) is StringType:            setattr(self, key, split_quoted(value))        else:            setattr(self, key, value)      def _find_macro (self, name):        i = 0        for defn in self.macros:            if defn[0] == name:                return i            i = i + 1         return None      def _check_macro_definitions (self, definitions):        """Ensures that every element of 'definitions' is a valid macro        definition, ie. either (name,value) 2-tuple or a (name,) tuple.  Do        nothing if all definitions are OK, raise TypeError otherwise.        """        for defn in definitions:            if not (type (defn) is TupleType and                    (len (defn) == 1 or                     (len (defn) == 2 and                      (type (defn[1]) is StringType or defn[1] is None))) and                    type (defn[0]) is StringType):                raise TypeError, \                      ("invalid macro definition '%s': " % defn) + \                      "must be tuple (string,), (string, string), or " + \                      "(string, None)"      # -- Bookkeeping methods -------------------------------------------     def define_macro (self, name, value=None):        """Define a preprocessor macro for all compilations driven by this        compiler object.  The optional parameter 'value' should be a        string; if it is not supplied, then the macro will be defined        without an explicit value and the exact outcome depends on the        compiler used (XXX true? does ANSI say anything about this?)        """        # Delete from the list of macro definitions/undefinitions if        # already there (so that this one will take precedence).        i = self._find_macro (name)        if i is not None:            del self.macros[i]         defn = (name, value)        self.macros.append (defn)      def undefine_macro (self, name):        """Undefine a preprocessor macro for all compilations driven by        this compiler object.  If the same macro is defined by        'define_macro()' and undefined by 'undefine_macro()' the last call        takes precedence (including multiple redefinitions or        undefinitions).  If the macro is redefined/undefined on a        per-compilation basis (ie. in the call to 'compile()'), then that        takes precedence.        """        # Delete from the list of macro definitions/undefinitions if        # already there (so that this one will take precedence).        i = self._find_macro (name)        if i is not None:            del self.macros[i]         undefn = (name,)        self.macros.append (undefn)      def add_include_dir (self, dir):        """Add 'dir' to the list of directories that will be searched for        header files.  The compiler is instructed to search directories in        the order in which they are supplied by successive calls to        'add_include_dir()'.        """        self.include_dirs.append (dir)     def set_include_dirs (self, dirs):        """Set the list of directories that will be searched to 'dirs' (a        list of strings).  Overrides any preceding calls to        'add_include_dir()'; subsequence calls to 'add_include_dir()' add        to the list passed to 'set_include_dirs()'.  This does not affect        any list of standard include directories that the compiler may        search by default.        """        self.include_dirs = copy (dirs)      def add_library (self, libname):        """Add 'libname' to the list of libraries that will be included in        all links driven by this compiler object.  Note that 'libname'        should *not* be the name of a file containing a library, but the        name of the library itself: the actual filename will be inferred by        the linker, the compiler, or the compiler class (depending on the        platform).         The linker will be instructed to link against libraries in the        order they were supplied to 'add_library()' and/or        'set_libraries()'.  It is perfectly valid to duplicate library        names; the linker will be instructed to link against libraries as        many times as they are mentioned.        """        self.libraries.append (libname)     def set_libraries (self, libnames):        """Set the list of libraries to be included in all links driven by        this compiler object to 'libnames' (a list of strings).  This does        not affect any standard system libraries that the linker may        include by default.        """        self.libraries = copy (libnames)      def add_library_dir (self, dir):        """Add 'dir' to the list of directories that will be searched for        libraries specified to 'add_library()' and 'set_libraries()'.  The        linker will be instructed to search for libraries in the order they        are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.        """        self.library_dirs.append (dir)     def set_library_dirs (self, dirs):        """Set the list of library search directories to 'dirs' (a list of        strings).  This does not affect any standard library search path        that the linker may search by default.        """        self.library_dirs = copy (dirs)      def add_runtime_library_dir (self, dir):        """Add 'dir' to the list of directories that will be searched for        shared libraries at runtime.        """        self.runtime_library_dirs.append (dir)     def set_runtime_library_dirs (self, dirs):        """Set the list of directories to search for shared libraries at        runtime to 'dirs' (a list of strings).  This does not affect any        standard search path that the runtime linker may search by        default.        """        self.runtime_library_dirs = copy (dirs)      def add_link_object (self, object):        """Add 'object' to the list of object files (or analogues, such as        explicitly named library files or the output of "resource        compilers") to be included in every link driven by this compiler        object.        """        self.objects.append (object)     def set_link_objects (self, objects):        """Set the list of object files (or analogues) to be included in        every link to 'objects'.  This does not affect any standard object        files that the linker may include by default (such as system        libraries).        """        self.objects = copy (objects)      # -- Private utility methods --------------------------------------    # (here for the convenience of subclasses)     # Helper method to prep compiler in subclass compile() methods     def _setup_compile(self, outdir, macros, incdirs, sources, depends,                       extra):        """Process arguments and decide which source files to compile.         Merges _fix_compile_args() and _prep_compile().        """        if outdir is None:            outdir = self.output_dir        elif type(outdir) is not StringType:            raise TypeError, "'output_dir' must be a string or None"         if macros is None:            macros = self.macros        elif type(macros) is ListType:            macros = macros + (self.macros or [])        else:            raise TypeError, "'macros' (if supplied) must be a list of tuples"         if incdirs is None:            incdirs = self.include_dirs        elif type(incdirs) in (ListType, TupleType):            incdirs = list(incdirs) + (self.include_dirs or [])        else:            raise TypeError, \                  "'include_dirs' (if supplied) must be a list of strings"         if extra is None:            extra = []         # Get the list of expected output (object) files        objects = self.object_filenames(sources,                                        strip_dir=0,                                        output_dir=outdir)        assert len(objects) == len(sources)         # XXX should redo this code to eliminate skip_source entirely.        # XXX instead create build and issue skip messages inline         if self.force:            skip_source = {}            # rebuild everything            for source in sources:                skip_source[source] = 0        elif depends is None:            # If depends is None, figure out which source files we            # have to recompile according to a simplistic check. We            # just compare the source and object file, no deep            # dependency checking involving header files.            skip_source = {}            # rebuild everything            for source in sources:      # no wait, rebuild nothing                skip_source[source] = 1             n_sources, n_objects = newer_pairwise(sources, objects)            for source in n_sources:    # no really, only rebuild what's                skip_source[source] = 0 # out-of-date        else:            # If depends is a list of files, then do a different            # simplistic check.  Assume that each object depends on            # its source and all files in the depends list.            skip_source = {}            # L contains all the depends plus a spot at the end for a            # particular source file            L = depends[:] + [None]            for i in range(len(objects)):                source = sources[i]                L[-1] = source                if newer_group(L, objects[i]):                    skip_source[source] = 0                else:                    skip_source[source] = 1         pp_opts = gen_preprocess_options(macros, incdirs)         build = {}        for i in range(len(sources)):            src = sources[i]            obj = objects[i]            ext = os.path.splitext(src)[1]            self.mkpath(os.path.dirname(obj))            if skip_source[src]:                log.debug("skipping %s (%s up-to-date)", src, obj)            else:                build[obj] = src, ext         return macros, objects, extra, pp_opts, build     def _get_cc_args(self, pp_opts, debug, before):        # works for unixccompiler, emxccompiler, cygwinccompiler        cc_args = pp_opts + ['-c']        if debug:            cc_args[:0] = ['-g']        if before:            cc_args[:0] = before        return cc_args     def _fix_compile_args (self, output_dir, macros, include_dirs):        """Typecheck and fix-up some of the arguments to the 'compile()'        method, and return fixed-up values.  Specifically: if 'output_dir'        is None, replaces it with 'self.output_dir'; ensures that 'macros'        is a list, and augments it with 'self.macros'; ensures that        'include_dirs' is a list, and augments it with 'self.include_dirs'.        Guarantees that the returned values are of the correct type,        i.e. for 'output_dir' either string or None, and for 'macros' and        'include_dirs' either list or None.        """        if output_dir is None:            output_dir = self.output_dir        elif type (output_dir) is not StringType:            raise TypeError, "'output_dir' must be a string or None"         if macros is None:            macros = self.macros        elif type (macros) is ListType:            macros = macros + (self.macros or [])        else:            raise TypeError, "'macros' (if supplied) must be a list of tuples"         if include_dirs is None:            include_dirs = self.include_dirs        elif type (include_dirs) in (ListType, TupleType):            include_dirs = list (include_dirs) + (self.include_dirs or [])        else:            raise TypeError, \                  "'include_dirs' (if supplied) must be a list of strings"         return output_dir, macros, include_dirs     # _fix_compile_args ()      def _prep_compile(self, sources, output_dir, depends=None):        """Decide which souce files must be recompiled.         Determine the list of object files corresponding to 'sources',        and figure out which ones really need to be recompiled.        Return a list of all object files and a dictionary telling        which source files can be skipped.        """        # Get the list of expected output (object) files        objects = self.object_filenames(sources, output_dir=output_dir)        assert len(objects) == len(sources)         if self.force:            skip_source = {}            # rebuild everything            for source in sources:                skip_source[source] = 0        elif depends is None:            # If depends is None, figure out which source files we            # have to recompile according to a simplistic check. We            # just compare the source and object file, no deep            # dependency checking involving header files.            skip_source = {}            # rebuild everything            for source in sources:      # no wait, rebuild nothing                skip_source[source] = 1             n_sources, n_objects = newer_pairwise(sources, objects)            for source in n_sources:    # no really, only rebuild what's                skip_source[source] = 0 # out-of-date        else:            # If depends is a list of files, then do a different            # simplistic check.  Assume that each object depends on            # its source and all files in the depends list.            skip_source = {}

Lines 1–500 of 1268.