blob: 98c4b6847d2fbd9161f60c79ac8247ed82b30db0 [file] [log] [blame]
Tarek Ziade1231a4e2011-05-19 13:07:25 +02001"""Abstract base class for compilers.
2
3This modules contains CCompiler, an abstract base class that defines the
4interface for the compiler abstraction model used by packaging.
5"""
6
7import os
Tarek Ziade1231a4e2011-05-19 13:07:25 +02008from shutil import move
9from packaging import logger
10from packaging.util import split_quoted, execute, newer_group, spawn
11from packaging.errors import (CompileError, LinkError, UnknownFileError)
12from packaging.compiler import gen_preprocess_options
13
14
15class CCompiler:
16 """Abstract base class to define the interface that must be implemented
17 by real compiler classes. Also has some utility methods used by
18 several compiler classes.
19
20 The basic idea behind a compiler abstraction class is that each
21 instance can be used for all the compile/link steps in building a
22 single project. Thus, attributes common to all of those compile and
23 link steps -- include directories, macros to define, libraries to link
24 against, etc. -- are attributes of the compiler instance. To allow for
25 variability in how individual files are treated, most of those
26 attributes may be varied on a per-compilation or per-link basis.
27 """
28
29 # 'name' is a class attribute that identifies this class. It
30 # keeps code that wants to know what kind of compiler it's dealing with
31 # from having to import all possible compiler classes just to do an
32 # 'isinstance'.
33 name = None
34 description = None
35
36 # XXX things not handled by this compiler abstraction model:
37 # * client can't provide additional options for a compiler,
38 # e.g. warning, optimization, debugging flags. Perhaps this
39 # should be the domain of concrete compiler abstraction classes
40 # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
41 # class should have methods for the common ones.
42 # * can't completely override the include or library searchg
43 # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
44 # I'm not sure how widely supported this is even by Unix
45 # compilers, much less on other platforms. And I'm even less
46 # sure how useful it is; maybe for cross-compiling, but
47 # support for that is a ways off. (And anyways, cross
48 # compilers probably have a dedicated binary with the
49 # right paths compiled in. I hope.)
50 # * can't do really freaky things with the library list/library
51 # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
52 # different versions of libfoo.a in different locations. I
53 # think this is useless without the ability to null out the
54 # library search path anyways.
55
56
57 # Subclasses that rely on the standard filename generation methods
58 # implemented below should override these; see the comment near
59 # those methods ('object_filenames()' et. al.) for details:
60 src_extensions = None # list of strings
61 obj_extension = None # string
62 static_lib_extension = None
63 shared_lib_extension = None # string
64 static_lib_format = None # format string
65 shared_lib_format = None # prob. same as static_lib_format
66 exe_extension = None # string
67
68 # Default language settings. language_map is used to detect a source
69 # file or Extension target language, checking source filenames.
70 # language_order is used to detect the language precedence, when deciding
71 # what language to use when mixing source types. For example, if some
72 # extension has two files with ".c" extension, and one with ".cpp", it
73 # is still linked as c++.
74 language_map = {".c": "c",
75 ".cc": "c++",
76 ".cpp": "c++",
77 ".cxx": "c++",
78 ".m": "objc",
79 }
80 language_order = ["c++", "objc", "c"]
81
Éric Araujo4d155462011-11-15 11:43:20 +010082 def __init__(self, dry_run=False, force=False):
Tarek Ziade1231a4e2011-05-19 13:07:25 +020083 self.dry_run = dry_run
84 self.force = force
Tarek Ziade1231a4e2011-05-19 13:07:25 +020085
86 # 'output_dir': a common output directory for object, library,
87 # shared object, and shared library files
88 self.output_dir = None
89
90 # 'macros': a list of macro definitions (or undefinitions). A
91 # macro definition is a 2-tuple (name, value), where the value is
92 # either a string or None (no explicit value). A macro
93 # undefinition is a 1-tuple (name,).
94 self.macros = []
95
96 # 'include_dirs': a list of directories to search for include files
97 self.include_dirs = []
98
99 # 'libraries': a list of libraries to include in any link
100 # (library names, not filenames: eg. "foo" not "libfoo.a")
101 self.libraries = []
102
103 # 'library_dirs': a list of directories to search for libraries
104 self.library_dirs = []
105
106 # 'runtime_library_dirs': a list of directories to search for
107 # shared libraries/objects at runtime
108 self.runtime_library_dirs = []
109
110 # 'objects': a list of object files (or similar, such as explicitly
111 # named library files) to include on any link
112 self.objects = []
113
114 for key, value in self.executables.items():
115 self.set_executable(key, value)
116
117 def set_executables(self, **args):
118 """Define the executables (and options for them) that will be run
119 to perform the various stages of compilation. The exact set of
120 executables that may be specified here depends on the compiler
121 class (via the 'executables' class attribute), but most will have:
122 compiler the C/C++ compiler
123 linker_so linker used to create shared objects and libraries
124 linker_exe linker used to create binary executables
125 archiver static library creator
126
127 On platforms with a command line (Unix, DOS/Windows), each of these
128 is a string that will be split into executable name and (optional)
129 list of arguments. (Splitting the string is done similarly to how
130 Unix shells operate: words are delimited by spaces, but quotes and
131 backslashes can override this. See
132 'distutils.util.split_quoted()'.)
133 """
134
135 # Note that some CCompiler implementation classes will define class
136 # attributes 'cpp', 'cc', etc. with hard-coded executable names;
137 # this is appropriate when a compiler class is for exactly one
138 # compiler/OS combination (eg. MSVCCompiler). Other compiler
139 # classes (UnixCCompiler, in particular) are driven by information
140 # discovered at run-time, since there are many different ways to do
141 # basically the same things with Unix C compilers.
142
143 for key, value in args.items():
144 if key not in self.executables:
145 raise ValueError("unknown executable '%s' for class %s" % \
146 (key, self.__class__.__name__))
147 self.set_executable(key, value)
148
149 def set_executable(self, key, value):
150 if isinstance(value, str):
151 setattr(self, key, split_quoted(value))
152 else:
153 setattr(self, key, value)
154
155 def _find_macro(self, name):
156 i = 0
157 for defn in self.macros:
158 if defn[0] == name:
159 return i
160 i = i + 1
161 return None
162
163 def _check_macro_definitions(self, definitions):
164 """Ensures that every element of 'definitions' is a valid macro
165 definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do
166 nothing if all definitions are OK, raise TypeError otherwise.
167 """
168 for defn in definitions:
169 if not (isinstance(defn, tuple) and
170 (len(defn) == 1 or
171 (len(defn) == 2 and
172 (isinstance(defn[1], str) or defn[1] is None))) and
173 isinstance(defn[0], str)):
174 raise TypeError(("invalid macro definition '%s': " % defn) + \
175 "must be tuple (string,), (string, string), or " + \
176 "(string, None)")
177
178
179 # -- Bookkeeping methods -------------------------------------------
180
181 def define_macro(self, name, value=None):
182 """Define a preprocessor macro for all compilations driven by this
183 compiler object. The optional parameter 'value' should be a
184 string; if it is not supplied, then the macro will be defined
185 without an explicit value and the exact outcome depends on the
186 compiler used (XXX true? does ANSI say anything about this?)
187 """
188 # Delete from the list of macro definitions/undefinitions if
189 # already there (so that this one will take precedence).
190 i = self._find_macro(name)
191 if i is not None:
192 del self.macros[i]
193
194 defn = (name, value)
195 self.macros.append(defn)
196
197 def undefine_macro(self, name):
198 """Undefine a preprocessor macro for all compilations driven by
199 this compiler object. If the same macro is defined by
200 'define_macro()' and undefined by 'undefine_macro()' the last call
201 takes precedence (including multiple redefinitions or
202 undefinitions). If the macro is redefined/undefined on a
203 per-compilation basis (ie. in the call to 'compile()'), then that
204 takes precedence.
205 """
206 # Delete from the list of macro definitions/undefinitions if
207 # already there (so that this one will take precedence).
208 i = self._find_macro(name)
209 if i is not None:
210 del self.macros[i]
211
212 undefn = (name,)
213 self.macros.append(undefn)
214
215 def add_include_dir(self, dir):
216 """Add 'dir' to the list of directories that will be searched for
217 header files. The compiler is instructed to search directories in
218 the order in which they are supplied by successive calls to
219 'add_include_dir()'.
220 """
221 self.include_dirs.append(dir)
222
223 def set_include_dirs(self, dirs):
224 """Set the list of directories that will be searched to 'dirs' (a
225 list of strings). Overrides any preceding calls to
226 'add_include_dir()'; subsequence calls to 'add_include_dir()' add
227 to the list passed to 'set_include_dirs()'. This does not affect
228 any list of standard include directories that the compiler may
229 search by default.
230 """
231 self.include_dirs = dirs[:]
232
233 def add_library(self, libname):
234 """Add 'libname' to the list of libraries that will be included in
235 all links driven by this compiler object. Note that 'libname'
236 should *not* be the name of a file containing a library, but the
237 name of the library itself: the actual filename will be inferred by
238 the linker, the compiler, or the compiler class (depending on the
239 platform).
240
241 The linker will be instructed to link against libraries in the
242 order they were supplied to 'add_library()' and/or
243 'set_libraries()'. It is perfectly valid to duplicate library
244 names; the linker will be instructed to link against libraries as
245 many times as they are mentioned.
246 """
247 self.libraries.append(libname)
248
249 def set_libraries(self, libnames):
250 """Set the list of libraries to be included in all links driven by
251 this compiler object to 'libnames' (a list of strings). This does
252 not affect any standard system libraries that the linker may
253 include by default.
254 """
255 self.libraries = libnames[:]
256
257
258 def add_library_dir(self, dir):
259 """Add 'dir' to the list of directories that will be searched for
260 libraries specified to 'add_library()' and 'set_libraries()'. The
261 linker will be instructed to search for libraries in the order they
262 are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
263 """
264 self.library_dirs.append(dir)
265
266 def set_library_dirs(self, dirs):
267 """Set the list of library search directories to 'dirs' (a list of
268 strings). This does not affect any standard library search path
269 that the linker may search by default.
270 """
271 self.library_dirs = dirs[:]
272
273 def add_runtime_library_dir(self, dir):
274 """Add 'dir' to the list of directories that will be searched for
275 shared libraries at runtime.
276 """
277 self.runtime_library_dirs.append(dir)
278
279 def set_runtime_library_dirs(self, dirs):
280 """Set the list of directories to search for shared libraries at
281 runtime to 'dirs' (a list of strings). This does not affect any
282 standard search path that the runtime linker may search by
283 default.
284 """
285 self.runtime_library_dirs = dirs[:]
286
287 def add_link_object(self, object):
288 """Add 'object' to the list of object files (or analogues, such as
289 explicitly named library files or the output of "resource
290 compilers") to be included in every link driven by this compiler
291 object.
292 """
293 self.objects.append(object)
294
295 def set_link_objects(self, objects):
296 """Set the list of object files (or analogues) to be included in
297 every link to 'objects'. This does not affect any standard object
298 files that the linker may include by default (such as system
299 libraries).
300 """
301 self.objects = objects[:]
302
303
304 # -- Private utility methods --------------------------------------
305 # (here for the convenience of subclasses)
306
307 # Helper method to prep compiler in subclass compile() methods
308 def _setup_compile(self, outdir, macros, incdirs, sources, depends,
309 extra):
310 """Process arguments and decide which source files to compile."""
311 if outdir is None:
312 outdir = self.output_dir
313 elif not isinstance(outdir, str):
314 raise TypeError("'output_dir' must be a string or None")
315
316 if macros is None:
317 macros = self.macros
318 elif isinstance(macros, list):
319 macros = macros + (self.macros or [])
320 else:
321 raise TypeError("'macros' (if supplied) must be a list of tuples")
322
323 if incdirs is None:
324 incdirs = self.include_dirs
325 elif isinstance(incdirs, (list, tuple)):
326 incdirs = list(incdirs) + (self.include_dirs or [])
327 else:
328 raise TypeError(
329 "'include_dirs' (if supplied) must be a list of strings")
330
331 if extra is None:
332 extra = []
333
334 # Get the list of expected output (object) files
335 objects = self.object_filenames(sources,
336 strip_dir=False,
337 output_dir=outdir)
338 assert len(objects) == len(sources)
339
340 pp_opts = gen_preprocess_options(macros, incdirs)
341
342 build = {}
343 for i in range(len(sources)):
344 src = sources[i]
345 obj = objects[i]
346 ext = os.path.splitext(src)[1]
347 self.mkpath(os.path.dirname(obj))
348 build[obj] = (src, ext)
349
350 return macros, objects, extra, pp_opts, build
351
352 def _get_cc_args(self, pp_opts, debug, before):
Éric Araujo25987d02011-06-01 15:20:44 +0200353 # works for unixccompiler and cygwinccompiler
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200354 cc_args = pp_opts + ['-c']
355 if debug:
356 cc_args[:0] = ['-g']
357 if before:
358 cc_args[:0] = before
359 return cc_args
360
361 def _fix_compile_args(self, output_dir, macros, include_dirs):
362 """Typecheck and fix-up some of the arguments to the 'compile()'
363 method, and return fixed-up values. Specifically: if 'output_dir'
364 is None, replaces it with 'self.output_dir'; ensures that 'macros'
365 is a list, and augments it with 'self.macros'; ensures that
366 'include_dirs' is a list, and augments it with 'self.include_dirs'.
367 Guarantees that the returned values are of the correct type,
368 i.e. for 'output_dir' either string or None, and for 'macros' and
369 'include_dirs' either list or None.
370 """
371 if output_dir is None:
372 output_dir = self.output_dir
373 elif not isinstance(output_dir, str):
374 raise TypeError("'output_dir' must be a string or None")
375
376 if macros is None:
377 macros = self.macros
378 elif isinstance(macros, list):
379 macros = macros + (self.macros or [])
380 else:
381 raise TypeError("'macros' (if supplied) must be a list of tuples")
382
383 if include_dirs is None:
384 include_dirs = self.include_dirs
385 elif isinstance(include_dirs, (list, tuple)):
386 include_dirs = list(include_dirs) + (self.include_dirs or [])
387 else:
388 raise TypeError(
389 "'include_dirs' (if supplied) must be a list of strings")
390
391 return output_dir, macros, include_dirs
392
393 def _fix_object_args(self, objects, output_dir):
394 """Typecheck and fix up some arguments supplied to various methods.
395 Specifically: ensure that 'objects' is a list; if output_dir is
396 None, replace with self.output_dir. Return fixed versions of
397 'objects' and 'output_dir'.
398 """
399 if not isinstance(objects, (list, tuple)):
400 raise TypeError("'objects' must be a list or tuple of strings")
401 objects = list(objects)
402
403 if output_dir is None:
404 output_dir = self.output_dir
405 elif not isinstance(output_dir, str):
406 raise TypeError("'output_dir' must be a string or None")
407
408 return objects, output_dir
409
410 def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
411 """Typecheck and fix up some of the arguments supplied to the
412 'link_*' methods. Specifically: ensure that all arguments are
413 lists, and augment them with their permanent versions
414 (eg. 'self.libraries' augments 'libraries'). Return a tuple with
415 fixed versions of all arguments.
416 """
417 if libraries is None:
418 libraries = self.libraries
419 elif isinstance(libraries, (list, tuple)):
420 libraries = list(libraries) + (self.libraries or [])
421 else:
422 raise TypeError(
423 "'libraries' (if supplied) must be a list of strings")
424
425 if library_dirs is None:
426 library_dirs = self.library_dirs
427 elif isinstance(library_dirs, (list, tuple)):
428 library_dirs = list(library_dirs) + (self.library_dirs or [])
429 else:
430 raise TypeError(
431 "'library_dirs' (if supplied) must be a list of strings")
432
433 if runtime_library_dirs is None:
434 runtime_library_dirs = self.runtime_library_dirs
435 elif isinstance(runtime_library_dirs, (list, tuple)):
436 runtime_library_dirs = (list(runtime_library_dirs) +
437 (self.runtime_library_dirs or []))
438 else:
439 raise TypeError("'runtime_library_dirs' (if supplied) "
440 "must be a list of strings")
441
442 return libraries, library_dirs, runtime_library_dirs
443
444 def _need_link(self, objects, output_file):
445 """Return true if we need to relink the files listed in 'objects'
446 to recreate 'output_file'.
447 """
448 if self.force:
449 return True
450 else:
451 if self.dry_run:
452 newer = newer_group(objects, output_file, missing='newer')
453 else:
454 newer = newer_group(objects, output_file)
455 return newer
456
457 def detect_language(self, sources):
458 """Detect the language of a given file, or list of files. Uses
459 language_map, and language_order to do the job.
460 """
461 if not isinstance(sources, list):
462 sources = [sources]
463 lang = None
464 index = len(self.language_order)
465 for source in sources:
466 base, ext = os.path.splitext(source)
467 extlang = self.language_map.get(ext)
468 try:
469 extindex = self.language_order.index(extlang)
470 if extindex < index:
471 lang = extlang
472 index = extindex
473 except ValueError:
474 pass
475 return lang
476
477 # -- Worker methods ------------------------------------------------
478 # (must be implemented by subclasses)
479
480 def preprocess(self, source, output_file=None, macros=None,
481 include_dirs=None, extra_preargs=None, extra_postargs=None):
482 """Preprocess a single C/C++ source file, named in 'source'.
483 Output will be written to file named 'output_file', or stdout if
484 'output_file' not supplied. 'macros' is a list of macro
485 definitions as for 'compile()', which will augment the macros set
486 with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a
487 list of directory names that will be added to the default list.
488
489 Raises PreprocessError on failure.
490 """
491 pass
492
493 def compile(self, sources, output_dir=None, macros=None,
494 include_dirs=None, debug=False, extra_preargs=None,
495 extra_postargs=None, depends=None):
496 """Compile one or more source files.
497
498 'sources' must be a list of filenames, most likely C/C++
499 files, but in reality anything that can be handled by a
500 particular compiler and compiler class (eg. MSVCCompiler can
501 handle resource files in 'sources'). Return a list of object
502 filenames, one per source filename in 'sources'. Depending on
503 the implementation, not all source files will necessarily be
504 compiled, but all corresponding object filenames will be
505 returned.
506
507 If 'output_dir' is given, object files will be put under it, while
508 retaining their original path component. That is, "foo/bar.c"
509 normally compiles to "foo/bar.o" (for a Unix implementation); if
510 'output_dir' is "build", then it would compile to
511 "build/foo/bar.o".
512
513 'macros', if given, must be a list of macro definitions. A macro
514 definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
515 The former defines a macro; if the value is None, the macro is
516 defined without an explicit value. The 1-tuple case undefines a
517 macro. Later definitions/redefinitions/ undefinitions take
518 precedence.
519
520 'include_dirs', if given, must be a list of strings, the
521 directories to add to the default include file search path for this
522 compilation only.
523
524 'debug' is a boolean; if true, the compiler will be instructed to
525 output debug symbols in (or alongside) the object file(s).
526
527 'extra_preargs' and 'extra_postargs' are implementation- dependent.
528 On platforms that have the notion of a command line (e.g. Unix,
529 DOS/Windows), they are most likely lists of strings: extra
530 command-line arguments to prepand/append to the compiler command
531 line. On other platforms, consult the implementation class
532 documentation. In any event, they are intended as an escape hatch
533 for those occasions when the abstract compiler framework doesn't
534 cut the mustard.
535
536 'depends', if given, is a list of filenames that all targets
537 depend on. If a source file is older than any file in
538 depends, then the source file will be recompiled. This
539 supports dependency tracking, but only at a coarse
540 granularity.
541
542 Raises CompileError on failure.
543 """
544 # A concrete compiler class can either override this method
545 # entirely or implement _compile().
546
547 macros, objects, extra_postargs, pp_opts, build = \
548 self._setup_compile(output_dir, macros, include_dirs, sources,
549 depends, extra_postargs)
550 cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
551
552 for obj in objects:
553 try:
554 src, ext = build[obj]
555 except KeyError:
556 continue
557 self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
558
559 # Return *all* object filenames, not just the ones we just built.
560 return objects
561
562 def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
563 """Compile 'src' to product 'obj'."""
564
565 # A concrete compiler class that does not override compile()
566 # should implement _compile().
567 pass
568
569 def create_static_lib(self, objects, output_libname, output_dir=None,
570 debug=False, target_lang=None):
571 """Link a bunch of stuff together to create a static library file.
572 The "bunch of stuff" consists of the list of object files supplied
573 as 'objects', the extra object files supplied to
574 'add_link_object()' and/or 'set_link_objects()', the libraries
575 supplied to 'add_library()' and/or 'set_libraries()', and the
576 libraries supplied as 'libraries' (if any).
577
578 'output_libname' should be a library name, not a filename; the
579 filename will be inferred from the library name. 'output_dir' is
580 the directory where the library file will be put.
581
582 'debug' is a boolean; if true, debugging information will be
583 included in the library (note that on most platforms, it is the
584 compile step where this matters: the 'debug' flag is included here
585 just for consistency).
586
587 'target_lang' is the target language for which the given objects
588 are being compiled. This allows specific linkage time treatment of
589 certain languages.
590
591 Raises LibError on failure.
592 """
593 pass
594
595 # values for target_desc parameter in link()
596 SHARED_OBJECT = "shared_object"
597 SHARED_LIBRARY = "shared_library"
598 EXECUTABLE = "executable"
599
600 def link(self, target_desc, objects, output_filename, output_dir=None,
601 libraries=None, library_dirs=None, runtime_library_dirs=None,
602 export_symbols=None, debug=False, extra_preargs=None,
603 extra_postargs=None, build_temp=None, target_lang=None):
604 """Link a bunch of stuff together to create an executable or
605 shared library file.
606
607 The "bunch of stuff" consists of the list of object files supplied
608 as 'objects'. 'output_filename' should be a filename. If
609 'output_dir' is supplied, 'output_filename' is relative to it
610 (i.e. 'output_filename' can provide directory components if
611 needed).
612
613 'libraries' is a list of libraries to link against. These are
614 library names, not filenames, since they're translated into
615 filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
616 on Unix and "foo.lib" on DOS/Windows). However, they can include a
617 directory component, which means the linker will look in that
618 specific directory rather than searching all the normal locations.
619
620 'library_dirs', if supplied, should be a list of directories to
621 search for libraries that were specified as bare library names
622 (ie. no directory component). These are on top of the system
623 default and those supplied to 'add_library_dir()' and/or
624 'set_library_dirs()'. 'runtime_library_dirs' is a list of
625 directories that will be embedded into the shared library and used
626 to search for other shared libraries that *it* depends on at
627 run-time. (This may only be relevant on Unix.)
628
629 'export_symbols' is a list of symbols that the shared library will
630 export. (This appears to be relevant only on Windows.)
631
632 'debug' is as for 'compile()' and 'create_static_lib()', with the
633 slight distinction that it actually matters on most platforms (as
634 opposed to 'create_static_lib()', which includes a 'debug' flag
635 mostly for form's sake).
636
637 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
638 of course that they supply command-line arguments for the
639 particular linker being used).
640
641 'target_lang' is the target language for which the given objects
642 are being compiled. This allows specific linkage time treatment of
643 certain languages.
644
645 Raises LinkError on failure.
646 """
647 raise NotImplementedError
648
649
650 # Old 'link_*()' methods, rewritten to use the new 'link()' method.
651
652 def link_shared_lib(self, objects, output_libname, output_dir=None,
653 libraries=None, library_dirs=None,
654 runtime_library_dirs=None, export_symbols=None,
655 debug=False, extra_preargs=None, extra_postargs=None,
656 build_temp=None, target_lang=None):
657 self.link(CCompiler.SHARED_LIBRARY, objects,
658 self.library_filename(output_libname, lib_type='shared'),
659 output_dir,
660 libraries, library_dirs, runtime_library_dirs,
661 export_symbols, debug,
662 extra_preargs, extra_postargs, build_temp, target_lang)
663
664 def link_shared_object(self, objects, output_filename, output_dir=None,
665 libraries=None, library_dirs=None,
666 runtime_library_dirs=None, export_symbols=None,
667 debug=False, extra_preargs=None, extra_postargs=None,
668 build_temp=None, target_lang=None):
669 self.link(CCompiler.SHARED_OBJECT, objects,
670 output_filename, output_dir,
671 libraries, library_dirs, runtime_library_dirs,
672 export_symbols, debug,
673 extra_preargs, extra_postargs, build_temp, target_lang)
674
675 def link_executable(self, objects, output_progname, output_dir=None,
676 libraries=None, library_dirs=None,
677 runtime_library_dirs=None, debug=False,
678 extra_preargs=None, extra_postargs=None,
679 target_lang=None):
680 self.link(CCompiler.EXECUTABLE, objects,
681 self.executable_filename(output_progname), output_dir,
682 libraries, library_dirs, runtime_library_dirs, None,
683 debug, extra_preargs, extra_postargs, None, target_lang)
684
685
686 # -- Miscellaneous methods -----------------------------------------
687 # These are all used by the 'gen_lib_options() function; there is
688 # no appropriate default implementation so subclasses should
689 # implement all of these.
690
691 def library_dir_option(self, dir):
692 """Return the compiler option to add 'dir' to the list of
693 directories searched for libraries.
694 """
695 raise NotImplementedError
696
697 def runtime_library_dir_option(self, dir):
698 """Return the compiler option to add 'dir' to the list of
699 directories searched for runtime libraries.
700 """
701 raise NotImplementedError
702
703 def library_option(self, lib):
704 """Return the compiler option to add 'dir' to the list of libraries
705 linked into the shared library or executable.
706 """
707 raise NotImplementedError
708
709 def has_function(self, funcname, includes=None, include_dirs=None,
710 libraries=None, library_dirs=None):
711 """Return a boolean indicating whether funcname is supported on
712 the current platform. The optional arguments can be used to
713 augment the compilation environment.
714 """
715
716 # this can't be included at module scope because it tries to
717 # import math which might not be available at that point - maybe
718 # the necessary logic should just be inlined?
719 import tempfile
720 if includes is None:
721 includes = []
722 if include_dirs is None:
723 include_dirs = []
724 if libraries is None:
725 libraries = []
726 if library_dirs is None:
727 library_dirs = []
728 fd, fname = tempfile.mkstemp(".c", funcname, text=True)
Victor Stinner21a9c742011-05-19 15:51:27 +0200729 with os.fdopen(fd, "w") as f:
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200730 for incl in includes:
731 f.write("""#include "%s"\n""" % incl)
732 f.write("""\
733main (int argc, char **argv) {
734 %s();
735}
736""" % funcname)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200737 try:
738 objects = self.compile([fname], include_dirs=include_dirs)
739 except CompileError:
740 return False
741
742 try:
743 self.link_executable(objects, "a.out",
744 libraries=libraries,
745 library_dirs=library_dirs)
746 except (LinkError, TypeError):
747 return False
748 return True
749
750 def find_library_file(self, dirs, lib, debug=False):
751 """Search the specified list of directories for a static or shared
752 library file 'lib' and return the full path to that file. If
753 'debug' is true, look for a debugging version (if that makes sense on
754 the current platform). Return None if 'lib' wasn't found in any of
755 the specified directories.
756 """
757 raise NotImplementedError
758
759 # -- Filename generation methods -----------------------------------
760
761 # The default implementation of the filename generating methods are
762 # prejudiced towards the Unix/DOS/Windows view of the world:
763 # * object files are named by replacing the source file extension
764 # (eg. .c/.cpp -> .o/.obj)
765 # * library files (shared or static) are named by plugging the
766 # library name and extension into a format string, eg.
767 # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
768 # * executables are named by appending an extension (possibly
769 # empty) to the program name: eg. progname + ".exe" for
770 # Windows
771 #
772 # To reduce redundant code, these methods expect to find
773 # several attributes in the current object (presumably defined
774 # as class attributes):
775 # * src_extensions -
776 # list of C/C++ source file extensions, eg. ['.c', '.cpp']
777 # * obj_extension -
778 # object file extension, eg. '.o' or '.obj'
779 # * static_lib_extension -
780 # extension for static library files, eg. '.a' or '.lib'
781 # * shared_lib_extension -
782 # extension for shared library/object files, eg. '.so', '.dll'
783 # * static_lib_format -
784 # format string for generating static library filenames,
785 # eg. 'lib%s.%s' or '%s.%s'
786 # * shared_lib_format
787 # format string for generating shared library filenames
788 # (probably same as static_lib_format, since the extension
789 # is one of the intended parameters to the format string)
790 # * exe_extension -
791 # extension for executable files, eg. '' or '.exe'
792
793 def object_filenames(self, source_filenames, strip_dir=False, output_dir=''):
794 if output_dir is None:
795 output_dir = ''
796 obj_names = []
797 for src_name in source_filenames:
798 base, ext = os.path.splitext(src_name)
799 base = os.path.splitdrive(base)[1] # Chop off the drive
800 base = base[os.path.isabs(base):] # If abs, chop off leading /
801 if ext not in self.src_extensions:
802 raise UnknownFileError("unknown file type '%s' (from '%s')" %
803 (ext, src_name))
804 if strip_dir:
805 base = os.path.basename(base)
806 obj_names.append(os.path.join(output_dir,
807 base + self.obj_extension))
808 return obj_names
809
810 def shared_object_filename(self, basename, strip_dir=False, output_dir=''):
811 assert output_dir is not None
812 if strip_dir:
813 basename = os.path.basename(basename)
814 return os.path.join(output_dir, basename + self.shared_lib_extension)
815
816 def executable_filename(self, basename, strip_dir=False, output_dir=''):
817 assert output_dir is not None
818 if strip_dir:
819 basename = os.path.basename(basename)
820 return os.path.join(output_dir, basename + (self.exe_extension or ''))
821
822 def library_filename(self, libname, lib_type='static', # or 'shared'
823 strip_dir=False, output_dir=''):
824 assert output_dir is not None
825 if lib_type not in ("static", "shared", "dylib"):
826 raise ValueError(
827 "'lib_type' must be 'static', 'shared' or 'dylib'")
828 fmt = getattr(self, lib_type + "_lib_format")
829 ext = getattr(self, lib_type + "_lib_extension")
830
831 dir, base = os.path.split(libname)
832 filename = fmt % (base, ext)
833 if strip_dir:
834 dir = ''
835
836 return os.path.join(output_dir, dir, filename)
837
838
839 # -- Utility methods -----------------------------------------------
840
841 def execute(self, func, args, msg=None, level=1):
842 execute(func, args, msg, self.dry_run)
843
844 def spawn(self, cmd):
845 spawn(cmd, dry_run=self.dry_run)
846
847 def move_file(self, src, dst):
848 logger.info("moving %r to %r", src, dst)
849 if self.dry_run:
850 return
851 return move(src, dst)
852
853 def mkpath(self, name, mode=0o777):
854 name = os.path.normpath(name)
855 if os.path.isdir(name) or name == '':
856 return
857 if self.dry_run:
858 head = ''
859 for part in name.split(os.sep):
860 logger.info("created directory %s%s", head, part)
861 head += part + os.sep
862 return
863 os.makedirs(name, mode)