]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/configure.py
Refactor mod/check (part vii)
[rust.git] / src / bootstrap / configure.py
1 #!/usr/bin/env python
2 # Copyright 2017 The Rust Project Developers. See the COPYRIGHT
3 # file at the top-level directory of this distribution and at
4 # http://rust-lang.org/COPYRIGHT.
5 #
6 # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7 # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8 # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9 # option. This file may not be copied, modified, or distributed
10 # except according to those terms.
11
12 # ignore-tidy-linelength
13
14 from __future__ import absolute_import, division, print_function
15 import sys
16 import os
17 rust_dir = os.path.dirname(os.path.abspath(__file__))
18 rust_dir = os.path.dirname(rust_dir)
19 rust_dir = os.path.dirname(rust_dir)
20 sys.path.append(os.path.join(rust_dir, "src", "bootstrap"))
21 import bootstrap
22
23
24 class Option(object):
25     def __init__(self, name, rustbuild, desc, value):
26         self.name = name
27         self.rustbuild = rustbuild
28         self.desc = desc
29         self.value = value
30
31
32 options = []
33
34
35 def o(*args):
36     options.append(Option(*args, value=False))
37
38
39 def v(*args):
40     options.append(Option(*args, value=True))
41
42
43 o("debug", "rust.debug", "debug mode; disables optimization unless `--enable-optimize` given")
44 o("docs", "build.docs", "build standard library documentation")
45 o("compiler-docs", "build.compiler-docs", "build compiler documentation")
46 o("optimize-tests", "rust.optimize-tests", "build tests with optimizations")
47 o("experimental-parallel-queries", "rust.experimental-parallel-queries", "build rustc with experimental parallelization")
48 o("test-miri", "rust.test-miri", "run miri's test suite")
49 o("debuginfo-tests", "rust.debuginfo-tests", "build tests with debugger metadata")
50 o("verbose-tests", "rust.verbose-tests", "enable verbose output when running tests")
51 o("ccache", "llvm.ccache", "invoke gcc/clang via ccache to reuse object files between builds")
52 o("sccache", None, "invoke gcc/clang via sccache to reuse object files between builds")
53 o("local-rust", None, "use an installed rustc rather than downloading a snapshot")
54 v("local-rust-root", None, "set prefix for local rust binary")
55 o("local-rebuild", "build.local-rebuild", "assume local-rust matches the current version, for rebuilds; implies local-rust, and is implied if local-rust already matches the current version")
56 o("llvm-static-stdcpp", "llvm.static-libstdcpp", "statically link to libstdc++ for LLVM")
57 o("llvm-link-shared", "llvm.link-shared", "prefer shared linking to LLVM (llvm-config --link-shared)")
58 o("rpath", "rust.rpath", "build rpaths into rustc itself")
59 o("llvm-version-check", "llvm.version-check", "check if the LLVM version is supported, build anyway")
60 o("codegen-tests", "rust.codegen-tests", "run the src/test/codegen tests")
61 o("option-checking", None, "complain about unrecognized options in this configure script")
62 o("ninja", "llvm.ninja", "build LLVM using the Ninja generator (for MSVC, requires building in the correct environment)")
63 o("locked-deps", "build.locked-deps", "force Cargo.lock to be up to date")
64 o("vendor", "build.vendor", "enable usage of vendored Rust crates")
65 o("sanitizers", "build.sanitizers", "build the sanitizer runtimes (asan, lsan, msan, tsan)")
66 o("dist-src", "rust.dist-src", "when building tarballs enables building a source tarball")
67 o("cargo-openssl-static", "build.openssl-static", "static openssl in cargo")
68 o("profiler", "build.profiler", "build the profiler runtime")
69 o("emscripten", None, "compile the emscripten backend as well as LLVM")
70 o("full-tools", None, "enable all tools")
71 o("lldb", "rust.lldb", "build lldb")
72
73 # Optimization and debugging options. These may be overridden by the release
74 # channel, etc.
75 o("optimize", "rust.optimize", "build optimized rust code")
76 o("optimize-llvm", "llvm.optimize", "build optimized LLVM")
77 o("llvm-assertions", "llvm.assertions", "build LLVM with assertions")
78 o("debug-assertions", "rust.debug-assertions", "build with debugging assertions")
79 o("llvm-release-debuginfo", "llvm.release-debuginfo", "build LLVM with debugger metadata")
80 o("debuginfo", "rust.debuginfo", "build with debugger metadata")
81 o("debuginfo-lines", "rust.debuginfo-lines", "build with line number debugger metadata")
82 o("debuginfo-only-std", "rust.debuginfo-only-std", "build only libstd with debugging information")
83 o("debuginfo-tools", "rust.debuginfo-tools", "build extended tools with debugging information")
84 o("debug-jemalloc", "rust.debug-jemalloc", "build jemalloc with --enable-debug --enable-fill")
85 v("save-toolstates", "rust.save-toolstates", "save build and test status of external tools into this file")
86
87 v("prefix", "install.prefix", "set installation prefix")
88 v("localstatedir", "install.localstatedir", "local state directory")
89 v("datadir", "install.datadir", "install data")
90 v("sysconfdir", "install.sysconfdir", "install system configuration files")
91 v("infodir", "install.infodir", "install additional info")
92 v("libdir", "install.libdir", "install libraries")
93 v("mandir", "install.mandir", "install man pages in PATH")
94 v("docdir", "install.docdir", "install documentation in PATH")
95 v("bindir", "install.bindir", "install binaries")
96
97 v("llvm-root", None, "set LLVM root")
98 v("python", "build.python", "set path to python")
99 v("jemalloc-root", None, "set directory where libjemalloc_pic.a is located")
100 v("android-cross-path", "target.arm-linux-androideabi.android-ndk",
101   "Android NDK standalone path (deprecated)")
102 v("i686-linux-android-ndk", "target.i686-linux-android.android-ndk",
103   "i686-linux-android NDK standalone path")
104 v("arm-linux-androideabi-ndk", "target.arm-linux-androideabi.android-ndk",
105   "arm-linux-androideabi NDK standalone path")
106 v("armv7-linux-androideabi-ndk", "target.armv7-linux-androideabi.android-ndk",
107   "armv7-linux-androideabi NDK standalone path")
108 v("aarch64-linux-android-ndk", "target.aarch64-linux-android.android-ndk",
109   "aarch64-linux-android NDK standalone path")
110 v("x86_64-linux-android-ndk", "target.x86_64-linux-android.android-ndk",
111   "x86_64-linux-android NDK standalone path")
112 v("musl-root", "target.x86_64-unknown-linux-musl.musl-root",
113   "MUSL root installation directory (deprecated)")
114 v("musl-root-x86_64", "target.x86_64-unknown-linux-musl.musl-root",
115   "x86_64-unknown-linux-musl install directory")
116 v("musl-root-i586", "target.i586-unknown-linux-musl.musl-root",
117   "i586-unknown-linux-musl install directory")
118 v("musl-root-i686", "target.i686-unknown-linux-musl.musl-root",
119   "i686-unknown-linux-musl install directory")
120 v("musl-root-arm", "target.arm-unknown-linux-musleabi.musl-root",
121   "arm-unknown-linux-musleabi install directory")
122 v("musl-root-armhf", "target.arm-unknown-linux-musleabihf.musl-root",
123   "arm-unknown-linux-musleabihf install directory")
124 v("musl-root-armv5te", "target.armv5te-unknown-linux-musleabi.musl-root",
125   "armv5te-unknown-linux-musleabi install directory")
126 v("musl-root-armv7", "target.armv7-unknown-linux-musleabihf.musl-root",
127   "armv7-unknown-linux-musleabihf install directory")
128 v("musl-root-aarch64", "target.aarch64-unknown-linux-musl.musl-root",
129   "aarch64-unknown-linux-musl install directory")
130 v("musl-root-mips", "target.mips-unknown-linux-musl.musl-root",
131   "mips-unknown-linux-musl install directory")
132 v("musl-root-mipsel", "target.mipsel-unknown-linux-musl.musl-root",
133   "mipsel-unknown-linux-musl install directory")
134 v("qemu-armhf-rootfs", "target.arm-unknown-linux-gnueabihf.qemu-rootfs",
135   "rootfs in qemu testing, you probably don't want to use this")
136 v("qemu-aarch64-rootfs", "target.aarch64-unknown-linux-gnu.qemu-rootfs",
137   "rootfs in qemu testing, you probably don't want to use this")
138 v("experimental-targets", "llvm.experimental-targets",
139   "experimental LLVM targets to build")
140 v("release-channel", "rust.channel", "the name of the release channel to build")
141
142 # Used on systems where "cc" is unavailable
143 v("default-linker", "rust.default-linker", "the default linker")
144
145 # Many of these are saved below during the "writing configuration" step
146 # (others are conditionally saved).
147 o("manage-submodules", "build.submodules", "let the build manage the git submodules")
148 o("jemalloc", "rust.use-jemalloc", "build liballoc with jemalloc")
149 o("full-bootstrap", "build.full-bootstrap", "build three compilers instead of two")
150 o("extended", "build.extended", "build an extended rust tool set")
151
152 v("tools", None, "List of extended tools will be installed")
153 v("build", "build.build", "GNUs ./configure syntax LLVM build triple")
154 v("host", None, "GNUs ./configure syntax LLVM host triples")
155 v("target", None, "GNUs ./configure syntax LLVM target triples")
156
157 v("set", None, "set arbitrary key/value pairs in TOML configuration")
158
159
160 def p(msg):
161     print("configure: " + msg)
162
163
164 def err(msg):
165     print("configure: error: " + msg)
166     sys.exit(1)
167
168
169 if '--help' in sys.argv or '-h' in sys.argv:
170     print('Usage: ./configure [options]')
171     print('')
172     print('Options')
173     for option in options:
174         if 'android' in option.name:
175             # no one needs to know about these obscure options
176             continue
177         if option.value:
178             print('\t{:30} {}'.format('--{}=VAL'.format(option.name), option.desc))
179         else:
180             print('\t{:30} {}'.format('--enable-{}'.format(option.name), option.desc))
181     print('')
182     print('This configure script is a thin configuration shim over the true')
183     print('configuration system, `config.toml`. You can explore the comments')
184     print('in `config.toml.example` next to this configure script to see')
185     print('more information about what each option is. Additionally you can')
186     print('pass `--set` as an argument to set arbitrary key/value pairs')
187     print('in the TOML configuration if desired')
188     print('')
189     print('Also note that all options which take `--enable` can similarly')
190     print('be passed with `--disable-foo` to forcibly disable the option')
191     sys.exit(0)
192
193 # Parse all command line arguments into one of these three lists, handling
194 # boolean and value-based options separately
195 unknown_args = []
196 need_value_args = []
197 known_args = {}
198
199 p("processing command line")
200 i = 1
201 while i < len(sys.argv):
202     arg = sys.argv[i]
203     i += 1
204     if not arg.startswith('--'):
205         unknown_args.append(arg)
206         continue
207
208     found = False
209     for option in options:
210         value = None
211         if option.value:
212             keyval = arg[2:].split('=', 1)
213             key = keyval[0]
214             if option.name != key:
215                 continue
216
217             if len(keyval) > 1:
218                 value = keyval[1]
219             elif i < len(sys.argv):
220                 value = sys.argv[i]
221                 i += 1
222             else:
223                 need_value_args.append(arg)
224                 continue
225         else:
226             if arg[2:] == 'enable-' + option.name:
227                 value = True
228             elif arg[2:] == 'disable-' + option.name:
229                 value = False
230             else:
231                 continue
232
233         found = True
234         if option.name not in known_args:
235             known_args[option.name] = []
236         known_args[option.name].append((option, value))
237         break
238
239     if not found:
240         unknown_args.append(arg)
241 p("")
242
243 # Note: here and a few other places, we use [-1] to apply the *last* value
244 # passed.  But if option-checking is enabled, then the known_args loop will
245 # also assert that options are only passed once.
246 option_checking = ('option-checking' not in known_args
247                    or known_args['option-checking'][-1][1])
248 if option_checking:
249     if len(unknown_args) > 0:
250         err("Option '" + unknown_args[0] + "' is not recognized")
251     if len(need_value_args) > 0:
252         err("Option '{0}' needs a value ({0}=val)".format(need_value_args[0]))
253
254 # Parse all known arguments into a configuration structure that reflects the
255 # TOML we're going to write out
256 config = {}
257
258
259 def build():
260     if 'build' in known_args:
261         return known_args['build'][-1][1]
262     return bootstrap.default_build_triple()
263
264
265 def set(key, value):
266     s = "{:20} := {}".format(key, value)
267     if len(s) < 70:
268         p(s)
269     else:
270         p(s[:70] + " ...")
271
272     arr = config
273     parts = key.split('.')
274     for i, part in enumerate(parts):
275         if i == len(parts) - 1:
276             arr[part] = value
277         else:
278             if part not in arr:
279                 arr[part] = {}
280             arr = arr[part]
281
282
283 for key in known_args:
284     # The `set` option is special and can be passed a bunch of times
285     if key == 'set':
286         for option, value in known_args[key]:
287             keyval = value.split('=', 1)
288             if len(keyval) == 1 or keyval[1] == "true":
289                 value = True
290             elif keyval[1] == "false":
291                 value = False
292             else:
293                 value = keyval[1]
294             set(keyval[0], value)
295         continue
296
297     # Ensure each option is only passed once
298     arr = known_args[key]
299     if option_checking and len(arr) > 1:
300         err("Option '{}' provided more than once".format(key))
301     option, value = arr[-1]
302
303     # If we have a clear avenue to set our value in rustbuild, do so
304     if option.rustbuild is not None:
305         set(option.rustbuild, value)
306         continue
307
308     # Otherwise we're a "special" option and need some extra handling, so do
309     # that here.
310     if option.name == 'sccache':
311         set('llvm.ccache', 'sccache')
312     elif option.name == 'local-rust':
313         for path in os.environ['PATH'].split(os.pathsep):
314             if os.path.exists(path + '/rustc'):
315                 set('build.rustc', path + '/rustc')
316                 break
317         for path in os.environ['PATH'].split(os.pathsep):
318             if os.path.exists(path + '/cargo'):
319                 set('build.cargo', path + '/cargo')
320                 break
321     elif option.name == 'local-rust-root':
322         set('build.rustc', value + '/bin/rustc')
323         set('build.cargo', value + '/bin/cargo')
324     elif option.name == 'llvm-root':
325         set('target.{}.llvm-config'.format(build()), value + '/bin/llvm-config')
326     elif option.name == 'jemalloc-root':
327         set('target.{}.jemalloc'.format(build()), value + '/libjemalloc_pic.a')
328     elif option.name == 'tools':
329         set('build.tools', value.split(','))
330     elif option.name == 'host':
331         set('build.host', value.split(','))
332     elif option.name == 'target':
333         set('build.target', value.split(','))
334     elif option.name == 'emscripten':
335         set('rust.codegen-backends', ['llvm', 'emscripten'])
336     elif option.name == 'full-tools':
337         set('rust.codegen-backends', ['llvm', 'emscripten'])
338         set('rust.lld', True)
339         set('rust.llvm-tools', True)
340         set('build.extended', True)
341     elif option.name == 'option-checking':
342         # this was handled above
343         pass
344     else:
345         raise RuntimeError("unhandled option {}".format(option.name))
346
347 set('build.configure-args', sys.argv[1:])
348
349 # "Parse" the `config.toml.example` file into the various sections, and we'll
350 # use this as a template of a `config.toml` to write out which preserves
351 # all the various comments and whatnot.
352 #
353 # Note that the `target` section is handled separately as we'll duplicate it
354 # per configured target, so there's a bit of special handling for that here.
355 sections = {}
356 cur_section = None
357 sections[None] = []
358 section_order = [None]
359 targets = {}
360
361 for line in open(rust_dir + '/config.toml.example').read().split("\n"):
362     if line.startswith('['):
363         cur_section = line[1:-1]
364         if cur_section.startswith('target'):
365             cur_section = 'target'
366         elif '.' in cur_section:
367             raise RuntimeError("don't know how to deal with section: {}".format(cur_section))
368         sections[cur_section] = [line]
369         section_order.append(cur_section)
370     else:
371         sections[cur_section].append(line)
372
373 # Fill out the `targets` array by giving all configured targets a copy of the
374 # `target` section we just loaded from the example config
375 configured_targets = [build()]
376 if 'build' in config:
377     if 'host' in config['build']:
378         configured_targets += config['build']['host']
379     if 'target' in config['build']:
380         configured_targets += config['build']['target']
381 if 'target' in config:
382     for target in config['target']:
383         configured_targets.append(target)
384 for target in configured_targets:
385     targets[target] = sections['target'][:]
386     targets[target][0] = targets[target][0].replace("x86_64-unknown-linux-gnu", target)
387
388
389 # Here we walk through the constructed configuration we have from the parsed
390 # command line arguments. We then apply each piece of configuration by
391 # basically just doing a `sed` to change the various configuration line to what
392 # we've got configure.
393 def to_toml(value):
394     if isinstance(value, bool):
395         if value:
396             return "true"
397         else:
398             return "false"
399     elif isinstance(value, list):
400         return '[' + ', '.join(map(to_toml, value)) + ']'
401     elif isinstance(value, str):
402         return "'" + value + "'"
403     else:
404         raise RuntimeError('no toml')
405
406
407 def configure_section(lines, config):
408     for key in config:
409         value = config[key]
410         found = False
411         for i, line in enumerate(lines):
412             if not line.startswith('#' + key + ' = '):
413                 continue
414             found = True
415             lines[i] = "{} = {}".format(key, to_toml(value))
416             break
417         if not found:
418             raise RuntimeError("failed to find config line for {}".format(key))
419
420
421 for section_key in config:
422     section_config = config[section_key]
423     if section_key not in sections:
424         raise RuntimeError("config key {} not in sections".format(section_key))
425
426     if section_key == 'target':
427         for target in section_config:
428             configure_section(targets[target], section_config[target])
429     else:
430         configure_section(sections[section_key], section_config)
431
432 # Now that we've built up our `config.toml`, write it all out in the same
433 # order that we read it in.
434 p("")
435 p("writing `config.toml` in current directory")
436 with bootstrap.output('config.toml') as f:
437     for section in section_order:
438         if section == 'target':
439             for target in targets:
440                 for line in targets[target]:
441                     f.write(line + "\n")
442         else:
443             for line in sections[section]:
444                 f.write(line + "\n")
445
446 with bootstrap.output('Makefile') as f:
447     contents = os.path.join(rust_dir, 'src', 'bootstrap', 'mk', 'Makefile.in')
448     contents = open(contents).read()
449     contents = contents.replace("$(CFG_SRC_DIR)", rust_dir + '/')
450     contents = contents.replace("$(CFG_PYTHON)", sys.executable)
451     f.write(contents)
452
453 p("")
454 p("run `python {}/x.py --help`".format(rust_dir))
455 p("")