source: trunk/essentials/dev-lang/python/Lib/distutils/ccompiler.py

Last change on this file was 3436, checked in by bird, 19 years ago

oops.

File size: 50.8 KB
Line 
1"""distutils.ccompiler
2
3Contains CCompiler, an abstract base class that defines the interface
4for the Distutils compiler abstraction model."""
5
6# This module should be kept compatible with Python 2.1.
7
8__revision__ = "$Id: ccompiler.py 46331 2006-05-26 14:07:23Z bob.ippolito $"
9
10import sys, os, re
11from types import *
12from copy import copy
13from distutils.errors import *
14from distutils.spawn import spawn
15from distutils.file_util import move_file
16from distutils.dir_util import mkpath
17from distutils.dep_util import newer_pairwise, newer_group
18from distutils.util import split_quoted, execute
19from distutils import log
20
21class CCompiler:
22 """Abstract base class to define the interface that must be implemented
23 by real compiler classes. Also has some utility methods used by
24 several compiler classes.
25
26 The basic idea behind a compiler abstraction class is that each
27 instance can be used for all the compile/link steps in building a
28 single project. Thus, attributes common to all of those compile and
29 link steps -- include directories, macros to define, libraries to link
30 against, etc. -- are attributes of the compiler instance. To allow for
31 variability in how individual files are treated, most of those
32 attributes may be varied on a per-compilation or per-link basis.
33 """
34
35 # 'compiler_type' is a class attribute that identifies this class. It
36 # keeps code that wants to know what kind of compiler it's dealing with
37 # from having to import all possible compiler classes just to do an
38 # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type'
39 # should really, really be one of the keys of the 'compiler_class'
40 # dictionary (see below -- used by the 'new_compiler()' factory
41 # function) -- authors of new compiler interface classes are
42 # responsible for updating 'compiler_class'!
43 compiler_type = None
44
45 # XXX things not handled by this compiler abstraction model:
46 # * client can't provide additional options for a compiler,
47 # e.g. warning, optimization, debugging flags. Perhaps this
48 # should be the domain of concrete compiler abstraction classes
49 # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
50 # class should have methods for the common ones.
51 # * can't completely override the include or library searchg
52 # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
53 # I'm not sure how widely supported this is even by Unix
54 # compilers, much less on other platforms. And I'm even less
55 # sure how useful it is; maybe for cross-compiling, but
56 # support for that is a ways off. (And anyways, cross
57 # compilers probably have a dedicated binary with the
58 # right paths compiled in. I hope.)
59 # * can't do really freaky things with the library list/library
60 # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
61 # different versions of libfoo.a in different locations. I
62 # think this is useless without the ability to null out the
63 # library search path anyways.
64
65
66 # Subclasses that rely on the standard filename generation methods
67 # implemented below should override these; see the comment near
68 # those methods ('object_filenames()' et. al.) for details:
69 src_extensions = None # list of strings
70 obj_extension = None # string
71 static_lib_extension = None
72 shared_lib_extension = None # string
73 static_lib_format = None # format string
74 shared_lib_format = None # prob. same as static_lib_format
75 exe_extension = None # string
76
77 # Default language settings. language_map is used to detect a source
78 # file or Extension target language, checking source filenames.
79 # language_order is used to detect the language precedence, when deciding
80 # what language to use when mixing source types. For example, if some
81 # extension has two files with ".c" extension, and one with ".cpp", it
82 # is still linked as c++.
83 language_map = {".c" : "c",
84 ".cc" : "c++",
85 ".cpp" : "c++",
86 ".cxx" : "c++",
87 ".m" : "objc",
88 }
89 language_order = ["c++", "objc", "c"]
90
91 def __init__ (self,
92 verbose=0,
93 dry_run=0,
94 force=0):
95
96 self.dry_run = dry_run
97 self.force = force
98 self.verbose = verbose
99
100 # 'output_dir': a common output directory for object, library,
101 # shared object, and shared library files
102 self.output_dir = None
103
104 # 'macros': a list of macro definitions (or undefinitions). A
105 # macro definition is a 2-tuple (name, value), where the value is
106 # either a string or None (no explicit value). A macro
107 # undefinition is a 1-tuple (name,).
108 self.macros = []
109
110 # 'include_dirs': a list of directories to search for include files
111 self.include_dirs = []
112
113 # 'libraries': a list of libraries to include in any link
114 # (library names, not filenames: eg. "foo" not "libfoo.a")
115 self.libraries = []
116
117 # 'library_dirs': a list of directories to search for libraries
118 self.library_dirs = []
119
120 # 'runtime_library_dirs': a list of directories to search for
121 # shared libraries/objects at runtime
122 self.runtime_library_dirs = []
123
124 # 'objects': a list of object files (or similar, such as explicitly
125 # named library files) to include on any link
126 self.objects = []
127
128 for key in self.executables.keys():
129 self.set_executable(key, self.executables[key])
130
131 # __init__ ()
132
133
134 def set_executables (self, **args):
135
136 """Define the executables (and options for them) that will be run
137 to perform the various stages of compilation. The exact set of
138 executables that may be specified here depends on the compiler
139 class (via the 'executables' class attribute), but most will have:
140 compiler the C/C++ compiler
141 linker_so linker used to create shared objects and libraries
142 linker_exe linker used to create binary executables
143 archiver static library creator
144
145 On platforms with a command-line (Unix, DOS/Windows), each of these
146 is a string that will be split into executable name and (optional)
147 list of arguments. (Splitting the string is done similarly to how
148 Unix shells operate: words are delimited by spaces, but quotes and
149 backslashes can override this. See
150 'distutils.util.split_quoted()'.)
151 """
152
153 # Note that some CCompiler implementation classes will define class
154 # attributes 'cpp', 'cc', etc. with hard-coded executable names;
155 # this is appropriate when a compiler class is for exactly one
156 # compiler/OS combination (eg. MSVCCompiler). Other compiler
157 # classes (UnixCCompiler, in particular) are driven by information
158 # discovered at run-time, since there are many different ways to do
159 # basically the same things with Unix C compilers.
160
161 for key in args.keys():
162 if not self.executables.has_key(key):
163 raise ValueError, \
164 "unknown executable '%s' for class %s" % \
165 (key, self.__class__.__name__)
166 self.set_executable(key, args[key])
167
168 # set_executables ()
169
170 def set_executable(self, key, value):
171 if type(value) is StringType:
172 setattr(self, key, split_quoted(value))
173 else:
174 setattr(self, key, value)
175
176
177 def _find_macro (self, name):
178 i = 0
179 for defn in self.macros:
180 if defn[0] == name:
181 return i
182 i = i + 1
183
184 return None
185
186
187 def _check_macro_definitions (self, definitions):
188 """Ensures that every element of 'definitions' is a valid macro
189 definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do
190 nothing if all definitions are OK, raise TypeError otherwise.
191 """
192 for defn in definitions:
193 if not (type (defn) is TupleType and
194 (len (defn) == 1 or
195 (len (defn) == 2 and
196 (type (defn[1]) is StringType or defn[1] is None))) and
197 type (defn[0]) is StringType):
198 raise TypeError, \
199 ("invalid macro definition '%s': " % defn) + \
200 "must be tuple (string,), (string, string), or " + \
201 "(string, None)"
202
203
204 # -- Bookkeeping methods -------------------------------------------
205
206 def define_macro (self, name, value=None):
207 """Define a preprocessor macro for all compilations driven by this
208 compiler object. The optional parameter 'value' should be a
209 string; if it is not supplied, then the macro will be defined
210 without an explicit value and the exact outcome depends on the
211 compiler used (XXX true? does ANSI say anything about this?)
212 """
213 # Delete from the list of macro definitions/undefinitions if
214 # already there (so that this one will take precedence).
215 i = self._find_macro (name)
216 if i is not None:
217 del self.macros[i]
218
219 defn = (name, value)
220 self.macros.append (defn)
221
222
223 def undefine_macro (self, name):
224 """Undefine a preprocessor macro for all compilations driven by
225 this compiler object. If the same macro is defined by
226 'define_macro()' and undefined by 'undefine_macro()' the last call
227 takes precedence (including multiple redefinitions or
228 undefinitions). If the macro is redefined/undefined on a
229 per-compilation basis (ie. in the call to 'compile()'), then that
230 takes precedence.
231 """
232 # Delete from the list of macro definitions/undefinitions if
233 # already there (so that this one will take precedence).
234 i = self._find_macro (name)
235 if i is not None:
236 del self.macros[i]
237
238 undefn = (name,)
239 self.macros.append (undefn)
240
241
242 def add_include_dir (self, dir):
243 """Add 'dir' to the list of directories that will be searched for
244 header files. The compiler is instructed to search directories in
245 the order in which they are supplied by successive calls to
246 'add_include_dir()'.
247 """
248 self.include_dirs.append (dir)
249
250 def set_include_dirs (self, dirs):
251 """Set the list of directories that will be searched to 'dirs' (a
252 list of strings). Overrides any preceding calls to
253 'add_include_dir()'; subsequence calls to 'add_include_dir()' add
254 to the list passed to 'set_include_dirs()'. This does not affect
255 any list of standard include directories that the compiler may
256 search by default.
257 """
258 self.include_dirs = copy (dirs)
259
260
261 def add_library (self, libname):
262 """Add 'libname' to the list of libraries that will be included in
263 all links driven by this compiler object. Note that 'libname'
264 should *not* be the name of a file containing a library, but the
265 name of the library itself: the actual filename will be inferred by
266 the linker, the compiler, or the compiler class (depending on the
267 platform).
268
269 The linker will be instructed to link against libraries in the
270 order they were supplied to 'add_library()' and/or
271 'set_libraries()'. It is perfectly valid to duplicate library
272 names; the linker will be instructed to link against libraries as
273 many times as they are mentioned.
274 """
275 self.libraries.append (libname)
276
277 def set_libraries (self, libnames):
278 """Set the list of libraries to be included in all links driven by
279 this compiler object to 'libnames' (a list of strings). This does
280 not affect any standard system libraries that the linker may
281 include by default.
282 """
283 self.libraries = copy (libnames)
284
285
286 def add_library_dir (self, dir):
287 """Add 'dir' to the list of directories that will be searched for
288 libraries specified to 'add_library()' and 'set_libraries()'. The
289 linker will be instructed to search for libraries in the order they
290 are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
291 """
292 self.library_dirs.append (dir)
293
294 def set_library_dirs (self, dirs):
295 """Set the list of library search directories to 'dirs' (a list of
296 strings). This does not affect any standard library search path
297 that the linker may search by default.
298 """
299 self.library_dirs = copy (dirs)
300
301
302 def add_runtime_library_dir (self, dir):
303 """Add 'dir' to the list of directories that will be searched for
304 shared libraries at runtime.
305 """
306 self.runtime_library_dirs.append (dir)
307
308 def set_runtime_library_dirs (self, dirs):
309 """Set the list of directories to search for shared libraries at
310 runtime to 'dirs' (a list of strings). This does not affect any
311 standard search path that the runtime linker may search by
312 default.
313 """
314 self.runtime_library_dirs = copy (dirs)
315
316
317 def add_link_object (self, object):
318 """Add 'object' to the list of object files (or analogues, such as
319 explicitly named library files or the output of "resource
320 compilers") to be included in every link driven by this compiler
321 object.
322 """
323 self.objects.append (object)
324
325 def set_link_objects (self, objects):
326 """Set the list of object files (or analogues) to be included in
327 every link to 'objects'. This does not affect any standard object
328 files that the linker may include by default (such as system
329 libraries).
330 """
331 self.objects = copy (objects)
332
333
334 # -- Private utility methods --------------------------------------
335 # (here for the convenience of subclasses)
336
337 # Helper method to prep compiler in subclass compile() methods
338
339 def _setup_compile(self, outdir, macros, incdirs, sources, depends,
340 extra):
341 """Process arguments and decide which source files to compile.
342
343 Merges _fix_compile_args() and _prep_compile().
344 """
345 if outdir is None:
346 outdir = self.output_dir
347 elif type(outdir) is not StringType:
348 raise TypeError, "'output_dir' must be a string or None"
349
350 if macros is None:
351 macros = self.macros
352 elif type(macros) is ListType:
353 macros = macros + (self.macros or [])
354 else:
355 raise TypeError, "'macros' (if supplied) must be a list of tuples"
356
357 if incdirs is None:
358 incdirs = self.include_dirs
359 elif type(incdirs) in (ListType, TupleType):
360 incdirs = list(incdirs) + (self.include_dirs or [])
361 else:
362 raise TypeError, \
363 "'include_dirs' (if supplied) must be a list of strings"
364
365 if extra is None:
366 extra = []
367
368 # Get the list of expected output (object) files
369 objects = self.object_filenames(sources,
370 strip_dir=0,
371 output_dir=outdir)
372 assert len(objects) == len(sources)
373
374 # XXX should redo this code to eliminate skip_source entirely.
375 # XXX instead create build and issue skip messages inline
376
377 if self.force:
378 skip_source = {} # rebuild everything
379 for source in sources:
380 skip_source[source] = 0
381 elif depends is None:
382 # If depends is None, figure out which source files we
383 # have to recompile according to a simplistic check. We
384 # just compare the source and object file, no deep
385 # dependency checking involving header files.
386 skip_source = {} # rebuild everything
387 for source in sources: # no wait, rebuild nothing
388 skip_source[source] = 1
389
390 n_sources, n_objects = newer_pairwise(sources, objects)
391 for source in n_sources: # no really, only rebuild what's
392 skip_source[source] = 0 # out-of-date
393 else:
394 # If depends is a list of files, then do a different
395 # simplistic check. Assume that each object depends on
396 # its source and all files in the depends list.
397 skip_source = {}
398 # L contains all the depends plus a spot at the end for a
399 # particular source file
400 L = depends[:] + [None]
401 for i in range(len(objects)):
402 source = sources[i]
403 L[-1] = source
404 if newer_group(L, objects[i]):
405 skip_source[source] = 0
406 else:
407 skip_source[source] = 1
408
409 pp_opts = gen_preprocess_options(macros, incdirs)
410
411 build = {}
412 for i in range(len(sources)):
413 src = sources[i]
414 obj = objects[i]
415 ext = os.path.splitext(src)[1]
416 self.mkpath(os.path.dirname(obj))
417 if skip_source[src]:
418 log.debug("skipping %s (%s up-to-date)", src, obj)
419 else:
420 build[obj] = src, ext
421
422 return macros, objects, extra, pp_opts, build
423
424 def _get_cc_args(self, pp_opts, debug, before):
425 # works for unixccompiler, emxccompiler, cygwinccompiler
426 cc_args = pp_opts + ['-c']
427 if debug:
428 cc_args[:0] = ['-g']
429 if before:
430 cc_args[:0] = before
431 return cc_args
432
433 def _fix_compile_args (self, output_dir, macros, include_dirs):
434 """Typecheck and fix-up some of the arguments to the 'compile()'
435 method, and return fixed-up values. Specifically: if 'output_dir'
436 is None, replaces it with 'self.output_dir'; ensures that 'macros'
437 is a list, and augments it with 'self.macros'; ensures that
438 'include_dirs' is a list, and augments it with 'self.include_dirs'.
439 Guarantees that the returned values are of the correct type,
440 i.e. for 'output_dir' either string or None, and for 'macros' and
441 'include_dirs' either list or None.
442 """
443 if output_dir is None:
444 output_dir = self.output_dir
445 elif type (output_dir) is not StringType:
446 raise TypeError, "'output_dir' must be a string or None"
447
448 if macros is None:
449 macros = self.macros
450 elif type (macros) is ListType:
451 macros = macros + (self.macros or [])
452 else:
453 raise TypeError, "'macros' (if supplied) must be a list of tuples"
454
455 if include_dirs is None:
456 include_dirs = self.include_dirs
457 elif type (include_dirs) in (ListType, TupleType):
458 include_dirs = list (include_dirs) + (self.include_dirs or [])
459 else:
460 raise TypeError, \
461 "'include_dirs' (if supplied) must be a list of strings"
462
463 return output_dir, macros, include_dirs
464
465 # _fix_compile_args ()
466
467
468 def _prep_compile(self, sources, output_dir, depends=None):
469 """Decide which souce files must be recompiled.
470
471 Determine the list of object files corresponding to 'sources',
472 and figure out which ones really need to be recompiled.
473 Return a list of all object files and a dictionary telling
474 which source files can be skipped.
475 """
476 # Get the list of expected output (object) files
477 objects = self.object_filenames(sources, output_dir=output_dir)