Merge pull request #665 from syntheticpp/localized-showinclude
[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 sys
27 import platform_helper
28 sys.path.insert(0, 'misc')
29
30 import ninja_syntax
31
32 parser = OptionParser()
33 profilers = ['gmon', 'pprof']
34 parser.add_option('--platform',
35                   help='target platform (' + '/'.join(platform_helper.platforms()) + ')',
36                   choices=platform_helper.platforms())
37 parser.add_option('--host',
38                   help='host platform (' + '/'.join(platform_helper.platforms()) + ')',
39                   choices=platform_helper.platforms())
40 parser.add_option('--debug', action='store_true',
41                   help='enable debugging extras',)
42 parser.add_option('--profile', metavar='TYPE',
43                   choices=profilers,
44                   help='enable profiling (' + '/'.join(profilers) + ')',)
45 parser.add_option('--with-gtest', metavar='PATH',
46                   help='use gtest unpacked in directory PATH')
47 parser.add_option('--with-python', metavar='EXE',
48                   help='use EXE as the Python interpreter',
49                   default=os.path.basename(sys.executable))
50 parser.add_option('--force-pselect', action='store_true',
51                   help="ppoll() is used by default where available, but some platforms may need to use pselect instead",)
52 (options, args) = parser.parse_args()
53 if args:
54     print('ERROR: extra unparsed command-line arguments:', args)
55     sys.exit(1)
56
57 platform = platform_helper.Platform(options.platform)
58 if options.host:
59     host = platform_helper.Platform(options.host)
60 else:
61     host = platform
62
63 BUILD_FILENAME = 'build.ninja'
64 buildfile = open(BUILD_FILENAME, 'w')
65 n = ninja_syntax.Writer(buildfile)
66 n.comment('This file is used to build ninja itself.')
67 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
68 n.newline()
69
70 n.variable('ninja_required_version', '1.3')
71 n.newline()
72
73 n.comment('The arguments passed to configure.py, for rerunning it.')
74 n.variable('configure_args', ' '.join(sys.argv[1:]))
75 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
76 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
77 if configure_env:
78     config_str = ' '.join([k + '=' + configure_env[k] for k in configure_env])
79     n.variable('configure_env', config_str + '$ ')
80 n.newline()
81
82 CXX = configure_env.get('CXX', 'g++')
83 objext = '.o'
84 if platform.is_msvc():
85     CXX = 'cl'
86     objext = '.obj'
87
88 def src(filename):
89     return os.path.join('src', filename)
90 def built(filename):
91     return os.path.join('$builddir', filename)
92 def doc(filename):
93     return os.path.join('doc', filename)
94 def cc(name, **kwargs):
95     return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
96 def cxx(name, **kwargs):
97     return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
98 def binary(name):
99     if platform.is_windows():
100         exe = name + '.exe'
101         n.build(name, 'phony', exe)
102         return exe
103     return name
104
105 n.variable('builddir', 'build')
106 n.variable('cxx', CXX)
107 if platform.is_msvc():
108     n.variable('ar', 'link')
109 else:
110     n.variable('ar', configure_env.get('AR', 'ar'))
111
112 if platform.is_msvc():
113     cflags = ['/nologo',  # Don't print startup banner.
114               '/Zi',  # Create pdb with debug info.
115               '/W4',  # Highest warning level.
116               '/WX',  # Warnings as errors.
117               '/wd4530', '/wd4100', '/wd4706',
118               '/wd4512', '/wd4800', '/wd4702', '/wd4819',
119               # Disable warnings about passing "this" during initialization.
120               '/wd4355',
121               '/GR-',  # Disable RTTI.
122               # Disable size_t -> int truncation warning.
123               # We never have strings or arrays larger than 2**31.
124               '/wd4267',
125               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
126               '/D_VARIADIC_MAX=10',
127               '/DNINJA_PYTHON="%s"' % options.with_python]
128     if platform.msvc_needs_fs():
129         cflags.append('/FS')
130     ldflags = ['/DEBUG', '/libpath:$builddir']
131     if not options.debug:
132         cflags += ['/Ox', '/DNDEBUG', '/GL']
133         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
134 else:
135     cflags = ['-g', '-Wall', '-Wextra',
136               '-Wno-deprecated',
137               '-Wno-unused-parameter',
138               '-fno-rtti',
139               '-fno-exceptions',
140               '-fvisibility=hidden', '-pipe',
141               '-Wno-missing-field-initializers',
142               '-DNINJA_PYTHON="%s"' % options.with_python]
143     if options.debug:
144         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
145         cflags.remove('-fno-rtti')  # Needed for above pedanticness.
146     else:
147         cflags += ['-O2', '-DNDEBUG']
148     if 'clang' in os.path.basename(CXX):
149         cflags += ['-fcolor-diagnostics']
150     if platform.is_mingw():
151         cflags += ['-D_WIN32_WINNT=0x0501']
152     ldflags = ['-L$builddir']
153 libs = []
154
155 if platform.is_mingw():
156     cflags.remove('-fvisibility=hidden');
157     ldflags.append('-static')
158 elif platform.is_sunos5():
159     cflags.remove('-fvisibility=hidden')
160 elif platform.is_msvc():
161     pass
162 else:
163     if options.profile == 'gmon':
164         cflags.append('-pg')
165         ldflags.append('-pg')
166     elif options.profile == 'pprof':
167         cflags.append('-fno-omit-frame-pointer')
168         libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
169
170 if (platform.is_linux() or platform.is_openbsd() or platform.is_bitrig()) and not options.force_pselect:
171     cflags.append('-DUSE_PPOLL')
172
173 def shell_escape(str):
174     """Escape str such that it's interpreted as a single argument by
175     the shell."""
176
177     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
178     if platform.is_windows():
179       return str
180     if '"' in str:
181         return "'%s'" % str.replace("'", "\\'")
182     return str
183
184 if 'CFLAGS' in configure_env:
185     cflags.append(configure_env['CFLAGS'])
186 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
187 if 'LDFLAGS' in configure_env:
188     ldflags.append(configure_env['LDFLAGS'])
189 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
190 n.newline()
191
192 if platform.is_msvc():
193     n.rule('cxx',
194         command='$cxx /showIncludes $cflags -c $in /Fo$out',
195         description='CXX $out',
196         deps='msvc')
197 else:
198     n.rule('cxx',
199         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
200         depfile='$out.d',
201         deps='gcc',
202         description='CXX $out')
203 n.newline()
204
205 if host.is_msvc():
206     n.rule('ar',
207            command='lib /nologo /ltcg /out:$out $in',
208            description='LIB $out')
209 elif host.is_mingw():
210     n.rule('ar',
211            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
212            description='AR $out')
213 else:
214     n.rule('ar',
215            command='rm -f $out && $ar crs $out $in',
216            description='AR $out')
217 n.newline()
218
219 if platform.is_msvc():
220     n.rule('link',
221         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
222         description='LINK $out')
223 else:
224     n.rule('link',
225         command='$cxx $ldflags -o $out $in $libs',
226         description='LINK $out')
227 n.newline()
228
229 objs = []
230
231 if not platform.is_windows() and not platform.is_solaris():
232     n.comment('browse_py.h is used to inline browse.py.')
233     n.rule('inline',
234            command='src/inline.sh $varname < $in > $out',
235            description='INLINE $out')
236     n.build(built('browse_py.h'), 'inline', src('browse.py'),
237             implicit='src/inline.sh',
238             variables=[('varname', 'kBrowsePy')])
239     n.newline()
240
241     objs += cxx('browse', order_only=built('browse_py.h'))
242     n.newline()
243
244 n.comment('the depfile parser and ninja lexers are generated using re2c.')
245 def has_re2c():
246     import subprocess
247     try:
248         proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
249         return int(proc.communicate()[0], 10) >= 1103
250     except OSError:
251         return False
252 if has_re2c():
253     n.rule('re2c',
254            command='re2c -b -i --no-generation-date -o $out $in',
255            description='RE2C $out')
256     # Generate the .cc files in the source directory so we can check them in.
257     n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
258     n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
259 else:
260     print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
261            "changes to src/*.in.cc will not affect your build.")
262 n.newline()
263
264 n.comment('Core source files all build into ninja library.')
265 for name in ['build',
266              'build_log',
267              'clean',
268              'debug_flags',
269              'depfile_parser',
270              'deps_log',
271              'disk_interface',
272              'edit_distance',
273              'eval_env',
274              'graph',
275              'graphviz',
276              'lexer',
277              'line_printer',
278              'manifest_parser',
279              'metrics',
280              'state',
281              'util',
282              'version']:
283     objs += cxx(name)
284 if platform.is_windows():
285     for name in ['subprocess-win32',
286                  'includes_normalize-win32',
287                  'msvc_helper-win32',
288                  'msvc_helper_main-win32']:
289         objs += cxx(name)
290     if platform.is_msvc():
291         objs += cxx('minidump-win32')
292     objs += cc('getopt')
293 else:
294     objs += cxx('subprocess-posix')
295 if platform.is_msvc():
296     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
297 else:
298     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
299 n.newline()
300
301 if platform.is_msvc():
302     libs.append('ninja.lib')
303 else:
304     libs.append('-lninja')
305
306 all_targets = []
307
308 n.comment('Main executable is library plus main() function.')
309 objs = cxx('ninja')
310 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
311                 variables=[('libs', libs)])
312 n.newline()
313 all_targets += ninja
314
315 n.comment('Tests all build into ninja_test executable.')
316
317 variables = []
318 test_cflags = cflags + ['-DGTEST_HAS_RTTI=0']
319 test_ldflags = None
320 test_libs = libs
321 objs = []
322 if options.with_gtest:
323     path = options.with_gtest
324
325     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
326     if platform.is_msvc():
327         gtest_cflags = '/nologo /EHsc /Zi /D_VARIADIC_MAX=10 ' + gtest_all_incs
328     else:
329         gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
330     objs += n.build(built('gtest-all' + objext), 'cxx',
331                     os.path.join(path, 'src', 'gtest-all.cc'),
332                     variables=[('cflags', gtest_cflags)])
333
334     test_cflags.append('-I%s' % os.path.join(path, 'include'))
335 else:
336     # Use gtest from system.
337     if platform.is_msvc():
338         test_libs.extend(['gtest_main.lib', 'gtest.lib'])
339     else:
340         test_libs.extend(['-lgtest_main', '-lgtest'])
341
342 n.variable('test_cflags', test_cflags)
343 for name in ['build_log_test',
344              'build_test',
345              'clean_test',
346              'depfile_parser_test',
347              'deps_log_test',
348              'disk_interface_test',
349              'edit_distance_test',
350              'graph_test',
351              'lexer_test',
352              'manifest_parser_test',
353              'ninja_test',
354              'state_test',
355              'subprocess_test',
356              'test',
357              'util_test']:
358     objs += cxx(name, variables=[('cflags', '$test_cflags')])
359 if platform.is_windows():
360     for name in ['includes_normalize_test', 'msvc_helper_test']:
361         objs += cxx(name, variables=[('cflags', test_cflags)])
362
363 if not platform.is_windows():
364     test_libs.append('-lpthread')
365 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
366                      variables=[('ldflags', test_ldflags),
367                                 ('libs', test_libs)])
368 n.newline()
369 all_targets += ninja_test
370
371
372 n.comment('Ancillary executables.')
373 objs = cxx('parser_perftest')
374 all_targets += n.build(binary('parser_perftest'), 'link', objs,
375                        implicit=ninja_lib, variables=[('libs', libs)])
376 objs = cxx('build_log_perftest')
377 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
378                        implicit=ninja_lib, variables=[('libs', libs)])
379 objs = cxx('canon_perftest')
380 all_targets += n.build(binary('canon_perftest'), 'link', objs,
381                        implicit=ninja_lib, variables=[('libs', libs)])
382 objs = cxx('hash_collision_bench')
383 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
384                               implicit=ninja_lib, variables=[('libs', libs)])
385 n.newline()
386
387 n.comment('Generate a graph using the "graph" tool.')
388 n.rule('gendot',
389        command='./ninja -t graph all > $out')
390 n.rule('gengraph',
391        command='dot -Tpng $in > $out')
392 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
393 n.build('graph.png', 'gengraph', dot)
394 n.newline()
395
396 n.comment('Generate the manual using asciidoc.')
397 n.rule('asciidoc',
398        command='asciidoc -b docbook -d book -o $out $in',
399        description='ASCIIDOC $out')
400 n.rule('xsltproc',
401        command='xsltproc --nonet doc/docbook.xsl $in > $out',
402        description='XSLTPROC $out')
403 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
404 manual = n.build(doc('manual.html'), 'xsltproc', xml,
405                  implicit=doc('style.css'))
406 n.build('manual', 'phony',
407         order_only=manual)
408 n.newline()
409
410 n.comment('Generate Doxygen.')
411 n.rule('doxygen',
412        command='doxygen $in',
413        description='DOXYGEN $in')
414 n.variable('doxygen_mainpage_generator',
415            src('gen_doxygen_mainpage.sh'))
416 n.rule('doxygen_mainpage',
417        command='$doxygen_mainpage_generator $in > $out',
418        description='DOXYGEN_MAINPAGE $out')
419 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
420                    ['README', 'COPYING'],
421                    implicit=['$doxygen_mainpage_generator'])
422 n.build('doxygen', 'doxygen', doc('doxygen.config'),
423         implicit=mainpage)
424 n.newline()
425
426 if not host.is_mingw():
427     n.comment('Regenerate build files if build script changes.')
428     n.rule('configure',
429            command='${configure_env}%s configure.py $configure_args' %
430                options.with_python,
431            generator=True)
432     n.build('build.ninja', 'configure',
433             implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
434     n.newline()
435
436 n.default(ninja)
437 n.newline()
438
439 if host.is_linux():
440     n.comment('Packaging')
441     n.rule('rpmbuild',
442            command="misc/packaging/rpmbuild.sh",
443            description='Building rpms..')
444     n.build('rpm', 'rpmbuild')
445     n.newline()
446
447 n.build('all', 'phony', all_targets)
448
449 print('wrote %s.' % BUILD_FILENAME)