OILS / build / ninja_main.py View on Github | oilshell.org

497 lines, 231 significant
1#!/usr/bin/env python2
2"""
3build/ninja_main.py - invoked by ./NINJA-config.sh
4
5See build/README.md for the code and data layout.
6"""
7from __future__ import print_function
8
9import cStringIO
10from glob import glob
11import os
12import re
13import sys
14
15from build import ninja_lib
16from build.ninja_lib import log
17
18from asdl import NINJA_subgraph as asdl_subgraph
19from bin import NINJA_subgraph as bin_subgraph
20from core import NINJA_subgraph as core_subgraph
21from cpp import NINJA_subgraph as cpp_subgraph
22from data_lang import NINJA_subgraph as data_lang_subgraph
23from display import NINJA_subgraph as display_subgraph
24from frontend import NINJA_subgraph as frontend_subgraph
25from ysh import NINJA_subgraph as ysh_subgraph
26from osh import NINJA_subgraph as osh_subgraph
27from mycpp import NINJA_subgraph as mycpp_subgraph
28from pea import NINJA_subgraph as pea_subgraph
29from prebuilt import NINJA_subgraph as prebuilt_subgraph
30from yaks import NINJA_subgraph as yaks_subgraph
31
32from vendor import ninja_syntax
33
34# The file Ninja runs by default.
35BUILD_NINJA = 'build.ninja'
36
37
38def TarballManifest(cc_h_files):
39 names = []
40
41 # Code we know about
42 names.extend(cc_h_files)
43
44 names.extend([
45 # Text
46 'LICENSE.txt',
47 'README-native.txt',
48 'INSTALL.txt',
49 'configure',
50 'install',
51 'doc/osh.1',
52
53 # Build Scripts
54 'build/common.sh',
55 'build/native.sh',
56
57 # These 2 are used by build/ninja-rules-cpp.sh
58 'build/py2.sh',
59 'build/dev-shell.sh',
60 'build/ninja-rules-cpp.sh',
61
62 # Generated
63 '_build/oils.sh',
64
65 # These are in build/py.sh, not Ninja. Should probably put them in Ninja.
66 #'_gen/frontend/help_meta.h',
67 '_gen/frontend/match.re2c.h',
68 '_gen/frontend/id_kind.asdl_c.h',
69 '_gen/frontend/types.asdl_c.h',
70 ])
71
72 # For configure
73 names.extend(glob('build/detect-*.c'))
74
75 # TODO: crawl headers
76 # We can now use the headers=[] attribute
77 names.extend(glob('mycpp/*.h'))
78 names.extend(glob('cpp/*.h'))
79
80 # ONLY the headers
81 names.extend(glob('prebuilt/*/*.h'))
82
83 names.sort() # Pass them to tar sorted
84
85 # Check for dupes here
86 unique = sorted(set(names))
87 if names != unique:
88 dupes = [n for n in names if names.count(n) > 1]
89 raise AssertionError("Tarball manifest shouldn't have duplicates: %s" %
90 dupes)
91
92 for name in names:
93 print(name)
94
95
96def ShellFunctions(cc_sources, f, argv0):
97 """
98 Generate a shell script that invokes the same function that build.ninja does
99 """
100 print('''\
101#!/bin/sh
102#
103# _build/oils.sh - generated by %s
104#
105# For usage, run:
106#
107# _build/oils --help
108
109. build/ninja-rules-cpp.sh
110
111show_help() {
112 cat <<'EOF'
113Compile the oils-for-unix source into an executable.
114
115Usage:
116 _build/oils.sh COMPILER? VARIANT? TRANSLATOR? SKIP_REBUILD?
117
118 COMPILER: 'cxx' for system compiler, 'clang' or custom one [default cxx]
119 VARIANT: 'dbg' or 'opt' [default opt]
120 TRANSLATOR: 'mycpp' or 'mycpp-souffle' [default mycpp]
121 SKIP_REBUILD: if non-empty, checks if the output exists before building
122
123Environment variable respected:
124
125 OILS_PARALLEL_BUILD=
126 BASE_CXXFLAGS= # See build/ninja-rules-cpp.sh for details
127 CXXFLAGS=
128 OILS_CXX_VERBOSE=
129
130EOF
131}
132
133parse_flags() {
134 while true; do
135 case "$1" in
136 '')
137 break
138 ;;
139 --help)
140 show_help
141 exit 0
142 ;;
143 *)
144 die "Invalid argument '$1'"
145 ;;
146 esac
147 shift
148 done
149}
150
151
152OILS_PARALLEL_BUILD=${OILS_PARALLEL_BUILD:-1}
153
154_compile_one() {
155 local src=$4
156
157 echo "CXX $src"
158
159 # Delegate to function in build/ninja-rules-cpp.sh
160 if test "${_do_fork:-}" = 1; then
161 compile_one "$@" & # we will wait later
162 else
163 compile_one "$@"
164 fi
165}
166
167main() {
168 ### Compile oils-for-unix into _bin/$compiler-$variant-sh/ (not with ninja)
169
170 parse_flags "$@"
171
172 local compiler=${1:-cxx} # default is system compiler
173 local variant=${2:-opt} # default is optimized build
174 local translator=${3:-mycpp} # default is the translator w/o optimizations
175 local skip_rebuild=${4:-} # if the output exists, skip build'
176''' % (argv0),
177 file=f)
178
179 print('''\
180 local out_dir
181 case $translator in
182 mycpp)
183 out_dir=_bin/$compiler-$variant-sh
184 ;;
185 *)
186 out_dir=_bin/$compiler-$variant-sh/$translator
187 ;;
188 esac
189 local out=$out_dir/oils-for-unix
190
191 if test -n "$skip_rebuild" && test -f "$out"; then
192 echo
193 echo "$0: SKIPPING build because $out exists"
194 echo
195 return
196 fi
197
198 echo
199 echo "$0: Building oils-for-unix: $out"
200 echo "$0: PWD = $PWD"
201 echo
202''',
203 file=f)
204
205 objects = []
206
207 in_out = [
208 ('_gen/bin/oils_for_unix.$translator.cc',
209 '_build/obj/$compiler-$variant-sh/_gen/bin/oils_for_unix.o'),
210 ]
211 for src in sorted(cc_sources):
212 # e.g. _build/obj/cxx-dbg-sh/posix.o
213 prefix, _ = os.path.splitext(src)
214 if prefix.startswith('_gen/bin/oils_for_unix'):
215 continue
216 obj = '_build/obj/$compiler-$variant-sh/%s.o' % prefix
217 in_out.append((src, obj))
218
219
220 bin_dir = '_bin/$compiler-$variant-sh/$translator'
221 obj_dirs = sorted(set(os.path.dirname(obj) for _, obj in in_out))
222
223 all_dirs = [bin_dir] + obj_dirs
224 # Double quote
225 all_dirs = ['"%s"' % d for d in all_dirs]
226
227 print(' mkdir -p \\', file=f)
228 print(' %s' % ' \\\n '.join(all_dirs), file=f)
229 print('', file=f)
230
231 do_fork = ''
232
233 for i, (src, obj) in enumerate(in_out):
234 obj_quoted = '"%s"' % obj
235 objects.append(obj_quoted)
236
237 # Only fork one translation unit that we know to be slow
238 if re.match('.*oils_for_unix\..*\.cc', src):
239 # There should only be one forked translation unit
240 # It can be turned off with OILS_PARALLEL_BUILD= _build/oils
241 assert do_fork == ''
242 do_fork = '_do_fork=$OILS_PARALLEL_BUILD'
243 else:
244 do_fork = ''
245
246 if do_fork:
247 print(' # Potentially fork this translation unit with &', file=f)
248 print(' %s _compile_one "$compiler" "$variant" "" \\' % do_fork,
249 file=f)
250 print(' %s %s' % (src, obj_quoted), file=f)
251 print('', file=f)
252
253 print(' # wait for the translation unit before linking', file=f)
254 print(' echo WAIT', file=f)
255 # time -p shows any excess parallelism on 2 cores
256 # example: oils_for_unix.mycpp.cc takes ~8 seconds longer to compile than all
257 # other translation units combined!
258
259 # Timing isn't POSIX
260 #print(' time -p wait', file=f)
261 print(' wait', file=f)
262 print('', file=f)
263
264 print(' echo "LINK $out"', file=f)
265 # note: can't have spaces in filenames
266 print(' link "$compiler" "$variant" "" "$out" \\', file=f)
267 # put each object on its own line, and indent by 4
268 print(' %s' % (' \\\n '.join(objects)), file=f)
269 print('', file=f)
270
271 # Strip opt binary
272 # TODO: provide a way for the user to get symbols?
273
274 print('''\
275 local out_name=oils-for-unix
276 if test "$variant" = opt; then
277 strip -o "$out.stripped" "$out"
278
279 # Symlink to unstripped binary for benchmarking
280 # out_name=$out_name.stripped
281 fi
282
283 cd $out_dir
284 for symlink in osh ysh; do
285 # like ln -v, which we can't use portably
286 echo " $symlink -> $out_name"
287 ln -s -f $out_name $symlink
288 done
289}
290
291main "$@"
292''',
293 file=f)
294
295
296def Preprocessed(n, cc_sources):
297 # See how much input we're feeding to the compiler. Test C++ template
298 # explosion, e.g. <unordered_map>
299 #
300 # Limit to {dbg,opt} so we don't generate useless rules. Invoked by
301 # metrics/source-code.sh
302
303 pre_matrix = [
304 ('cxx', 'dbg'),
305 ('cxx', 'opt'),
306 ('clang', 'dbg'),
307 ('clang', 'opt'),
308 ]
309 for compiler, variant in pre_matrix:
310 preprocessed = []
311 for src in cc_sources:
312 # e.g. mycpp/gc_heap.cc -> _build/preprocessed/cxx-dbg/mycpp/gc_heap.cc
313 pre = '_build/preprocessed/%s-%s/%s' % (compiler, variant, src)
314 preprocessed.append(pre)
315
316 # Summary file
317 n.build('_build/preprocessed/%s-%s.txt' % (compiler, variant),
318 'line_count', preprocessed)
319 n.newline()
320
321
322def InitSteps(n):
323 """Wrappers for build/ninja-rules-*.sh
324
325 Some of these are defined in mycpp/NINJA_subgraph.py. Could move them here.
326 """
327 #
328 # Compiling and linking
329 #
330
331 # Preprocess one translation unit
332 n.rule(
333 'preprocess',
334 # compile_one detects the _build/preprocessed path
335 command=
336 'build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out',
337 description='PP $compiler $variant $more_cxx_flags $in $out')
338 n.newline()
339
340 n.rule('line_count',
341 command='build/ninja-rules-cpp.sh line_count $out $in',
342 description='line_count $out $in')
343 n.newline()
344
345 # Compile one translation unit
346 n.rule(
347 'compile_one',
348 command=
349 'build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out $out.d',
350 depfile='$out.d',
351 # no prefix since the compiler is the first arg
352 description='$compiler $variant $more_cxx_flags $in $out')
353 n.newline()
354
355 # Link objects together
356 n.rule(
357 'link',
358 command=
359 'build/ninja-rules-cpp.sh link $compiler $variant $more_link_flags $out $in',
360 description='LINK $compiler $variant $more_link_flags $out $in')
361 n.newline()
362
363 # 1 input and 2 outputs
364 n.rule('strip',
365 command='build/ninja-rules-cpp.sh strip_ $in $out',
366 description='STRIP $in $out')
367 n.newline()
368
369 # cc_binary can have symliks
370 n.rule('symlink',
371 command='build/ninja-rules-cpp.sh symlink $dir $target $new',
372 description='SYMLINK $dir $target $new')
373 n.newline()
374
375 #
376 # Code generators
377 #
378
379 n.rule(
380 'write-shwrap',
381 # $in must start with main program
382 command='build/ninja-rules-py.sh write-shwrap $template $out $in',
383 description='make-pystub $out $in')
384 n.newline()
385
386 n.rule(
387 'gen-oils-for-unix',
388 command=
389 'build/ninja-rules-py.sh gen-oils-for-unix $main_name $translator $out_prefix $preamble $extra_mycpp_opts $in',
390 description='gen-oils-for-unix $main_name $translator $out_prefix $preamble $extra_mycpp_opts $in')
391 n.newline()
392
393
394def main(argv):
395 try:
396 action = argv[1]
397 except IndexError:
398 action = 'ninja'
399
400 if action == 'ninja':
401 f = open(BUILD_NINJA, 'w')
402 else:
403 f = cStringIO.StringIO() # thrown away
404
405 n = ninja_syntax.Writer(f)
406 ru = ninja_lib.Rules(n)
407
408 ru.comment('InitSteps()')
409 InitSteps(n)
410
411 #
412 # Create the graph.
413 #
414
415 asdl_subgraph.NinjaGraph(ru)
416 ru.comment('')
417
418 bin_subgraph.NinjaGraph(ru)
419 ru.comment('')
420
421 core_subgraph.NinjaGraph(ru)
422 ru.comment('')
423
424 cpp_subgraph.NinjaGraph(ru)
425 ru.comment('')
426
427 data_lang_subgraph.NinjaGraph(ru)
428 ru.comment('')
429
430 display_subgraph.NinjaGraph(ru)
431 ru.comment('')
432
433 frontend_subgraph.NinjaGraph(ru)
434 ru.comment('')
435
436 mycpp_subgraph.NinjaGraph(ru)
437 ru.comment('')
438
439 ysh_subgraph.NinjaGraph(ru)
440 ru.comment('')
441
442 osh_subgraph.NinjaGraph(ru)
443 ru.comment('')
444
445 pea_subgraph.NinjaGraph(ru)
446 ru.comment('')
447
448 prebuilt_subgraph.NinjaGraph(ru)
449 ru.comment('')
450
451 yaks_subgraph.NinjaGraph(ru)
452 ru.comment('')
453
454 # Materialize all the cc_binary() rules
455 ru.WriteRules()
456
457 # Collect sources for metrics, tarball, shell script
458 cc_sources = ru.SourcesForBinary('_gen/bin/oils_for_unix.mycpp.cc')
459
460 if 0:
461 from pprint import pprint
462 pprint(cc_sources)
463
464 # TODO: could thin these out, not generate for unit tests, etc.
465 Preprocessed(n, cc_sources)
466
467 ru.WritePhony()
468
469 n.default(['_bin/cxx-asan/osh', '_bin/cxx-asan/ysh'])
470
471 if action == 'ninja':
472 log(' (%s) -> %s (%d targets)', argv[0], BUILD_NINJA,
473 n.num_build_targets())
474
475 elif action == 'shell':
476 out = '_build/oils.sh'
477 with open(out, 'w') as f:
478 ShellFunctions(cc_sources, f, argv[0])
479 log(' (%s) -> %s', argv[0], out)
480
481 elif action == 'tarball-manifest':
482 h = ru.HeadersForBinary('_gen/bin/oils_for_unix.mycpp.cc')
483 tar_cc_sources = cc_sources + ['_gen/bin/oils_for_unix.mycpp-souffle.cc']
484 TarballManifest(tar_cc_sources + h)
485
486 else:
487 raise RuntimeError('Invalid action %r' % action)
488
489
490if __name__ == '__main__':
491 try:
492 main(sys.argv)
493 except RuntimeError as e:
494 print('FATAL: %s' % e, file=sys.stderr)
495 sys.exit(1)
496
497# vim: sw=2