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