add DepsLog, a new data structure for dependency information
[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 parser.add_option('--with-ninja', metavar='NAME',
51                   help="name for ninja binary for -t msvc (MSVC only)",
52                   default="ninja")
53 (options, args) = parser.parse_args()
54 if args:
55     print('ERROR: extra unparsed command-line arguments:', args)
56     sys.exit(1)
57
58 platform = options.platform
59 if platform is None:
60     platform = sys.platform
61     if platform.startswith('linux'):
62         platform = 'linux'
63     elif platform.startswith('freebsd'):
64         platform = 'freebsd'
65     elif platform.startswith('solaris'):
66         platform = 'solaris'
67     elif platform.startswith('mingw'):
68         platform = 'mingw'
69     elif platform.startswith('win'):
70         platform = 'windows'
71 host = options.host or platform
72
73 BUILD_FILENAME = 'build.ninja'
74 buildfile = open(BUILD_FILENAME, 'w')
75 n = ninja_syntax.Writer(buildfile)
76 n.comment('This file is used to build ninja itself.')
77 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
78 n.newline()
79
80 n.comment('The arguments passed to configure.py, for rerunning it.')
81 n.variable('configure_args', ' '.join(sys.argv[1:]))
82 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
83 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
84 if configure_env:
85     config_str = ' '.join([k + '=' + configure_env[k] for k in configure_env])
86     n.variable('configure_env', config_str + '$ ')
87 n.newline()
88
89 CXX = configure_env.get('CXX', 'g++')
90 objext = '.o'
91 if platform == 'windows':
92     CXX = 'cl'
93     objext = '.obj'
94
95 def src(filename):
96     return os.path.join('src', filename)
97 def built(filename):
98     return os.path.join('$builddir', filename)
99 def doc(filename):
100     return os.path.join('doc', filename)
101 def cc(name, **kwargs):
102     return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
103 def cxx(name, **kwargs):
104     return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
105 def binary(name):
106     if platform in ('mingw', 'windows'):
107         exe = name + '.exe'
108         n.build(name, 'phony', exe)
109         return exe
110     return name
111
112 n.variable('builddir', 'build')
113 n.variable('cxx', CXX)
114 if platform == 'windows':
115     n.variable('ar', 'link')
116 else:
117     n.variable('ar', configure_env.get('AR', 'ar'))
118
119 if platform == 'windows':
120     cflags = ['/nologo',  # Don't print startup banner.
121               '/Zi',  # Create pdb with debug info.
122               '/W4',  # Highest warning level.
123               '/WX',  # Warnings as errors.
124               '/wd4530', '/wd4100', '/wd4706',
125               '/wd4512', '/wd4800', '/wd4702', '/wd4819',
126               # Disable warnings about passing "this" during initialization.
127               '/wd4355',
128               '/GR-',  # Disable RTTI.
129               # Disable size_t -> int truncation warning.
130               # We never have strings or arrays larger than 2**31.
131               '/wd4267',
132               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
133               '/DNINJA_PYTHON="%s"' % options.with_python]
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 == 'mingw':
155         cflags += ['-D_WIN32_WINNT=0x0501']
156     ldflags = ['-L$builddir']
157 libs = []
158
159 if platform == 'mingw':
160     cflags.remove('-fvisibility=hidden');
161     ldflags.append('-static')
162 elif platform == 'sunos5':
163     cflags.remove('-fvisibility=hidden')
164 elif platform == 'windows':
165     pass
166 else:
167     if options.profile == 'gmon':
168         cflags.append('-pg')
169         ldflags.append('-pg')
170     elif options.profile == 'pprof':
171         libs.append('-lprofiler')
172
173 def shell_escape(str):
174     """Escape str such that it's interpreted as a single argument by
175     the shell."""
176
177     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
178     if platform in ('windows', 'mingw'):
179       return str
180     if '"' in str:
181         return "'%s'" % str.replace("'", "\\'")
182     return str
183
184 if 'CFLAGS' in configure_env:
185     cflags.append(configure_env['CFLAGS'])
186 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
187 if 'LDFLAGS' in configure_env:
188     ldflags.append(configure_env['LDFLAGS'])
189 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
190 n.newline()
191
192 if platform == 'windows':
193     compiler = '$cxx'
194     if options.with_ninja:
195         compiler = ('%s -t msvc -o $out -- $cxx /showIncludes' %
196                     options.with_ninja)
197     n.rule('cxx',
198         command='%s $cflags -c $in /Fo$out' % compiler,
199         depfile='$out.d',
200         description='CXX $out')
201 else:
202     n.rule('cxx',
203         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
204         depfile='$out.d',
205         description='CXX $out')
206 n.newline()
207
208 if host == 'windows':
209     n.rule('ar',
210            command='lib /nologo /ltcg /out:$out $in',
211            description='LIB $out')
212 elif host == '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 == 'windows':
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 platform not in ('solaris', 'mingw', 'windows'):
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              'depfile_parser',
272              'deps_log',
273              'disk_interface',
274              'edit_distance',
275              'eval_env',
276              'explain',
277              'graph',
278              'graphviz',
279              'lexer',
280              'manifest_parser',
281              'metrics',
282              'state',
283              'util',
284              'version']:
285     objs += cxx(name)
286 if platform in ('mingw', 'windows'):
287     for name in ['subprocess-win32',
288                  'includes_normalize-win32',
289                  'msvc_helper-win32',
290                  'msvc_helper_main-win32']:
291         objs += cxx(name)
292     if platform == 'windows':
293         objs += cxx('minidump-win32')
294     objs += cc('getopt')
295 else:
296     objs += cxx('subprocess-posix')
297 if platform == 'windows':
298     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
299 else:
300     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
301 n.newline()
302
303 if platform == 'windows':
304     libs.append('ninja.lib')
305 else:
306     libs.append('-lninja')
307
308 all_targets = []
309
310 n.comment('Main executable is library plus main() function.')
311 objs = cxx('ninja')
312 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
313                 variables=[('libs', libs)])
314 n.newline()
315 all_targets += ninja
316
317 n.comment('Tests all build into ninja_test executable.')
318
319 variables = []
320 test_cflags = cflags + ['-DGTEST_HAS_RTTI=0']
321 test_ldflags = None
322 test_libs = libs
323 objs = []
324 if options.with_gtest:
325     path = options.with_gtest
326
327     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
328     if platform == 'windows':
329         gtest_cflags = '/nologo /EHsc /Zi ' + gtest_all_incs
330     else:
331         gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
332     objs += n.build(built('gtest-all' + objext), 'cxx',
333                     os.path.join(path, 'src', 'gtest-all.cc'),
334                     variables=[('cflags', gtest_cflags)])
335     objs += n.build(built('gtest_main' + objext), 'cxx',
336                     os.path.join(path, 'src', 'gtest_main.cc'),
337                     variables=[('cflags', gtest_cflags)])
338
339     test_cflags.append('-I%s' % os.path.join(path, 'include'))
340 else:
341     # Use gtest from system.
342     if platform == 'windows':
343         test_libs.extend(['gtest_main.lib', 'gtest.lib'])
344     else:
345         test_libs.extend(['-lgtest_main', '-lgtest'])
346
347 n.variable('test_cflags', test_cflags)
348 for name in ['build_log_test',
349              'build_test',
350              'clean_test',
351              'depfile_parser_test',
352              'deps_log_test',
353              'disk_interface_test',
354              'edit_distance_test',
355              'graph_test',
356              'lexer_test',
357              'manifest_parser_test',
358              'state_test',
359              'subprocess_test',
360              'test',
361              'util_test']:
362     objs += cxx(name, variables=[('cflags', '$test_cflags')])
363 if platform in ('windows', 'mingw'):
364     for name in ['includes_normalize_test', 'msvc_helper_test']:
365         objs += cxx(name, variables=[('cflags', test_cflags)])
366
367 if platform != 'mingw' and platform != 'windows':
368     test_libs.append('-lpthread')
369 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
370                      variables=[('ldflags', test_ldflags),
371                                 ('libs', test_libs)])
372 n.newline()
373 all_targets += ninja_test
374
375
376 n.comment('Ancillary executables.')
377 objs = cxx('parser_perftest')
378 all_targets += n.build(binary('parser_perftest'), 'link', objs,
379                        implicit=ninja_lib, variables=[('libs', libs)])
380 objs = cxx('build_log_perftest')
381 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
382                        implicit=ninja_lib, variables=[('libs', libs)])
383 objs = cxx('canon_perftest')
384 all_targets += n.build(binary('canon_perftest'), 'link', objs,
385                        implicit=ninja_lib, variables=[('libs', libs)])
386 objs = cxx('hash_collision_bench')
387 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
388                               implicit=ninja_lib, variables=[('libs', libs)])
389 n.newline()
390
391 n.comment('Generate a graph using the "graph" tool.')
392 n.rule('gendot',
393        command='./ninja -t graph all > $out')
394 n.rule('gengraph',
395        command='dot -Tpng $in > $out')
396 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
397 n.build('graph.png', 'gengraph', dot)
398 n.newline()
399
400 n.comment('Generate the manual using asciidoc.')
401 n.rule('asciidoc',
402        command='asciidoc -b docbook -d book -o $out $in',
403        description='ASCIIDOC $out')
404 n.rule('xsltproc',
405        command='xsltproc --nonet doc/docbook.xsl $in > $out',
406        description='XSLTPROC $out')
407 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
408 manual = n.build(doc('manual.html'), 'xsltproc', xml,
409                  implicit=doc('style.css'))
410 n.build('manual', 'phony',
411         order_only=manual)
412 n.newline()
413
414 n.comment('Generate Doxygen.')
415 n.rule('doxygen',
416        command='doxygen $in',
417        description='DOXYGEN $in')
418 n.variable('doxygen_mainpage_generator',
419            src('gen_doxygen_mainpage.sh'))
420 n.rule('doxygen_mainpage',
421        command='$doxygen_mainpage_generator $in > $out',
422        description='DOXYGEN_MAINPAGE $out')
423 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
424                    ['README', 'COPYING'],
425                    implicit=['$doxygen_mainpage_generator'])
426 n.build('doxygen', 'doxygen', doc('doxygen.config'),
427         implicit=mainpage)
428 n.newline()
429
430 if host != 'mingw':
431     n.comment('Regenerate build files if build script changes.')
432     n.rule('configure',
433            command='${configure_env}%s configure.py $configure_args' %
434                options.with_python,
435            generator=True)
436     n.build('build.ninja', 'configure',
437             implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
438     n.newline()
439
440 n.default(ninja)
441 n.newline()
442
443 if host == 'linux':
444     n.comment('Packaging')
445     n.rule('rpmbuild',
446            command="misc/packaging/rpmbuild.sh",
447            description='Building rpms..')
448     n.build('rpm', 'rpmbuild')
449     n.newline()
450
451 n.build('all', 'phony', all_targets)
452
453 print('wrote %s.' % BUILD_FILENAME)