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