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