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

443 lines, 226 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
7"""
8from __future__ import print_function
9
10import cStringIO
11from glob import glob
12import os
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# Usage:
106# _build/oils.sh COMPILER? VARIANT? SKIP_REBUILD?
107#
108# COMPILER: 'cxx' for system compiler, 'clang' or custom one [default cxx]
109# VARIANT: 'dbg' or 'opt' [default opt]
110# SKIP_REBUILD: if non-empty, checks if the output exists before building
111
112. build/ninja-rules-cpp.sh
113
114OILS_PARALLEL_BUILD=${OILS_PARALLEL_BUILD:-1}
115
116_compile_one() {
117 local src=$4
118
119 echo "CXX $src"
120
121 # Delegate to function in build/ninja-rules-cpp.sh
122 if test "${_do_fork:-}" = 1; then
123 compile_one "$@" & # we will wait later
124 else
125 compile_one "$@"
126 fi
127}
128
129main() {
130 ### Compile oils-for-unix into _bin/$compiler-$variant-sh/ (not with ninja)
131
132 local compiler=${1:-cxx} # default is system compiler
133 local variant=${2:-opt} # default is optimized build
134 local skip_rebuild=${3:-} # if the output exists, skip build'
135''' % (argv0),
136 file=f)
137
138 out_dir = '_bin/$compiler-$variant-sh'
139 print(' local out_dir=%s' % out_dir, file=f)
140
141 print('''\
142 local out=$out_dir/oils-for-unix
143
144 if test -n "$skip_rebuild" && test -f "$out"; then
145 echo
146 echo "$0: SKIPPING build because $out exists"
147 echo
148 return
149 fi
150
151 echo
152 echo "$0: Building oils-for-unix: $out"
153 echo "$0: PWD = $PWD"
154 echo
155''',
156 file=f)
157
158 objects = []
159
160 in_out = []
161 for src in sorted(cc_sources):
162 # e.g. _build/obj/cxx-dbg-sh/posix.o
163 prefix, _ = os.path.splitext(src)
164 obj = '_build/obj/$compiler-$variant-sh/%s.o' % prefix
165 in_out.append((src, obj))
166
167 bin_dir = '_bin/$compiler-$variant-sh'
168 obj_dirs = sorted(set(os.path.dirname(obj) for _, obj in in_out))
169
170 all_dirs = [bin_dir] + obj_dirs
171 # Double quote
172 all_dirs = ['"%s"' % d for d in all_dirs]
173
174 print(' mkdir -p \\', file=f)
175 print(' %s' % ' \\\n '.join(all_dirs), file=f)
176 print('', file=f)
177
178 do_fork = ''
179
180 for i, (src, obj) in enumerate(in_out):
181 obj_quoted = '"%s"' % obj
182 objects.append(obj_quoted)
183
184 # Only fork one translation unit that we know to be slow
185 if 'oils_for_unix.mycpp.cc' in src:
186 # There should only be one forked translation unit
187 # It can be turned off with OILS_PARALLEL_BUILD= _build/oils
188 assert do_fork == ''
189 do_fork = '_do_fork=$OILS_PARALLEL_BUILD'
190 else:
191 do_fork = ''
192
193 if do_fork:
194 print(' # Potentially fork this translation unit with &', file=f)
195 print(' %s _compile_one "$compiler" "$variant" "" \\' % do_fork,
196 file=f)
197 print(' %s %s' % (src, obj_quoted), file=f)
198 print('', file=f)
199
200 print(' # wait for the translation unit before linking', file=f)
201 print(' echo WAIT', file=f)
202 # time -p shows any excess parallelism on 2 cores
203 # example: oils_for_unix.mycpp.cc takes ~8 seconds longer to compile than all
204 # other translation units combined!
205
206 # Timing isn't POSIX
207 #print(' time -p wait', file=f)
208 print(' wait', file=f)
209 print('', file=f)
210
211 print(' echo "LINK $out"', file=f)
212 # note: can't have spaces in filenames
213 print(' link "$compiler" "$variant" "" "$out" \\', file=f)
214 # put each object on its own line, and indent by 4
215 print(' %s' % (' \\\n '.join(objects)), file=f)
216 print('', file=f)
217
218 # Strip opt binary
219 # TODO: provide a way for the user to get symbols?
220
221 print('''\
222 local out_name=oils-for-unix
223 if test "$variant" = opt; then
224 strip -o "$out.stripped" "$out"
225
226 # Symlink to unstripped binary for benchmarking
227 # out_name=$out_name.stripped
228 fi
229
230 cd $out_dir
231 for symlink in osh ysh; do
232 # like ln -v, which we can't use portably
233 echo " $symlink -> $out_name"
234 ln -s -f $out_name $symlink
235 done
236}
237
238main "$@"
239''',
240 file=f)
241
242
243def Preprocessed(n, cc_sources):
244 # See how much input we're feeding to the compiler. Test C++ template
245 # explosion, e.g. <unordered_map>
246 #
247 # Limit to {dbg,opt} so we don't generate useless rules. Invoked by
248 # metrics/source-code.sh
249
250 pre_matrix = [
251 ('cxx', 'dbg'),
252 ('cxx', 'opt'),
253 ('clang', 'dbg'),
254 ('clang', 'opt'),
255 ]
256 for compiler, variant in pre_matrix:
257 preprocessed = []
258 for src in cc_sources:
259 # e.g. mycpp/gc_heap.cc -> _build/preprocessed/cxx-dbg/mycpp/gc_heap.cc
260 pre = '_build/preprocessed/%s-%s/%s' % (compiler, variant, src)
261 preprocessed.append(pre)
262
263 # Summary file
264 n.build('_build/preprocessed/%s-%s.txt' % (compiler, variant),
265 'line_count', preprocessed)
266 n.newline()
267
268
269def InitSteps(n):
270 """Wrappers for build/ninja-rules-*.sh
271
272 Some of these are defined in mycpp/NINJA_subgraph.py. Could move them here.
273 """
274 #
275 # Compiling and linking
276 #
277
278 # Preprocess one translation unit
279 n.rule(
280 'preprocess',
281 # compile_one detects the _build/preprocessed path
282 command=
283 'build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out',
284 description='PP $compiler $variant $more_cxx_flags $in $out')
285 n.newline()
286
287 n.rule('line_count',
288 command='build/ninja-rules-cpp.sh line_count $out $in',
289 description='line_count $out $in')
290 n.newline()
291
292 # Compile one translation unit
293 n.rule(
294 'compile_one',
295 command=
296 'build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out $out.d',
297 depfile='$out.d',
298 # no prefix since the compiler is the first arg
299 description='$compiler $variant $more_cxx_flags $in $out')
300 n.newline()
301
302 # Link objects together
303 n.rule(
304 'link',
305 command=
306 'build/ninja-rules-cpp.sh link $compiler $variant $more_link_flags $out $in',
307 description='LINK $compiler $variant $more_link_flags $out $in')
308 n.newline()
309
310 # 1 input and 2 outputs
311 n.rule('strip',
312 command='build/ninja-rules-cpp.sh strip_ $in $out',
313 description='STRIP $in $out')
314 n.newline()
315
316 # cc_binary can have symliks
317 n.rule('symlink',
318 command='build/ninja-rules-cpp.sh symlink $dir $target $new',
319 description='SYMLINK $dir $target $new')
320 n.newline()
321
322 #
323 # Code generators
324 #
325
326 n.rule(
327 'write-shwrap',
328 # $in must start with main program
329 command='build/ninja-rules-py.sh write-shwrap $template $out $in',
330 description='make-pystub $out $in')
331 n.newline()
332
333 n.rule(
334 'gen-oils-for-unix',
335 command=
336 'build/ninja-rules-py.sh gen-oils-for-unix $main_name $out_prefix $preamble $extra_mycpp_opts $in',
337 description='gen-oils-for-unix $main_name $out_prefix $preamble $extra_mycpp_opts $in')
338 n.newline()
339
340
341def main(argv):
342 try:
343 action = argv[1]
344 except IndexError:
345 action = 'ninja'
346
347 if action == 'ninja':
348 f = open(BUILD_NINJA, 'w')
349 else:
350 f = cStringIO.StringIO() # thrown away
351
352 n = ninja_syntax.Writer(f)
353 ru = ninja_lib.Rules(n)
354
355 ru.comment('InitSteps()')
356 InitSteps(n)
357
358 #
359 # Create the graph.
360 #
361
362 asdl_subgraph.NinjaGraph(ru)
363 ru.comment('')
364
365 bin_subgraph.NinjaGraph(ru)
366 ru.comment('')
367
368 core_subgraph.NinjaGraph(ru)
369 ru.comment('')
370
371 cpp_subgraph.NinjaGraph(ru)
372 ru.comment('')
373
374 data_lang_subgraph.NinjaGraph(ru)
375 ru.comment('')
376
377 display_subgraph.NinjaGraph(ru)
378 ru.comment('')
379
380 frontend_subgraph.NinjaGraph(ru)
381 ru.comment('')
382
383 mycpp_subgraph.NinjaGraph(ru)
384 ru.comment('')
385
386 ysh_subgraph.NinjaGraph(ru)
387 ru.comment('')
388
389 osh_subgraph.NinjaGraph(ru)
390 ru.comment('')
391
392 pea_subgraph.NinjaGraph(ru)
393 ru.comment('')
394
395 prebuilt_subgraph.NinjaGraph(ru)
396 ru.comment('')
397
398 yaks_subgraph.NinjaGraph(ru)
399 ru.comment('')
400
401 # Materialize all the cc_binary() rules
402 ru.WriteRules()
403
404 # Collect sources for metrics, tarball, shell script
405 cc_sources = ru.SourcesForBinary('_gen/bin/oils_for_unix.mycpp.cc')
406
407 if 0:
408 from pprint import pprint
409 pprint(cc_sources)
410
411 # TODO: could thin these out, not generate for unit tests, etc.
412 Preprocessed(n, cc_sources)
413
414 ru.WritePhony()
415
416 n.default(['_bin/cxx-asan/osh', '_bin/cxx-asan/ysh'])
417
418 if action == 'ninja':
419 log(' (%s) -> %s (%d targets)', argv[0], BUILD_NINJA,
420 n.num_build_targets())
421
422 elif action == 'shell':
423 out = '_build/oils.sh'
424 with open(out, 'w') as f:
425 ShellFunctions(cc_sources, f, argv[0])
426 log(' (%s) -> %s', argv[0], out)
427
428 elif action == 'tarball-manifest':
429 h = ru.HeadersForBinary('_gen/bin/oils_for_unix.mycpp.cc')
430 TarballManifest(cc_sources + h)
431
432 else:
433 raise RuntimeError('Invalid action %r' % action)
434
435
436if __name__ == '__main__':
437 try:
438 main(sys.argv)
439 except RuntimeError as e:
440 print('FATAL: %s' % e, file=sys.stderr)
441 sys.exit(1)
442
443# vim: sw=2