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

430 lines, 210 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 frontend import NINJA_subgraph as frontend_subgraph
24from ysh import NINJA_subgraph as ysh_subgraph
25from osh import NINJA_subgraph as osh_subgraph
26from mycpp import NINJA_subgraph as mycpp_subgraph
27from pea import NINJA_subgraph as pea_subgraph
28from prebuilt import NINJA_subgraph as prebuilt_subgraph
29from yaks import NINJA_subgraph as yaks_subgraph
30
31from vendor import ninja_syntax
32
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 'configure',
49 'install',
50 'doc/osh.1',
51
52 # Build Scripts
53 'build/common.sh',
54 'build/native.sh',
55
56 # These 2 are used by build/ninja-rules-cpp.sh
57 'build/py2.sh',
58 'build/dev-shell.sh',
59
60 'build/ninja-rules-cpp.sh',
61 'mycpp/common.sh',
62
63 # Generated
64 '_build/oils.sh',
65
66 # These are in build/py.sh, not Ninja. Should probably put them in Ninja.
67 #'_gen/frontend/help_meta.h',
68 '_gen/frontend/match.re2c.h',
69 '_gen/frontend/id_kind.asdl_c.h',
70 '_gen/frontend/types.asdl_c.h',
71 ])
72
73 # For configure
74 names.extend(glob('build/detect-*.c'))
75
76 # TODO: crawl headers
77 # We can now use the headers=[] attribute
78 names.extend(glob('mycpp/*.h'))
79 names.extend(glob('cpp/*.h'))
80
81 # ONLY the headers
82 names.extend(glob('prebuilt/*/*.h'))
83
84 names.sort() # Pass them to tar sorted
85
86 # Check for dupes here
87 unique = sorted(set(names))
88 if names != unique:
89 dupes = [n for n in names if names.count(n) > 1]
90 raise AssertionError("Tarball manifest shouldn't have duplicates: %s" % 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, or 'clang' [default cxx]
109# VARIANT: 'dbg' or 'opt' [default dbg]
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), file=f)
136
137 out_dir = '_bin/$compiler-$variant-sh'
138 print(' local out_dir=%s' % out_dir, file=f)
139
140 print('''\
141 local out=$out_dir/oils-for-unix
142
143 if test -n "$skip_rebuild" && test -f "$out"; then
144 echo
145 echo "$0: SKIPPING build because $out exists"
146 echo
147 return
148 fi
149
150 echo
151 echo "$0: Building oils-for-unix: $out"
152 echo "$0: PWD = $PWD"
153 echo
154''', file=f)
155
156 objects = []
157
158 in_out = []
159 for src in sorted(cc_sources):
160 # e.g. _build/obj/cxx-dbg-sh/posix.o
161 prefix, _ = os.path.splitext(src)
162 obj = '_build/obj/$compiler-$variant-sh/%s.o' % prefix
163 in_out.append((src, obj))
164
165 bin_dir = '_bin/$compiler-$variant-sh'
166 obj_dirs = sorted(set(os.path.dirname(obj) for _, obj in in_out))
167
168 all_dirs = [bin_dir] + obj_dirs
169 # Double quote
170 all_dirs = ['"%s"' % d for d in all_dirs]
171
172 print(' mkdir -p \\', file=f)
173 print(' %s' % ' \\\n '.join(all_dirs), file=f)
174 print('', file=f)
175
176 do_fork = ''
177
178 for i, (src, obj) in enumerate(in_out):
179 obj_quoted = '"%s"' % obj
180 objects.append(obj_quoted)
181
182 # Only fork one translation unit that we know to be slow
183 if 'oils_for_unix.mycpp.cc' in src:
184 # There should only be one forked translation unit
185 # It can be turned off with OILS_PARALLEL_BUILD= _build/oils
186 assert do_fork == ''
187 do_fork = '_do_fork=$OILS_PARALLEL_BUILD'
188 else:
189 do_fork = ''
190
191 if do_fork:
192 print(' # Potentially fork this translation unit with &', file=f)
193 print(' %s _compile_one "$compiler" "$variant" "" \\' % do_fork, file=f)
194 print(' %s %s' % (src, obj_quoted), file=f)
195 print('', file=f)
196
197 print(' # wait for the translation unit before linking', file=f)
198 print(' echo WAIT', file=f)
199 # time -p shows any excess parallelism on 2 cores
200 # example: oils_for_unix.mycpp.cc takes ~8 seconds longer to compile than all
201 # other translation units combined!
202
203 # Timing isn't POSIX
204 #print(' time -p wait', file=f)
205 print(' wait', file=f)
206 print('', file=f)
207
208 print(' echo "LINK $out"', file=f)
209 # note: can't have spaces in filenames
210 print(' link "$compiler" "$variant" "$out" \\', file=f)
211 # put each object on its own line, and indent by 4
212 print(' %s' % (' \\\n '.join(objects)), file=f)
213 print('', file=f)
214
215 # Strip opt binary
216 # TODO: provide a way for the user to get symbols?
217
218 print('''\
219 local out_name=oils-for-unix
220 if test "$variant" = opt; then
221 strip -o "$out.stripped" "$out"
222
223 # Symlink to unstripped binary for benchmarking
224 # out_name=$out_name.stripped
225 fi
226
227 cd $out_dir
228 for symlink in osh ysh; do
229 # like ln -v, which we can't use portably
230 echo " $symlink -> $out_name"
231 ln -s -f $out_name $symlink
232 done
233}
234
235main "$@"
236''', file=f)
237
238
239def Preprocessed(n, cc_sources):
240 # See how much input we're feeding to the compiler. Test C++ template
241 # explosion, e.g. <unordered_map>
242 #
243 # Limit to {dbg,opt} so we don't generate useless rules. Invoked by
244 # metrics/source-code.sh
245
246 pre_matrix = [
247 ('cxx', 'dbg'),
248 ('cxx', 'opt'),
249 ('clang', 'dbg'),
250 ('clang', 'opt'),
251 ]
252 for compiler, variant in pre_matrix:
253 preprocessed = []
254 for src in cc_sources:
255 # e.g. mycpp/gc_heap.cc -> _build/preprocessed/cxx-dbg/mycpp/gc_heap.cc
256 pre = '_build/preprocessed/%s-%s/%s' % (compiler, variant, src)
257 preprocessed.append(pre)
258
259 # Summary file
260 n.build('_build/preprocessed/%s-%s.txt' % (compiler, variant),
261 'line_count',
262 preprocessed)
263 n.newline()
264
265
266def InitSteps(n):
267 """Wrappers for build/ninja-rules-*.sh
268
269 Some of these are defined in mycpp/NINJA_subgraph.py. Could move them here.
270 """
271
272 #
273 # Compiling and linking
274 #
275
276 # Preprocess one translation unit
277 n.rule('preprocess',
278 # compile_one detects the _build/preprocessed path
279 command='build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out',
280 description='PP $compiler $variant $more_cxx_flags $in $out')
281 n.newline()
282
283 n.rule('line_count',
284 command='build/ninja-rules-cpp.sh line_count $out $in',
285 description='line_count $out $in')
286 n.newline()
287
288 # Compile one translation unit
289 n.rule('compile_one',
290 command='build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out $out.d',
291 depfile='$out.d',
292 # no prefix since the compiler is the first arg
293 description='$compiler $variant $more_cxx_flags $in $out')
294 n.newline()
295
296 # Link objects together
297 n.rule('link',
298 command='build/ninja-rules-cpp.sh link $compiler $variant $out $in',
299 description='LINK $compiler $variant $out $in')
300 n.newline()
301
302 # 1 input and 2 outputs
303 n.rule('strip',
304 command='build/ninja-rules-cpp.sh strip_ $in $out',
305 description='STRIP $in $out')
306 n.newline()
307
308 # cc_binary can have symliks
309 n.rule('symlink',
310 command='build/ninja-rules-cpp.sh symlink $dir $target $new',
311 description='SYMLINK $dir $target $new')
312 n.newline()
313
314 #
315 # Code generators
316 #
317
318 n.rule('write-shwrap',
319 # $in must start with main program
320 command='build/ninja-rules-py.sh write-shwrap $template $out $in',
321 description='make-pystub $out $in')
322 n.newline()
323
324 n.rule('gen-oils-for-unix',
325 command='build/ninja-rules-py.sh gen-oils-for-unix $main_name $out_prefix $preamble $in',
326 description='gen-oils-for-unix $main_name $out_prefix $preamble $in')
327 n.newline()
328
329
330def main(argv):
331 try:
332 action = argv[1]
333 except IndexError:
334 action = 'ninja'
335
336 if action == 'ninja':
337 f = open(BUILD_NINJA, 'w')
338 else:
339 f = cStringIO.StringIO() # thrown away
340
341 n = ninja_syntax.Writer(f)
342 ru = ninja_lib.Rules(n)
343
344 ru.comment('InitSteps()')
345 InitSteps(n)
346
347 #
348 # Create the graph.
349 #
350
351 asdl_subgraph.NinjaGraph(ru)
352 ru.comment('')
353
354 bin_subgraph.NinjaGraph(ru)
355 ru.comment('')
356
357 core_subgraph.NinjaGraph(ru)
358 ru.comment('')
359
360 cpp_subgraph.NinjaGraph(ru)
361 ru.comment('')
362
363 data_lang_subgraph.NinjaGraph(ru)
364 ru.comment('')
365
366 frontend_subgraph.NinjaGraph(ru)
367 ru.comment('')
368
369 mycpp_subgraph.NinjaGraph(ru)
370 ru.comment('')
371
372 ysh_subgraph.NinjaGraph(ru)
373 ru.comment('')
374
375 osh_subgraph.NinjaGraph(ru)
376 ru.comment('')
377
378 pea_subgraph.NinjaGraph(ru)
379 ru.comment('')
380
381 prebuilt_subgraph.NinjaGraph(ru)
382 ru.comment('')
383
384 yaks_subgraph.NinjaGraph(ru)
385 ru.comment('')
386
387
388 # Materialize all the cc_binary() rules
389 ru.WriteRules()
390
391 # Collect sources for metrics, tarball, shell script
392 cc_sources = ru.SourcesForBinary('_gen/bin/oils_for_unix.mycpp.cc')
393
394 if 0:
395 from pprint import pprint
396 pprint(cc_sources)
397
398 # TODO: could thin these out, not generate for unit tests, etc.
399 Preprocessed(n, cc_sources)
400
401 ru.WritePhony()
402
403 n.default(['_bin/cxx-asan/osh', '_bin/cxx-asan/ysh'])
404
405 if action == 'ninja':
406 log(' (%s) -> %s (%d targets)', argv[0], BUILD_NINJA,
407 n.num_build_targets())
408
409 elif action == 'shell':
410 out = '_build/oils.sh'
411 with open(out, 'w') as f:
412 ShellFunctions(cc_sources, f, argv[0])
413 log(' (%s) -> %s', argv[0], out)
414
415 elif action == 'tarball-manifest':
416 h = ru.HeadersForBinary('_gen/bin/oils_for_unix.mycpp.cc')
417 TarballManifest(cc_sources + h)
418
419 else:
420 raise RuntimeError('Invalid action %r' % action)
421
422
423if __name__ == '__main__':
424 try:
425 main(sys.argv)
426 except RuntimeError as e:
427 print('FATAL: %s' % e, file=sys.stderr)
428 sys.exit(1)
429
430# vim: sw=2