rename "special" to "deps"
[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               '/DNINJA_PYTHON="%s"' % options.with_python]
131     ldflags = ['/DEBUG', '/libpath:$builddir']
132     if not options.debug:
133         cflags += ['/Ox', '/DNDEBUG', '/GL']
134         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
135 else:
136     cflags = ['-g', '-Wall', '-Wextra',
137               '-Wno-deprecated',
138               '-Wno-unused-parameter',
139               '-fno-rtti',
140               '-fno-exceptions',
141               '-fvisibility=hidden', '-pipe',
142               '-Wno-missing-field-initializers',
143               '-DNINJA_PYTHON="%s"' % options.with_python]
144     if options.debug:
145         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
146         cflags.remove('-fno-rtti')  # Needed for above pedanticness.
147     else:
148         cflags += ['-O2', '-DNDEBUG']
149     if 'clang' in os.path.basename(CXX):
150         cflags += ['-fcolor-diagnostics']
151     if platform == 'mingw':
152         cflags += ['-D_WIN32_WINNT=0x0501']
153     ldflags = ['-L$builddir']
154 libs = []
155
156 if platform == 'mingw':
157     cflags.remove('-fvisibility=hidden');
158     ldflags.append('-static')
159 elif platform == 'sunos5':
160     cflags.remove('-fvisibility=hidden')
161 elif platform == 'windows':
162     pass
163 else:
164     if options.profile == 'gmon':
165         cflags.append('-pg')
166         ldflags.append('-pg')
167     elif options.profile == 'pprof':
168         libs.append('-lprofiler')
169
170 def shell_escape(str):
171     """Escape str such that it's interpreted as a single argument by
172     the shell."""
173
174     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
175     if platform in ('windows', 'mingw'):
176       return str
177     if '"' in str:
178         return "'%s'" % str.replace("'", "\\'")
179     return str
180
181 if 'CFLAGS' in configure_env:
182     cflags.append(configure_env['CFLAGS'])
183 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
184 if 'LDFLAGS' in configure_env:
185     ldflags.append(configure_env['LDFLAGS'])
186 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
187 n.newline()
188
189 if platform == 'windows':
190     n.rule('cxx',
191         command='$cxx /showIncludes $cflags -c $in /Fo$out',
192         depfile='$out.d',
193         description='CXX $out',
194         deps='msvc')
195 else:
196     n.rule('cxx',
197         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
198         depfile='$out.d',
199         description='CXX $out')
200 n.newline()
201
202 if host == 'windows':
203     n.rule('ar',
204            command='lib /nologo /ltcg /out:$out $in',
205            description='LIB $out')
206 elif host == 'mingw':
207     n.rule('ar',
208            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
209            description='AR $out')
210 else:
211     n.rule('ar',
212            command='rm -f $out && $ar crs $out $in',
213            description='AR $out')
214 n.newline()
215
216 if platform == 'windows':
217     n.rule('link',
218         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
219         description='LINK $out')
220 else:
221     n.rule('link',
222         command='$cxx $ldflags -o $out $in $libs',
223         description='LINK $out')
224 n.newline()
225
226 objs = []
227
228 if platform not in ('solaris', 'mingw', 'windows'):
229     n.comment('browse_py.h is used to inline browse.py.')
230     n.rule('inline',
231            command='src/inline.sh $varname < $in > $out',
232            description='INLINE $out')
233     n.build(built('browse_py.h'), 'inline', src('browse.py'),
234             implicit='src/inline.sh',
235             variables=[('varname', 'kBrowsePy')])
236     n.newline()
237
238     objs += cxx('browse', order_only=built('browse_py.h'))
239     n.newline()
240
241 n.comment('the depfile parser and ninja lexers are generated using re2c.')
242 def has_re2c():
243     import subprocess
244     try:
245         proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
246         return int(proc.communicate()[0], 10) >= 1103
247     except OSError:
248         return False
249 if has_re2c():
250     n.rule('re2c',
251            command='re2c -b -i --no-generation-date -o $out $in',
252            description='RE2C $out')
253     # Generate the .cc files in the source directory so we can check them in.
254     n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
255     n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
256 else:
257     print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
258            "changes to src/*.in.cc will not affect your build.")
259 n.newline()
260
261 n.comment('Core source files all build into ninja library.')
262 for name in ['build',
263              'build_log',
264              'clean',
265              'depfile_parser',
266              'deps_log',
267              'disk_interface',
268              'edit_distance',
269              'eval_env',
270              'explain',
271              'graph',
272              'graphviz',
273              'lexer',
274              'manifest_parser',
275              'metrics',
276              'state',
277              'util',
278              'version']:
279     objs += cxx(name)
280 if platform in ('mingw', 'windows'):
281     for name in ['subprocess-win32',
282                  'includes_normalize-win32',
283                  'msvc_helper-win32',
284                  'msvc_helper_main-win32']:
285         objs += cxx(name)
286     if platform == 'windows':
287         objs += cxx('minidump-win32')
288     objs += cc('getopt')
289 else:
290     objs += cxx('subprocess-posix')
291 if platform == 'windows':
292     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
293 else:
294     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
295 n.newline()
296
297 if platform == 'windows':
298     libs.append('ninja.lib')
299 else:
300     libs.append('-lninja')
301
302 all_targets = []
303
304 n.comment('Main executable is library plus main() function.')
305 objs = cxx('ninja')
306 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
307                 variables=[('libs', libs)])
308 n.newline()
309 all_targets += ninja
310
311 n.comment('Tests all build into ninja_test executable.')
312
313 variables = []
314 test_cflags = cflags + ['-DGTEST_HAS_RTTI=0']
315 test_ldflags = None
316 test_libs = libs
317 objs = []
318 if options.with_gtest:
319     path = options.with_gtest
320
321     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
322     if platform == 'windows':
323         gtest_cflags = '/nologo /EHsc /Zi ' + gtest_all_incs
324     else:
325         gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
326     objs += n.build(built('gtest-all' + objext), 'cxx',
327                     os.path.join(path, 'src', 'gtest-all.cc'),
328                     variables=[('cflags', gtest_cflags)])
329     objs += n.build(built('gtest_main' + objext), 'cxx',
330                     os.path.join(path, 'src', 'gtest_main.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              'state_test',
353              'subprocess_test',
354              'test',
355              'util_test']:
356     objs += cxx(name, variables=[('cflags', '$test_cflags')])
357 if platform in ('windows', 'mingw'):
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('Ancillary 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 -b docbook -d book -o $out $in',
397        description='ASCIIDOC $out')
398 n.rule('xsltproc',
399        command='xsltproc --nonet doc/docbook.xsl $in > $out',
400        description='XSLTPROC $out')
401 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
402 manual = n.build(doc('manual.html'), 'xsltproc', xml,
403                  implicit=doc('style.css'))
404 n.build('manual', 'phony',
405         order_only=manual)
406 n.newline()
407
408 n.comment('Generate Doxygen.')
409 n.rule('doxygen',
410        command='doxygen $in',
411        description='DOXYGEN $in')
412 n.variable('doxygen_mainpage_generator',
413            src('gen_doxygen_mainpage.sh'))
414 n.rule('doxygen_mainpage',
415        command='$doxygen_mainpage_generator $in > $out',
416        description='DOXYGEN_MAINPAGE $out')
417 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
418                    ['README', 'COPYING'],
419                    implicit=['$doxygen_mainpage_generator'])
420 n.build('doxygen', 'doxygen', doc('doxygen.config'),
421         implicit=mainpage)
422 n.newline()
423
424 if host != 'mingw':
425     n.comment('Regenerate build files if build script changes.')
426     n.rule('configure',
427            command='${configure_env}%s configure.py $configure_args' %
428                options.with_python,
429            generator=True)
430     n.build('build.ninja', 'configure',
431             implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
432     n.newline()
433
434 n.default(ninja)
435 n.newline()
436
437 if host == 'linux':
438     n.comment('Packaging')
439     n.rule('rpmbuild',
440            command="misc/packaging/rpmbuild.sh",
441            description='Building rpms..')
442     n.build('rpm', 'rpmbuild')
443     n.newline()
444
445 n.build('all', 'phony', all_targets)
446
447 print('wrote %s.' % BUILD_FILENAME)