Add support for Python 3
[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 optparse import OptionParser
23 import os
24 import sys
25 sys.path.insert(0, 'misc')
26
27 import ninja_syntax
28
29 if sys.version_info[0] == 3:
30     import builtins
31     print_ = getattr(builtins, "print")
32 else:
33     def print_(*args):
34         sys.stdout.write(" ".join(str(x) for x in args))
35         sys.stdout.write("\n")
36
37 parser = OptionParser()
38 platforms = ['linux', 'freebsd', 'solaris', 'mingw', 'windows']
39 profilers = ['gmon', 'pprof']
40 parser.add_option('--platform',
41                   help='target platform (' + '/'.join(platforms) + ')',
42                   choices=platforms)
43 parser.add_option('--host',
44                   help='host platform (' + '/'.join(platforms) + ')',
45                   choices=platforms)
46 parser.add_option('--debug', action='store_true',
47                   help='enable debugging extras',)
48 parser.add_option('--profile', metavar='TYPE',
49                   choices=profilers,
50                   help='enable profiling (' + '/'.join(profilers) + ')',)
51 parser.add_option('--with-gtest', metavar='PATH',
52                   help='use gtest unpacked in directory PATH')
53 parser.add_option('--with-python', metavar='EXE',
54                   help='use EXE as the Python interpreter',
55                   default=os.path.basename(sys.executable))
56 parser.add_option('--with-ninja', metavar='NAME',
57                   help="name for ninja binary for -t msvc (MSVC only)",
58                   default="ninja")
59 (options, args) = parser.parse_args()
60 if args:
61     print_('ERROR: extra unparsed command-line arguments:', args)
62     sys.exit(1)
63
64 platform = options.platform
65 if platform is None:
66     platform = sys.platform
67     if platform.startswith('linux'):
68         platform = 'linux'
69     elif platform.startswith('freebsd'):
70         platform = 'freebsd'
71     elif platform.startswith('solaris'):
72         platform = 'solaris'
73     elif platform.startswith('mingw'):
74         platform = 'mingw'
75     elif platform.startswith('win'):
76         platform = 'windows'
77 host = options.host or platform
78
79 BUILD_FILENAME = 'build.ninja'
80 buildfile = open(BUILD_FILENAME, 'w')
81 n = ninja_syntax.Writer(buildfile)
82 n.comment('This file is used to build ninja itself.')
83 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
84 n.newline()
85
86 n.comment('The arguments passed to configure.py, for rerunning it.')
87 n.variable('configure_args', ' '.join(sys.argv[1:]))
88 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
89 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
90 if configure_env:
91     config_str = ' '.join([k + '=' + configure_env[k] for k in configure_env])
92     n.variable('configure_env', config_str + '$ ')
93 n.newline()
94
95 CXX = configure_env.get('CXX', 'g++')
96 objext = '.o'
97 if platform == 'windows':
98     CXX = 'cl'
99     objext = '.obj'
100
101 def src(filename):
102     return os.path.join('src', filename)
103 def built(filename):
104     return os.path.join('$builddir', filename)
105 def doc(filename):
106     return os.path.join('doc', filename)
107 def cc(name, **kwargs):
108     return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
109 def cxx(name, **kwargs):
110     return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
111 def binary(name):
112     if platform in ('mingw', 'windows'):
113         exe = name + '.exe'
114         n.build(name, 'phony', exe)
115         return exe
116     return name
117
118 n.variable('builddir', 'build')
119 n.variable('cxx', CXX)
120 if platform == 'windows':
121     n.variable('ar', 'link')
122 else:
123     n.variable('ar', configure_env.get('AR', 'ar'))
124
125 if platform == 'windows':
126     cflags = ['/nologo',  # Don't print startup banner.
127               '/Zi',  # Create pdb with debug info.
128               '/W4',  # Highest warning level.
129               '/WX',  # Warnings as errors.
130               '/wd4530', '/wd4100', '/wd4706',
131               '/wd4512', '/wd4800', '/wd4702', '/wd4819',
132               # Disable warnings about passing "this" during initialization.
133               '/wd4355',
134               '/GR-',  # Disable RTTI.
135               # Disable size_t -> int truncation warning.
136               # We never have strings or arrays larger than 2**31.
137               '/wd4267',
138               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
139               '/DNINJA_PYTHON="%s"' % options.with_python]
140     ldflags = ['/DEBUG', '/libpath:$builddir']
141     if not options.debug:
142         cflags += ['/Ox', '/DNDEBUG', '/GL']
143         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
144 else:
145     cflags = ['-g', '-Wall', '-Wextra',
146               '-Wno-deprecated',
147               '-Wno-unused-parameter',
148               '-fno-rtti',
149               '-fno-exceptions',
150               '-fvisibility=hidden', '-pipe',
151               '-Wno-missing-field-initializers',
152               '-DNINJA_PYTHON="%s"' % options.with_python]
153     if options.debug:
154         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
155         cflags.remove('-fno-rtti')  # Needed for above pedanticness.
156     else:
157         cflags += ['-O2', '-DNDEBUG']
158     if 'clang' in os.path.basename(CXX):
159         cflags += ['-fcolor-diagnostics']
160     if platform == 'mingw':
161         cflags += ['-D_WIN32_WINNT=0x0501']
162     ldflags = ['-L$builddir']
163 libs = []
164
165 if platform == 'mingw':
166     cflags.remove('-fvisibility=hidden');
167     ldflags.append('-static')
168 elif platform == 'sunos5':
169     cflags.remove('-fvisibility=hidden')
170 elif platform == 'windows':
171     pass
172 else:
173     if options.profile == 'gmon':
174         cflags.append('-pg')
175         ldflags.append('-pg')
176     elif options.profile == 'pprof':
177         libs.append('-lprofiler')
178
179 def shell_escape(str):
180     """Escape str such that it's interpreted as a single argument by the shell."""
181     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
182     if platform in ('windows', 'mingw'):
183       return str
184     if '"' in str:
185         return "'%s'" % str.replace("'", "\\'")
186     return str
187
188 if 'CFLAGS' in configure_env:
189     cflags.append(configure_env['CFLAGS'])
190 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
191 if 'LDFLAGS' in configure_env:
192     ldflags.append(configure_env['LDFLAGS'])
193 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
194 n.newline()
195
196 if platform == 'windows':
197     compiler = '$cxx'
198     if options.with_ninja:
199         compiler = ('%s -t msvc -o $out -- $cxx /showIncludes' %
200                     options.with_ninja)
201     n.rule('cxx',
202         command='%s $cflags -c $in /Fo$out' % compiler,
203         depfile='$out.d',
204         description='CXX $out')
205 else:
206     n.rule('cxx',
207         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
208         depfile='$out.d',
209         description='CXX $out')
210 n.newline()
211
212 if host == 'windows':
213     n.rule('ar',
214            command='lib /nologo /ltcg /out:$out $in',
215            description='LIB $out')
216 elif host == 'mingw':
217     n.rule('ar',
218            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
219            description='AR $out')
220 else:
221     n.rule('ar',
222            command='rm -f $out && $ar crs $out $in',
223            description='AR $out')
224 n.newline()
225
226 if platform == 'windows':
227     n.rule('link',
228         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
229         description='LINK $out')
230 else:
231     n.rule('link',
232         command='$cxx $ldflags -o $out $in $libs',
233         description='LINK $out')
234 n.newline()
235
236 objs = []
237
238 if platform not in ('solaris', 'mingw', 'windows'):
239     n.comment('browse_py.h is used to inline browse.py.')
240     n.rule('inline',
241            command='src/inline.sh $varname < $in > $out',
242            description='INLINE $out')
243     n.build(built('browse_py.h'), 'inline', src('browse.py'),
244             implicit='src/inline.sh',
245             variables=[('varname', 'kBrowsePy')])
246     n.newline()
247
248     objs += cxx('browse', order_only=built('browse_py.h'))
249     n.newline()
250
251 n.comment('the depfile parser and ninja lexers are generated using re2c.')
252 def has_re2c():
253     import subprocess
254     try:
255         proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
256         return int(proc.communicate()[0], 10) >= 1103
257     except OSError:
258         return False
259 if has_re2c():
260     n.rule('re2c',
261            command='re2c -b -i --no-generation-date -o $out $in',
262            description='RE2C $out')
263     # Generate the .cc files in the source directory so we can check them in.
264     n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
265     n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
266 else:
267     print_("warning: A compatible version of re2c (>= 0.11.3) was not found; "
268            "changes to src/*.in.cc will not affect your build.")
269 n.newline()
270
271 n.comment('Core source files all build into ninja library.')
272 for name in ['build',
273              'build_log',
274              'clean',
275              'depfile_parser',
276              'disk_interface',
277              'edit_distance',
278              'eval_env',
279              'explain',
280              'graph',
281              'graphviz',
282              'lexer',
283              'manifest_parser',
284              'metrics',
285              'state',
286              'util']:
287     objs += cxx(name)
288 if platform in ('mingw', 'windows'):
289     for name in ['subprocess-win32',
290                  'includes_normalize-win32',
291                  'msvc_helper-win32',
292                  'msvc_helper_main-win32']:
293         objs += cxx(name)
294     if platform == 'windows':
295         objs += cxx('minidump-win32')
296     objs += cc('getopt')
297 else:
298     objs += cxx('subprocess-posix')
299 if platform == 'windows':
300     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
301 else:
302     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
303 n.newline()
304
305 if platform == 'windows':
306     libs.append('ninja.lib')
307 else:
308     libs.append('-lninja')
309
310 all_targets = []
311
312 n.comment('Main executable is library plus main() function.')
313 objs = cxx('ninja')
314 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
315                 variables=[('libs', libs)])
316 n.newline()
317 all_targets += ninja
318
319 n.comment('Tests all build into ninja_test executable.')
320
321 variables = []
322 test_cflags = None
323 test_ldflags = None
324 test_libs = libs
325 objs = []
326 if options.with_gtest:
327     path = options.with_gtest
328
329     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
330     if platform == 'windows':
331         gtest_cflags = '/nologo /EHsc /Zi ' + gtest_all_incs
332     else:
333         gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
334     objs += n.build(built('gtest-all' + objext), 'cxx',
335                     os.path.join(path, 'src', 'gtest-all.cc'),
336                     variables=[('cflags', gtest_cflags)])
337     objs += n.build(built('gtest_main' + objext), 'cxx',
338                     os.path.join(path, 'src', 'gtest_main.cc'),
339                     variables=[('cflags', gtest_cflags)])
340
341     test_cflags = cflags + ['-DGTEST_HAS_RTTI=0',
342                             '-I%s' % os.path.join(path, 'include')]
343 elif platform == 'windows':
344     test_libs.extend(['gtest_main.lib', 'gtest.lib'])
345 else:
346     test_libs.extend(['-lgtest_main', '-lgtest'])
347
348 for name in ['build_log_test',
349              'build_test',
350              'clean_test',
351              'depfile_parser_test',
352              'disk_interface_test',
353              'edit_distance_test',
354              'graph_test',
355              'lexer_test',
356              'manifest_parser_test',
357              'state_test',
358              'subprocess_test',
359              'test',
360              'util_test']:
361     objs += cxx(name, variables=[('cflags', test_cflags)])
362 if platform in ('windows', 'mingw'):
363     for name in ['includes_normalize_test', 'msvc_helper_test']:
364         objs += cxx(name, variables=[('cflags', test_cflags)])
365
366 if platform != 'mingw' and platform != 'windows':
367     test_libs.append('-lpthread')
368 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
369                      variables=[('ldflags', test_ldflags),
370                                 ('libs', test_libs)])
371 n.newline()
372 all_targets += ninja_test
373
374
375 n.comment('Ancillary executables.')
376 objs = cxx('parser_perftest')
377 all_targets += n.build(binary('parser_perftest'), 'link', objs,
378                        implicit=ninja_lib, variables=[('libs', libs)])
379 objs = cxx('build_log_perftest')
380 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
381                        implicit=ninja_lib, variables=[('libs', libs)])
382 objs = cxx('canon_perftest')
383 all_targets += n.build(binary('canon_perftest'), 'link', objs,
384                        implicit=ninja_lib, variables=[('libs', libs)])
385 objs = cxx('hash_collision_bench')
386 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
387                               implicit=ninja_lib, variables=[('libs', libs)])
388 n.newline()
389
390 n.comment('Generate a graph using the "graph" tool.')
391 n.rule('gendot',
392        command='./ninja -t graph all > $out')
393 n.rule('gengraph',
394        command='dot -Tpng $in > $out')
395 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
396 n.build('graph.png', 'gengraph', dot)
397 n.newline()
398
399 n.comment('Generate the manual using asciidoc.')
400 n.rule('asciidoc',
401        command='asciidoc -a toc -a max-width=45em -o $out $in',
402        description='ASCIIDOC $in')
403 manual = n.build(doc('manual.html'), 'asciidoc', doc('manual.asciidoc'))
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)