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

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