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

440 lines, 232 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 fragment that invokes the same function that build.ninja
99 does
100 """
101 print('''\
102main() {
103 ### Compile oils-for-unix into _bin/$compiler-$variant-sh/ (not with ninja)
104
105 parse_flags "$@"
106
107 # Copy into locals
108 local compiler=$FLAG_cxx
109 local variant=$FLAG_variant
110 local translator=$FLAG_translator
111 local skip_rebuild=$FLAG_skip_rebuild
112
113 local out_dir
114 case $translator in
115 mycpp)
116 out_dir=_bin/$compiler-$variant-sh
117 ;;
118 *)
119 out_dir=_bin/$compiler-$variant-sh/$translator
120 ;;
121 esac
122 local out=$out_dir/oils-for-unix
123
124 echo
125 echo "$0: Building oils-for-unix: $out"
126 echo " PWD = $PWD"
127 echo " cxx = $compiler"
128 echo " variant = $variant"
129 echo " translator = $translator"
130 if test -n "$skip_rebuild"; then
131 echo " skip_rebuild = $skip_rebuild"
132 fi
133
134 if test -n "$skip_rebuild" && test -f "$out"; then
135 echo
136 echo "$0: SKIPPING build because $out exists"
137 echo
138 return
139 fi
140
141 echo
142''',
143 file=f)
144
145 objects = []
146
147 in_out = [
148 ('_gen/bin/oils_for_unix.$translator.cc',
149 '_build/obj/$compiler-$variant-sh/_gen/bin/oils_for_unix.o'),
150 ]
151 for src in sorted(cc_sources):
152 # e.g. _build/obj/cxx-dbg-sh/posix.o
153 prefix, _ = os.path.splitext(src)
154 if prefix.startswith('_gen/bin/oils_for_unix'):
155 continue
156 obj = '_build/obj/$compiler-$variant-sh/%s.o' % prefix
157 in_out.append((src, obj))
158
159 bin_dir = '_bin/$compiler-$variant-sh/$translator'
160 obj_dirs = sorted(set(os.path.dirname(obj) for _, obj in in_out))
161
162 all_dirs = [bin_dir] + obj_dirs
163 # Double quote
164 all_dirs = ['"%s"' % d for d in all_dirs]
165
166 print(' mkdir -p \\', file=f)
167 print(' %s' % ' \\\n '.join(all_dirs), file=f)
168 print('', file=f)
169
170 do_fork = ''
171
172 for i, (src, obj) in enumerate(in_out):
173 obj_quoted = '"%s"' % obj
174 objects.append(obj_quoted)
175
176 # Only fork one translation unit that we know to be slow
177 if re.match('.*oils_for_unix\..*\.cc', src):
178 # There should only be one forked translation unit
179 # It can be turned off with OILS_PARALLEL_BUILD= _build/oils
180 assert do_fork == ''
181 do_fork = '_do_fork=$OILS_PARALLEL_BUILD'
182 else:
183 do_fork = ''
184
185 if do_fork:
186 print(' # Potentially fork this translation unit with &', file=f)
187 print(' %s \\' % do_fork, file=f)
188 indent = ' ' if do_fork else ''
189 print(' %s_compile_one "$compiler" "$variant" "" \\' % indent, file=f)
190 print(' %s %s' % (src, obj_quoted), file=f)
191 if do_fork:
192 print(
193 ' _do_fork= # work around bug in some versions of the dash shell',
194 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''',
237 file=f)
238
239
240def Preprocessed(n, cc_sources):
241 # See how much input we're feeding to the compiler. Test C++ template
242 # explosion, e.g. <unordered_map>
243 #
244 # Limit to {dbg,opt} so we don't generate useless rules. Invoked by
245 # metrics/source-code.sh
246
247 pre_matrix = [
248 ('cxx', 'dbg'),
249 ('cxx', 'opt'),
250 ('clang', 'dbg'),
251 ('clang', 'opt'),
252 ]
253 for compiler, variant in pre_matrix:
254 preprocessed = []
255 for src in cc_sources:
256 # e.g. mycpp/gc_heap.cc -> _build/preprocessed/cxx-dbg/mycpp/gc_heap.cc
257 pre = '_build/preprocessed/%s-%s/%s' % (compiler, variant, src)
258 preprocessed.append(pre)
259
260 # Summary file
261 n.build('_build/preprocessed/%s-%s.txt' % (compiler, variant),
262 'line_count', 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 # Compiling and linking
273 #
274
275 # Preprocess one translation unit
276 n.rule(
277 'preprocess',
278 # compile_one detects the _build/preprocessed path
279 command=
280 'build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out',
281 description='PP $compiler $variant $more_cxx_flags $in $out')
282 n.newline()
283
284 n.rule('line_count',
285 command='build/ninja-rules-cpp.sh line_count $out $in',
286 description='line_count $out $in')
287 n.newline()
288
289 # Compile one translation unit
290 n.rule(
291 'compile_one',
292 command=
293 'build/ninja-rules-cpp.sh compile_one $compiler $variant $more_cxx_flags $in $out $out.d',
294 depfile='$out.d',
295 # no prefix since the compiler is the first arg
296 description='$compiler $variant $more_cxx_flags $in $out')
297 n.newline()
298
299 # Link objects together
300 n.rule(
301 'link',
302 command=
303 'build/ninja-rules-cpp.sh link $compiler $variant $more_link_flags $out $in',
304 description='LINK $compiler $variant $more_link_flags $out $in')
305 n.newline()
306
307 # 1 input and 2 outputs
308 n.rule('strip',
309 command='build/ninja-rules-cpp.sh strip_ $in $out',
310 description='STRIP $in $out')
311 n.newline()
312
313 # cc_binary can have symliks
314 n.rule('symlink',
315 command='build/ninja-rules-cpp.sh symlink $dir $target $new',
316 description='SYMLINK $dir $target $new')
317 n.newline()
318
319 #
320 # Code generators
321 #
322
323 n.rule(
324 'write-shwrap',
325 # $in must start with main program
326 command='build/ninja-rules-py.sh write-shwrap $template $out $in',
327 description='make-pystub $out $in')
328 n.newline()
329
330 n.rule(
331 'gen-oils-for-unix',
332 command=
333 'build/ninja-rules-py.sh gen-oils-for-unix $main_name $translator $out_prefix $preamble $extra_mycpp_opts $in',
334 description=
335 'gen-oils-for-unix $main_name $translator $out_prefix $preamble $extra_mycpp_opts $in'
336 )
337 n.newline()
338
339
340def main(argv):
341 try:
342 action = argv[1]
343 except IndexError:
344 action = 'ninja'
345
346 if action == 'ninja':
347 f = open(BUILD_NINJA, 'w')
348 else:
349 f = cStringIO.StringIO() # thrown away
350
351 n = ninja_syntax.Writer(f)
352 ru = ninja_lib.Rules(n)
353
354 ru.comment('InitSteps()')
355 InitSteps(n)
356
357 #
358 # Create the graph.
359 #
360
361 asdl_subgraph.NinjaGraph(ru)
362 ru.comment('')
363
364 bin_subgraph.NinjaGraph(ru)
365 ru.comment('')
366
367 core_subgraph.NinjaGraph(ru)
368 ru.comment('')
369
370 cpp_subgraph.NinjaGraph(ru)
371 ru.comment('')
372
373 data_lang_subgraph.NinjaGraph(ru)
374 ru.comment('')
375
376 display_subgraph.NinjaGraph(ru)
377 ru.comment('')
378
379 frontend_subgraph.NinjaGraph(ru)
380 ru.comment('')
381
382 mycpp_subgraph.NinjaGraph(ru)
383 ru.comment('')
384
385 ysh_subgraph.NinjaGraph(ru)
386 ru.comment('')
387
388 osh_subgraph.NinjaGraph(ru)
389 ru.comment('')
390
391 pea_subgraph.NinjaGraph(ru)
392 ru.comment('')
393
394 prebuilt_subgraph.NinjaGraph(ru)
395 ru.comment('')
396
397 yaks_subgraph.NinjaGraph(ru)
398 ru.comment('')
399
400 # Materialize all the cc_binary() rules
401 ru.WriteRules()
402
403 # Collect sources for metrics, tarball, shell script
404 cc_sources = ru.SourcesForBinary('_gen/bin/oils_for_unix.mycpp.cc')
405
406 if 0:
407 from pprint import pprint
408 pprint(cc_sources)
409
410 # TODO: could thin these out, not generate for unit tests, etc.
411 Preprocessed(n, cc_sources)
412
413 ru.WritePhony()
414
415 n.default(['_bin/cxx-asan/osh', '_bin/cxx-asan/ysh'])
416
417 if action == 'ninja':
418 log(' (%s) -> %s (%d targets)', argv[0], BUILD_NINJA,
419 n.num_build_targets())
420
421 elif action == 'shell':
422 ShellFunctions(cc_sources, sys.stdout, argv[0])
423
424 elif action == 'tarball-manifest':
425 h = ru.HeadersForBinary('_gen/bin/oils_for_unix.mycpp.cc')
426 tar_cc_sources = cc_sources + [
427 '_gen/bin/oils_for_unix.mycpp-souffle.cc'
428 ]
429 TarballManifest(tar_cc_sources + h)
430
431 else:
432 raise RuntimeError('Invalid action %r' % action)
433
434
435if __name__ == '__main__':
436 try:
437 main(sys.argv)
438 except RuntimeError as e:
439 print('FATAL: %s' % e, file=sys.stderr)
440 sys.exit(1)