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