Merge pull request #812 from nico/ninjatest
[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 (' +
36                        '/'.join(platform_helper.platforms()) + ')',
37                   choices=platform_helper.platforms())
38 parser.add_option('--host',
39                   help='host platform (' +
40                        '/'.join(platform_helper.platforms()) + ')',
41                   choices=platform_helper.platforms())
42 parser.add_option('--debug', action='store_true',
43                   help='enable debugging extras',)
44 parser.add_option('--profile', metavar='TYPE',
45                   choices=profilers,
46                   help='enable profiling (' + '/'.join(profilers) + ')',)
47 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
48 parser.add_option('--with-python', metavar='EXE',
49                   help='use EXE as the Python interpreter',
50                   default=os.path.basename(sys.executable))
51 parser.add_option('--force-pselect', action='store_true',
52                   help='ppoll() is used by default where available, '
53                        'but some platforms may need to use pselect instead',)
54 (options, args) = parser.parse_args()
55 if args:
56     print('ERROR: extra unparsed command-line arguments:', args)
57     sys.exit(1)
58
59 platform = platform_helper.Platform(options.platform)
60 if options.host:
61     host = platform_helper.Platform(options.host)
62 else:
63     host = platform
64
65 BUILD_FILENAME = 'build.ninja'
66 buildfile = open(BUILD_FILENAME, 'w')
67 n = ninja_syntax.Writer(buildfile)
68 n.comment('This file is used to build ninja itself.')
69 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
70 n.newline()
71
72 n.variable('ninja_required_version', '1.3')
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.is_msvc():
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.is_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.is_msvc():
110     n.variable('ar', 'link')
111 else:
112     n.variable('ar', configure_env.get('AR', 'ar'))
113
114 if platform.is_msvc():
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               '/D_VARIADIC_MAX=10',
129               '/DNINJA_PYTHON="%s"' % options.with_python]
130     if platform.msvc_needs_fs():
131         cflags.append('/FS')
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.is_mingw():
153         cflags += ['-D_WIN32_WINNT=0x0501']
154     ldflags = ['-L$builddir']
155 libs = []
156
157 if platform.is_mingw():
158     cflags.remove('-fvisibility=hidden');
159     ldflags.append('-static')
160 elif platform.is_sunos5():
161     cflags.remove('-fvisibility=hidden')
162 elif platform.is_msvc():
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 if (platform.is_linux() or platform.is_openbsd() or platform.is_bitrig()) and \
173         not options.force_pselect:
174     cflags.append('-DUSE_PPOLL')
175
176 def shell_escape(str):
177     """Escape str such that it's interpreted as a single argument by
178     the shell."""
179
180     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
181     if platform.is_windows():
182       return str
183     if '"' in str:
184         return "'%s'" % str.replace("'", "\\'")
185     return str
186
187 if 'CFLAGS' in configure_env:
188     cflags.append(configure_env['CFLAGS'])
189 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
190 if 'LDFLAGS' in configure_env:
191     ldflags.append(configure_env['LDFLAGS'])
192 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
193 n.newline()
194
195 if platform.is_msvc():
196     n.rule('cxx',
197         command='$cxx /showIncludes $cflags -c $in /Fo$out',
198         description='CXX $out',
199         deps='msvc')
200 else:
201     n.rule('cxx',
202         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
203         depfile='$out.d',
204         deps='gcc',
205         description='CXX $out')
206 n.newline()
207
208 if host.is_msvc():
209     n.rule('ar',
210            command='lib /nologo /ltcg /out:$out $in',
211            description='LIB $out')
212 elif host.is_mingw():
213     n.rule('ar',
214            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
215            description='AR $out')
216 else:
217     n.rule('ar',
218            command='rm -f $out && $ar crs $out $in',
219            description='AR $out')
220 n.newline()
221
222 if platform.is_msvc():
223     n.rule('link',
224         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
225         description='LINK $out')
226 else:
227     n.rule('link',
228         command='$cxx $ldflags -o $out $in $libs',
229         description='LINK $out')
230 n.newline()
231
232 objs = []
233
234 if not platform.is_windows() and not platform.is_solaris():
235     n.comment('browse_py.h is used to inline browse.py.')
236     n.rule('inline',
237            command='src/inline.sh $varname < $in > $out',
238            description='INLINE $out')
239     n.build(built('browse_py.h'), 'inline', src('browse.py'),
240             implicit='src/inline.sh',
241             variables=[('varname', 'kBrowsePy')])
242     n.newline()
243
244     objs += cxx('browse', order_only=built('browse_py.h'))
245     n.newline()
246
247 n.comment('the depfile parser and ninja lexers are generated using re2c.')
248 def has_re2c():
249     import subprocess
250     try:
251         proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
252         return int(proc.communicate()[0], 10) >= 1103
253     except OSError:
254         return False
255 if has_re2c():
256     n.rule('re2c',
257            command='re2c -b -i --no-generation-date -o $out $in',
258            description='RE2C $out')
259     # Generate the .cc files in the source directory so we can check them in.
260     n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
261     n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
262 else:
263     print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
264            "changes to src/*.in.cc will not affect your build.")
265 n.newline()
266
267 n.comment('Core source files all build into ninja library.')
268 for name in ['build',
269              'build_log',
270              'clean',
271              'debug_flags',
272              'depfile_parser',
273              'deps_log',
274              'disk_interface',
275              'edit_distance',
276              'eval_env',
277              'graph',
278              'graphviz',
279              'lexer',
280              'line_printer',
281              'manifest_parser',
282              'metrics',
283              'state',
284              'util',
285              'version']:
286     objs += cxx(name)
287 if platform.is_windows():
288     for name in ['subprocess-win32',
289                  'includes_normalize-win32',
290                  'msvc_helper-win32',
291                  'msvc_helper_main-win32']:
292         objs += cxx(name)
293     if platform.is_msvc():
294         objs += cxx('minidump-win32')
295     objs += cc('getopt')
296 else:
297     objs += cxx('subprocess-posix')
298 if platform.is_msvc():
299     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
300 else:
301     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
302 n.newline()
303
304 if platform.is_msvc():
305     libs.append('ninja.lib')
306 else:
307     libs.append('-lninja')
308
309 all_targets = []
310
311 n.comment('Main executable is library plus main() function.')
312 objs = cxx('ninja')
313 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
314                 variables=[('libs', libs)])
315 n.newline()
316 all_targets += ninja
317
318 n.comment('Tests all build into ninja_test executable.')
319
320 variables = []
321 test_ldflags = None
322 test_libs = libs
323 objs = []
324
325 for name in ['build_log_test',
326              'build_test',
327              'clean_test',
328              'depfile_parser_test',
329              'deps_log_test',
330              'disk_interface_test',
331              'edit_distance_test',
332              'graph_test',
333              'lexer_test',
334              'manifest_parser_test',
335              'ninja_test',
336              'state_test',
337              'subprocess_test',
338              'test',
339              'util_test']:
340     objs += cxx(name)
341 if platform.is_windows():
342     for name in ['includes_normalize_test', 'msvc_helper_test']:
343         objs += cxx(name)
344
345 if not platform.is_windows():
346     test_libs.append('-lpthread')
347 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
348                      variables=[('ldflags', test_ldflags),
349                                 ('libs', test_libs)])
350 n.newline()
351 all_targets += ninja_test
352
353
354 n.comment('Ancillary executables.')
355 objs = cxx('build_log_perftest')
356 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
357                        implicit=ninja_lib, variables=[('libs', libs)])
358 objs = cxx('canon_perftest')
359 all_targets += n.build(binary('canon_perftest'), 'link', objs,
360                        implicit=ninja_lib, variables=[('libs', libs)])
361 objs = cxx('depfile_parser_perftest')
362 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
363                        implicit=ninja_lib, variables=[('libs', libs)])
364 objs = cxx('hash_collision_bench')
365 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
366                               implicit=ninja_lib, variables=[('libs', libs)])
367 objs = cxx('manifest_parser_perftest')
368 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
369                               implicit=ninja_lib, variables=[('libs', libs)])
370 n.newline()
371
372 n.comment('Generate a graph using the "graph" tool.')
373 n.rule('gendot',
374        command='./ninja -t graph all > $out')
375 n.rule('gengraph',
376        command='dot -Tpng $in > $out')
377 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
378 n.build('graph.png', 'gengraph', dot)
379 n.newline()
380
381 n.comment('Generate the manual using asciidoc.')
382 n.rule('asciidoc',
383        command='asciidoc -b docbook -d book -o $out $in',
384        description='ASCIIDOC $out')
385 n.rule('xsltproc',
386        command='xsltproc --nonet doc/docbook.xsl $in > $out',
387        description='XSLTPROC $out')
388 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
389 manual = n.build(doc('manual.html'), 'xsltproc', xml,
390                  implicit=doc('style.css'))
391 n.build('manual', 'phony',
392         order_only=manual)
393 n.newline()
394
395 n.comment('Generate Doxygen.')
396 n.rule('doxygen',
397        command='doxygen $in',
398        description='DOXYGEN $in')
399 n.variable('doxygen_mainpage_generator',
400            src('gen_doxygen_mainpage.sh'))
401 n.rule('doxygen_mainpage',
402        command='$doxygen_mainpage_generator $in > $out',
403        description='DOXYGEN_MAINPAGE $out')
404 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
405                    ['README', 'COPYING'],
406                    implicit=['$doxygen_mainpage_generator'])
407 n.build('doxygen', 'doxygen', doc('doxygen.config'),
408         implicit=mainpage)
409 n.newline()
410
411 if not host.is_mingw():
412     n.comment('Regenerate build files if build script changes.')
413     n.rule('configure',
414            command='${configure_env}%s configure.py $configure_args' %
415                options.with_python,
416            generator=True)
417     n.build('build.ninja', 'configure',
418             implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
419     n.newline()
420
421 n.default(ninja)
422 n.newline()
423
424 if host.is_linux():
425     n.comment('Packaging')
426     n.rule('rpmbuild',
427            command="misc/packaging/rpmbuild.sh",
428            description='Building rpms..')
429     n.build('rpm', 'rpmbuild')
430     n.newline()
431
432 n.build('all', 'phony', all_targets)
433
434 print('wrote %s.' % BUILD_FILENAME)