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

428 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#!/usr/bin/env bash
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# Could run with /bin/sh, but use bash for now, bceause dash has bad errors
113# messages!
114
115. build/ninja-rules-cpp.sh
116
117OILS_PARALLEL_BUILD=${OILS_PARALLEL_BUILD:-1}
118
119_compile_one() {
120 local src=$4
121
122 echo "CXX $src"
123
124 # Delegate to function in build/ninja-rules-cpp.sh
125 if test "${_do_fork:-}" = 1; then
126 compile_one "$@" & # we will wait later
127 else
128 compile_one "$@"
129 fi
130}
131
132main() {
133 ### Compile oils-for-unix into _bin/$compiler-$variant-sh/ (not with ninja)
134
135 local compiler=${1:-cxx} # default is system compiler
136 local variant=${2:-opt} # default is optimized build
137 local skip_rebuild=${3:-} # if the output exists, skip build'
138''' % (argv0), file=f)
139
140 out_dir = '_bin/$compiler-$variant-sh'
141 print(' local out_dir=%s' % out_dir, file=f)
142
143 print('''\
144 local out=$out_dir/oils-for-unix
145
146 if test -n "$skip_rebuild" && test -f "$out"; then
147 echo
148 echo "$0: SKIPPING build because $out exists"
149 echo
150 return
151 fi
152
153 echo
154 echo "$0: Building oils-for-unix: $out"
155 echo
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, file=f)
196 print(' %s %s' % (src, obj_quoted), file=f)
197 print('', file=f)
198
199 print(' # wait for the translation unit before linking', file=f)
200 print(' echo WAIT', file=f)
201 # time -p shows any excess parallelism on 2 cores
202 # example: oils_for_unix.mycpp.cc takes ~8 seconds longer to compile than all
203 # other translation units combined!
204
205 print(' time -p 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 ln -s -f -v $out_name $symlink
230 done
231}
232
233main "$@"
234''', file=f)
235
236
237def Preprocessed(n, cc_sources):
238 # See how much input we're feeding to the compiler. Test C++ template
239 # explosion, e.g. <unordered_map>
240 #
241 # Limit to {dbg,opt} so we don't generate useless rules. Invoked by
242 # metrics/source-code.sh
243
244 pre_matrix = [
245 ('cxx', 'dbg'),
246 ('cxx', 'opt'),
247 ('clang', 'dbg'),
248 ('clang', 'opt'),
249 ]
250 for compiler, variant in pre_matrix:
251 preprocessed = []
252 for src in cc_sources:
253 # e.g. mycpp/gc_heap.cc -> _build/preprocessed/cxx-dbg/mycpp/gc_heap.cc
254 pre = '_build/preprocessed/%s-%s/%s' % (compiler, variant, src)
255 preprocessed.append(pre)
256
257 # Summary file
258 n.build('_build/preprocessed/%s-%s.txt' % (compiler, variant),
259 'line_count',
260 preprocessed)
261 n.newline()
262
263
264def InitSteps(n):
265 """Wrappers for build/ninja-rules-*.sh
266
267 Some of these are defined in mycpp/NINJA_subgraph.py. Could move them here.
268 """
269
270 #
271 # Compiling and linking
272 #
273
274 # Preprocess one translation unit
275 n.rule('preprocess',
276 # compile_one detects the _build/preprocessed path
277 command='build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out',
278 description='PP $compiler $variant $more_cxx_flags $in $out')
279 n.newline()
280
281 n.rule('line_count',
282 command='build/ninja-rules-cpp.sh line_count $out $in',
283 description='line_count $out $in')
284 n.newline()
285
286 # Compile one translation unit
287 n.rule('compile_one',
288 command='build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out $out.d',
289 depfile='$out.d',
290 # no prefix since the compiler is the first arg
291 description='$compiler $variant $more_cxx_flags $in $out')
292 n.newline()
293
294 # Link objects together
295 n.rule('link',
296 command='build/ninja-rules-cpp.sh link $compiler $variant $out $in',
297 description='LINK $compiler $variant $out $in')
298 n.newline()
299
300 # 1 input and 2 outputs
301 n.rule('strip',
302 command='build/ninja-rules-cpp.sh strip_ $in $out',
303 description='STRIP $in $out')
304 n.newline()
305
306 # cc_binary can have symliks
307 n.rule('symlink',
308 command='build/ninja-rules-cpp.sh symlink $dir $target $new',
309 description='SYMLINK $dir $target $new')
310 n.newline()
311
312 #
313 # Code generators
314 #
315
316 n.rule('write-shwrap',
317 # $in must start with main program
318 command='build/ninja-rules-py.sh write-shwrap $template $out $in',
319 description='make-pystub $out $in')
320 n.newline()
321
322 n.rule('gen-oils-for-unix',
323 command='build/ninja-rules-py.sh gen-oils-for-unix $main_name $out_prefix $preamble $in',
324 description='gen-oils-for-unix $main_name $out_prefix $preamble $in')
325 n.newline()
326
327
328def main(argv):
329 try:
330 action = argv[1]
331 except IndexError:
332 action = 'ninja'
333
334 if action == 'ninja':
335 f = open(BUILD_NINJA, 'w')
336 else:
337 f = cStringIO.StringIO() # thrown away
338
339 n = ninja_syntax.Writer(f)
340 ru = ninja_lib.Rules(n)
341
342 ru.comment('InitSteps()')
343 InitSteps(n)
344
345 #
346 # Create the graph.
347 #
348
349 asdl_subgraph.NinjaGraph(ru)
350 ru.comment('')
351
352 bin_subgraph.NinjaGraph(ru)
353 ru.comment('')
354
355 core_subgraph.NinjaGraph(ru)
356 ru.comment('')
357
358 cpp_subgraph.NinjaGraph(ru)
359 ru.comment('')
360
361 data_lang_subgraph.NinjaGraph(ru)
362 ru.comment('')
363
364 frontend_subgraph.NinjaGraph(ru)
365 ru.comment('')
366
367 mycpp_subgraph.NinjaGraph(ru)
368 ru.comment('')
369
370 ysh_subgraph.NinjaGraph(ru)
371 ru.comment('')
372
373 osh_subgraph.NinjaGraph(ru)
374 ru.comment('')
375
376 pea_subgraph.NinjaGraph(ru)
377 ru.comment('')
378
379 prebuilt_subgraph.NinjaGraph(ru)
380 ru.comment('')
381
382 yaks_subgraph.NinjaGraph(ru)
383 ru.comment('')
384
385
386 # Materialize all the cc_binary() rules
387 ru.WriteRules()
388
389 # Collect sources for metrics, tarball, shell script
390 cc_sources = ru.SourcesForBinary('_gen/bin/oils_for_unix.mycpp.cc')
391
392 if 0:
393 from pprint import pprint
394 pprint(cc_sources)
395
396 # TODO: could thin these out, not generate for unit tests, etc.
397 Preprocessed(n, cc_sources)
398
399 ru.WritePhony()
400
401 n.default(['_bin/cxx-asan/osh', '_bin/cxx-asan/ysh'])
402
403 if action == 'ninja':
404 log(' (%s) -> %s (%d targets)', argv[0], BUILD_NINJA,
405 n.num_build_targets())
406
407 elif action == 'shell':
408 out = '_build/oils.sh'
409 with open(out, 'w') as f:
410 ShellFunctions(cc_sources, f, argv[0])
411 log(' (%s) -> %s', argv[0], out)
412
413 elif action == 'tarball-manifest':
414 h = ru.HeadersForBinary('_gen/bin/oils_for_unix.mycpp.cc')
415 TarballManifest(cc_sources + h)
416
417 else:
418 raise RuntimeError('Invalid action %r' % action)
419
420
421if __name__ == '__main__':
422 try:
423 main(sys.argv)
424 except RuntimeError as e:
425 print('FATAL: %s' % e, file=sys.stderr)
426 sys.exit(1)
427
428# vim: sw=2