Merge pull request #772 from drbo/syntax_bugfix
[platform/upstream/ninja.git] / configure.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2001 Google Inc. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 """Script that generates the build.ninja for ninja itself.
18
19 Projects that use ninja themselves should either write a similar script
20 or use a meta-build system that supports Ninja output."""
21
22 from __future__ import print_function
23
24 from optparse import OptionParser
25 import os
26 import pipes
27 import string
28 import subprocess
29 import sys
30
31 sys.path.insert(0, 'misc')
32 import ninja_syntax
33
34
35 class Platform(object):
36     """Represents a host/target platform and its specific build attributes."""
37     def __init__(self, platform):
38         self._platform = platform
39         if self._platform is not None:
40             return
41         self._platform = sys.platform
42         if self._platform.startswith('linux'):
43             self._platform = 'linux'
44         elif self._platform.startswith('freebsd'):
45             self._platform = 'freebsd'
46         elif self._platform.startswith('gnukfreebsd'):
47             self._platform = 'freebsd'
48         elif self._platform.startswith('openbsd'):
49             self._platform = 'openbsd'
50         elif self._platform.startswith('solaris') or self._platform == 'sunos5':
51             self._platform = 'solaris'
52         elif self._platform.startswith('mingw'):
53             self._platform = 'mingw'
54         elif self._platform.startswith('win'):
55             self._platform = 'msvc'
56         elif self._platform.startswith('bitrig'):
57             self._platform = 'bitrig'
58         elif self._platform.startswith('netbsd'):
59             self._platform = 'netbsd'
60
61     @staticmethod
62     def known_platforms():
63       return ['linux', 'darwin', 'freebsd', 'openbsd', 'solaris', 'sunos5',
64               'mingw', 'msvc', 'gnukfreebsd', 'bitrig', 'netbsd']
65
66     def platform(self):
67         return self._platform
68
69     def is_linux(self):
70         return self._platform == 'linux'
71
72     def is_mingw(self):
73         return self._platform == 'mingw'
74
75     def is_msvc(self):
76         return self._platform == 'msvc'
77
78     def msvc_needs_fs(self):
79         popen = subprocess.Popen(['cl', '/nologo', '/?'],
80                                  stdout=subprocess.PIPE,
81                                  stderr=subprocess.PIPE)
82         out, err = popen.communicate()
83         return '/FS ' in str(out)
84
85     def is_windows(self):
86         return self.is_mingw() or self.is_msvc()
87
88     def is_solaris(self):
89         return self._platform == 'solaris'
90
91     def uses_usr_local(self):
92         return self._platform in ('freebsd', 'openbsd', 'bitrig')
93
94     def supports_ppoll(self):
95         return self._platform in ('linux', 'openbsd', 'bitrig')
96
97     def supports_ninja_browse(self):
98         return not self.is_windows() and not self.is_solaris()
99
100
101 class Bootstrap:
102     """API shim for ninja_syntax.Writer that instead runs the commands.
103
104     Used to bootstrap Ninja from scratch.  In --bootstrap mode this
105     class is used to execute all the commands to build an executable.
106     It also proxies all calls to an underlying ninja_syntax.Writer, to
107     behave like non-bootstrap mode.
108     """
109     def __init__(self, writer):
110         self.writer = writer
111         # Map of variable name => expanded variable value.
112         self.vars = {}
113         # Map of rule name => dict of rule attributes.
114         self.rules = {
115             'phony': {}
116         }
117
118     def comment(self, text):
119         return self.writer.comment(text)
120
121     def newline(self):
122         return self.writer.newline()
123
124     def variable(self, key, val):
125         self.vars[key] = self._expand(val)
126         return self.writer.variable(key, val)
127
128     def rule(self, name, **kwargs):
129         self.rules[name] = kwargs
130         return self.writer.rule(name, **kwargs)
131
132     def build(self, outputs, rule, inputs=None, **kwargs):
133         ruleattr = self.rules[rule]
134         cmd = ruleattr.get('command')
135         if cmd is None:  # A phony rule, for example.
136             return
137
138         # Implement just enough of Ninja variable expansion etc. to
139         # make the bootstrap build work.
140         local_vars = {
141             'in': self._expand_paths(inputs),
142             'out': self._expand_paths(outputs)
143         }
144         for key, val in kwargs.get('variables', []):
145             local_vars[key] = ' '.join(ninja_syntax.as_list(val))
146
147         self._run_command(self._expand(cmd, local_vars))
148
149         return self.writer.build(outputs, rule, inputs, **kwargs)
150
151     def default(self, paths):
152         return self.writer.default(paths)
153
154     def _expand_paths(self, paths):
155         """Expand $vars in an array of paths, e.g. from a 'build' block."""
156         paths = ninja_syntax.as_list(paths)
157         return ' '.join(map(self._expand, paths))
158
159     def _expand(self, str, local_vars={}):
160         """Expand $vars in a string."""
161         return ninja_syntax.expand(str, self.vars, local_vars)
162
163     def _run_command(self, cmdline):
164         """Run a subcommand, quietly.  Prints the full command on error."""
165         try:
166             subprocess.check_call(cmdline, shell=True)
167         except subprocess.CalledProcessError, e:
168             print('when running: ', cmdline)
169             raise
170
171
172 parser = OptionParser()
173 profilers = ['gmon', 'pprof']
174 parser.add_option('--bootstrap', action='store_true',
175                   help='bootstrap a ninja binary from nothing')
176 parser.add_option('--platform',
177                   help='target platform (' +
178                        '/'.join(Platform.known_platforms()) + ')',
179                   choices=Platform.known_platforms())
180 parser.add_option('--host',
181                   help='host platform (' +
182                        '/'.join(Platform.known_platforms()) + ')',
183                   choices=Platform.known_platforms())
184 parser.add_option('--debug', action='store_true',
185                   help='enable debugging extras',)
186 parser.add_option('--profile', metavar='TYPE',
187                   choices=profilers,
188                   help='enable profiling (' + '/'.join(profilers) + ')',)
189 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
190 parser.add_option('--with-python', metavar='EXE',
191                   help='use EXE as the Python interpreter',
192                   default=os.path.basename(sys.executable))
193 parser.add_option('--force-pselect', action='store_true',
194                   help='ppoll() is used by default where available, '
195                        'but some platforms may need to use pselect instead',)
196 (options, args) = parser.parse_args()
197 if args:
198     print('ERROR: extra unparsed command-line arguments:', args)
199     sys.exit(1)
200
201 platform = Platform(options.platform)
202 if options.host:
203     host = Platform(options.host)
204 else:
205     host = platform
206
207 BUILD_FILENAME = 'build.ninja'
208 ninja_writer = ninja_syntax.Writer(open(BUILD_FILENAME, 'w'))
209 n = ninja_writer
210
211 if options.bootstrap:
212     # Make the build directory.
213     try:
214         os.mkdir('build')
215     except OSError:
216         pass
217     # Wrap ninja_writer with the Bootstrapper, which also executes the
218     # commands.
219     print('bootstrapping ninja...')
220     n = Bootstrap(n)
221
222 n.comment('This file is used to build ninja itself.')
223 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
224 n.newline()
225
226 n.variable('ninja_required_version', '1.3')
227 n.newline()
228
229 n.comment('The arguments passed to configure.py, for rerunning it.')
230 configure_args = sys.argv[1:]
231 if '--bootstrap' in configure_args:
232     configure_args.remove('--bootstrap')
233 n.variable('configure_args', ' '.join(configure_args))
234 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
235 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
236 if configure_env:
237     config_str = ' '.join([k + '=' + pipes.quote(configure_env[k])
238                            for k in configure_env])
239     n.variable('configure_env', config_str + '$ ')
240 n.newline()
241
242 CXX = configure_env.get('CXX', 'g++')
243 objext = '.o'
244 if platform.is_msvc():
245     CXX = 'cl'
246     objext = '.obj'
247
248 def src(filename):
249     return os.path.join('src', filename)
250 def built(filename):
251     return os.path.join('$builddir', filename)
252 def doc(filename):
253     return os.path.join('doc', filename)
254 def cc(name, **kwargs):
255     return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
256 def cxx(name, **kwargs):
257     return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
258 def binary(name):
259     if platform.is_windows():
260         exe = name + '.exe'
261         n.build(name, 'phony', exe)
262         return exe
263     return name
264
265 n.variable('builddir', 'build')
266 n.variable('cxx', CXX)
267 if platform.is_msvc():
268     n.variable('ar', 'link')
269 else:
270     n.variable('ar', configure_env.get('AR', 'ar'))
271
272 if platform.is_msvc():
273     cflags = ['/showIncludes',
274               '/nologo',  # Don't print startup banner.
275               '/Zi',  # Create pdb with debug info.
276               '/W4',  # Highest warning level.
277               '/WX',  # Warnings as errors.
278               '/wd4530', '/wd4100', '/wd4706',
279               '/wd4512', '/wd4800', '/wd4702', '/wd4819',
280               # Disable warnings about passing "this" during initialization.
281               '/wd4355',
282               '/GR-',  # Disable RTTI.
283               # Disable size_t -> int truncation warning.
284               # We never have strings or arrays larger than 2**31.
285               '/wd4267',
286               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
287               '/D_VARIADIC_MAX=10',
288               '/DNINJA_PYTHON="%s"' % options.with_python]
289     if options.bootstrap:
290         # In bootstrap mode, we have no ninja process to catch /showIncludes
291         # output.
292         cflags.remove('/showIncludes')
293     if platform.msvc_needs_fs():
294         cflags.append('/FS')
295     ldflags = ['/DEBUG', '/libpath:$builddir']
296     if not options.debug:
297         cflags += ['/Ox', '/DNDEBUG', '/GL']
298         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
299 else:
300     cflags = ['-g', '-Wall', '-Wextra',
301               '-Wno-deprecated',
302               '-Wno-unused-parameter',
303               '-fno-rtti',
304               '-fno-exceptions',
305               '-fvisibility=hidden', '-pipe',
306               '-Wno-missing-field-initializers',
307               '-DNINJA_PYTHON="%s"' % options.with_python]
308     if options.debug:
309         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
310         cflags.remove('-fno-rtti')  # Needed for above pedanticness.
311     else:
312         cflags += ['-O2', '-DNDEBUG']
313     if 'clang' in os.path.basename(CXX):
314         cflags += ['-fcolor-diagnostics']
315     if platform.is_mingw():
316         cflags += ['-D_WIN32_WINNT=0x0501']
317     ldflags = ['-L$builddir']
318     if platform.uses_usr_local():
319         cflags.append('-I/usr/local/include')
320         ldflags.append('-L/usr/local/lib')
321
322 libs = []
323
324 if platform.is_mingw():
325     cflags.remove('-fvisibility=hidden');
326     ldflags.append('-static')
327 elif platform.is_solaris():
328     cflags.remove('-fvisibility=hidden')
329 elif platform.is_msvc():
330     pass
331 else:
332     if options.profile == 'gmon':
333         cflags.append('-pg')
334         ldflags.append('-pg')
335     elif options.profile == 'pprof':
336         cflags.append('-fno-omit-frame-pointer')
337         libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
338
339 if platform.supports_ppoll() and not options.force_pselect:
340     cflags.append('-DUSE_PPOLL')
341 if platform.supports_ninja_browse():
342     cflags.append('-DNINJA_HAVE_BROWSE')
343
344 def shell_escape(str):
345     """Escape str such that it's interpreted as a single argument by
346     the shell."""
347
348     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
349     if platform.is_windows():
350       return str
351     if '"' in str:
352         return "'%s'" % str.replace("'", "\\'")
353     return str
354
355 if 'CFLAGS' in configure_env:
356     cflags.append(configure_env['CFLAGS'])
357 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
358 if 'LDFLAGS' in configure_env:
359     ldflags.append(configure_env['LDFLAGS'])
360 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
361 n.newline()
362
363 if platform.is_msvc():
364     n.rule('cxx',
365         command='$cxx $cflags -c $in /Fo$out',
366         description='CXX $out',
367         deps='msvc'  # /showIncludes is included in $cflags.
368     )
369 else:
370     n.rule('cxx',
371         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
372         depfile='$out.d',
373         deps='gcc',
374         description='CXX $out')
375 n.newline()
376
377 if host.is_msvc():
378     n.rule('ar',
379            command='lib /nologo /ltcg /out:$out $in',
380            description='LIB $out')
381 elif host.is_mingw():
382     n.rule('ar',
383            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
384            description='AR $out')
385 else:
386     n.rule('ar',
387            command='rm -f $out && $ar crs $out $in',
388            description='AR $out')
389 n.newline()
390
391 if platform.is_msvc():
392     n.rule('link',
393         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
394         description='LINK $out')
395 else:
396     n.rule('link',
397         command='$cxx $ldflags -o $out $in $libs',
398         description='LINK $out')
399 n.newline()
400
401 objs = []
402
403 if platform.supports_ninja_browse():
404     n.comment('browse_py.h is used to inline browse.py.')
405     n.rule('inline',
406            command='src/inline.sh $varname < $in > $out',
407            description='INLINE $out')
408     n.build(built('browse_py.h'), 'inline', src('browse.py'),
409             implicit='src/inline.sh',
410             variables=[('varname', 'kBrowsePy')])
411     n.newline()
412
413     objs += cxx('browse', order_only=built('browse_py.h'))
414     n.newline()
415
416 n.comment('the depfile parser and ninja lexers are generated using re2c.')
417 def has_re2c():
418     try:
419         proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
420         return int(proc.communicate()[0], 10) >= 1103
421     except OSError:
422         return False
423 if has_re2c():
424     n.rule('re2c',
425            command='re2c -b -i --no-generation-date -o $out $in',
426            description='RE2C $out')
427     # Generate the .cc files in the source directory so we can check them in.
428     n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
429     n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
430 else:
431     print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
432            "changes to src/*.in.cc will not affect your build.")
433 n.newline()
434
435 n.comment('Core source files all build into ninja library.')
436 for name in ['build',
437              'build_log',
438              'clean',
439              'debug_flags',
440              'depfile_parser',
441              'deps_log',
442              'disk_interface',
443              'edit_distance',
444              'eval_env',
445              'graph',
446              'graphviz',
447              'lexer',
448              'line_printer',
449              'manifest_parser',
450              'metrics',
451              'state',
452              'util',
453              'version']:
454     objs += cxx(name)
455 if platform.is_windows():
456     for name in ['subprocess-win32',
457                  'includes_normalize-win32',
458                  'msvc_helper-win32',
459                  'msvc_helper_main-win32']:
460         objs += cxx(name)
461     if platform.is_msvc():
462         objs += cxx('minidump-win32')
463     objs += cc('getopt')
464 else:
465     objs += cxx('subprocess-posix')
466 if platform.is_msvc():
467     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
468 else:
469     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
470 n.newline()
471
472 if platform.is_msvc():
473     libs.append('ninja.lib')
474 else:
475     libs.append('-lninja')
476
477 all_targets = []
478
479 n.comment('Main executable is library plus main() function.')
480 objs = cxx('ninja')
481 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
482                 variables=[('libs', libs)])
483 n.newline()
484 all_targets += ninja
485
486 if options.bootstrap:
487     # We've built the ninja binary.  Don't run any more commands
488     # through the bootstrap executor, but continue writing the
489     # build.ninja file.
490     n = ninja_writer
491
492 n.comment('Tests all build into ninja_test executable.')
493
494 objs = []
495
496 for name in ['build_log_test',
497              'build_test',
498              'clean_test',
499              'depfile_parser_test',
500              'deps_log_test',
501              'disk_interface_test',
502              'edit_distance_test',
503              'graph_test',
504              'lexer_test',
505              'manifest_parser_test',
506              'ninja_test',
507              'state_test',
508              'subprocess_test',
509              'test',
510              'util_test']:
511     objs += cxx(name)
512 if platform.is_windows():
513     for name in ['includes_normalize_test', 'msvc_helper_test']:
514         objs += cxx(name)
515
516 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
517                      variables=[('libs', libs)])
518 n.newline()
519 all_targets += ninja_test
520
521
522 n.comment('Ancillary executables.')
523 objs = cxx('build_log_perftest')
524 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
525                        implicit=ninja_lib, variables=[('libs', libs)])
526 objs = cxx('canon_perftest')
527 all_targets += n.build(binary('canon_perftest'), 'link', objs,
528                        implicit=ninja_lib, variables=[('libs', libs)])
529 objs = cxx('depfile_parser_perftest')
530 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
531                        implicit=ninja_lib, variables=[('libs', libs)])
532 objs = cxx('hash_collision_bench')
533 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
534                               implicit=ninja_lib, variables=[('libs', libs)])
535 objs = cxx('manifest_parser_perftest')
536 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
537                               implicit=ninja_lib, variables=[('libs', libs)])
538 n.newline()
539
540 n.comment('Generate a graph using the "graph" tool.')
541 n.rule('gendot',
542        command='./ninja -t graph all > $out')
543 n.rule('gengraph',
544        command='dot -Tpng $in > $out')
545 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
546 n.build('graph.png', 'gengraph', dot)
547 n.newline()
548
549 n.comment('Generate the manual using asciidoc.')
550 n.rule('asciidoc',
551        command='asciidoc -b docbook -d book -o $out $in',
552        description='ASCIIDOC $out')
553 n.rule('xsltproc',
554        command='xsltproc --nonet doc/docbook.xsl $in > $out',
555        description='XSLTPROC $out')
556 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
557 manual = n.build(doc('manual.html'), 'xsltproc', xml,
558                  implicit=doc('style.css'))
559 n.build('manual', 'phony',
560         order_only=manual)
561 n.newline()
562
563 n.comment('Generate Doxygen.')
564 n.rule('doxygen',
565        command='doxygen $in',
566        description='DOXYGEN $in')
567 n.variable('doxygen_mainpage_generator',
568            src('gen_doxygen_mainpage.sh'))
569 n.rule('doxygen_mainpage',
570        command='$doxygen_mainpage_generator $in > $out',
571        description='DOXYGEN_MAINPAGE $out')
572 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
573                    ['README', 'COPYING'],
574                    implicit=['$doxygen_mainpage_generator'])
575 n.build('doxygen', 'doxygen', doc('doxygen.config'),
576         implicit=mainpage)
577 n.newline()
578
579 if not host.is_mingw():
580     n.comment('Regenerate build files if build script changes.')
581     n.rule('configure',
582            command='${configure_env}%s configure.py $configure_args' %
583                options.with_python,
584            generator=True)
585     n.build('build.ninja', 'configure',
586             implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
587     n.newline()
588
589 n.default(ninja)
590 n.newline()
591
592 if host.is_linux():
593     n.comment('Packaging')
594     n.rule('rpmbuild',
595            command="misc/packaging/rpmbuild.sh",
596            description='Building rpms..')
597     n.build('rpm', 'rpmbuild')
598     n.newline()
599
600 n.build('all', 'phony', all_targets)
601
602 n.close()
603 print('wrote %s.' % BUILD_FILENAME)
604
605 if options.bootstrap:
606     print('bootstrap complete.  rebuilding...')
607     if platform.is_windows():
608         bootstrap_exe = 'ninja.bootstrap.exe'
609         if os.path.exists(bootstrap_exe):
610             os.unlink(bootstrap_exe)
611         os.rename('ninja.exe', bootstrap_exe)
612         subprocess.check_call('ninja.bootstrap.exe', shell=True)
613     else:
614         subprocess.check_call('./ninja', shell=True)