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

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