]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/configure.py
d5f8d9d27d95632b8d6fc9fc799323fcb5423b8c
[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-native-static", "build.cargo-native-static", "static native libraries 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 o("missing-tools", "dist.missing-tools", "allow failures when building tools")
73
74 # Optimization and debugging options. These may be overridden by the release
75 # channel, etc.
76 o("optimize", "rust.optimize", "build optimized rust code")
77 o("optimize-llvm", "llvm.optimize", "build optimized LLVM")
78 o("llvm-assertions", "llvm.assertions", "build LLVM with assertions")
79 o("debug-assertions", "rust.debug-assertions", "build with debugging assertions")
80 o("llvm-release-debuginfo", "llvm.release-debuginfo", "build LLVM with debugger metadata")
81 o("debuginfo", "rust.debuginfo", "build with debugger metadata")
82 o("debuginfo-lines", "rust.debuginfo-lines", "build with line number debugger metadata")
83 o("debuginfo-only-std", "rust.debuginfo-only-std", "build only libstd with debugging information")
84 o("debuginfo-tools", "rust.debuginfo-tools", "build extended tools with debugging information")
85 o("debug-jemalloc", "rust.debug-jemalloc", "build jemalloc with --enable-debug --enable-fill")
86 v("save-toolstates", "rust.save-toolstates", "save build and test status of external tools into this file")
87
88 v("prefix", "install.prefix", "set installation prefix")
89 v("localstatedir", "install.localstatedir", "local state directory")
90 v("datadir", "install.datadir", "install data")
91 v("sysconfdir", "install.sysconfdir", "install system configuration files")
92 v("infodir", "install.infodir", "install additional info")
93 v("libdir", "install.libdir", "install libraries")
94 v("mandir", "install.mandir", "install man pages in PATH")
95 v("docdir", "install.docdir", "install documentation in PATH")
96 v("bindir", "install.bindir", "install binaries")
97
98 v("llvm-root", None, "set LLVM root")
99 v("llvm-config", None, "set path to llvm-config")
100 v("llvm-filecheck", None, "set path to LLVM's FileCheck utility")
101 v("python", "build.python", "set path to python")
102 v("jemalloc-root", None, "set directory where libjemalloc_pic.a is located")
103 v("android-cross-path", "target.arm-linux-androideabi.android-ndk",
104   "Android NDK standalone path (deprecated)")
105 v("i686-linux-android-ndk", "target.i686-linux-android.android-ndk",
106   "i686-linux-android NDK standalone path")
107 v("arm-linux-androideabi-ndk", "target.arm-linux-androideabi.android-ndk",
108   "arm-linux-androideabi NDK standalone path")
109 v("armv7-linux-androideabi-ndk", "target.armv7-linux-androideabi.android-ndk",
110   "armv7-linux-androideabi NDK standalone path")
111 v("aarch64-linux-android-ndk", "target.aarch64-linux-android.android-ndk",
112   "aarch64-linux-android NDK standalone path")
113 v("x86_64-linux-android-ndk", "target.x86_64-linux-android.android-ndk",
114   "x86_64-linux-android NDK standalone path")
115 v("musl-root", "target.x86_64-unknown-linux-musl.musl-root",
116   "MUSL root installation directory (deprecated)")
117 v("musl-root-x86_64", "target.x86_64-unknown-linux-musl.musl-root",
118   "x86_64-unknown-linux-musl install directory")
119 v("musl-root-i586", "target.i586-unknown-linux-musl.musl-root",
120   "i586-unknown-linux-musl install directory")
121 v("musl-root-i686", "target.i686-unknown-linux-musl.musl-root",
122   "i686-unknown-linux-musl install directory")
123 v("musl-root-arm", "target.arm-unknown-linux-musleabi.musl-root",
124   "arm-unknown-linux-musleabi install directory")
125 v("musl-root-armhf", "target.arm-unknown-linux-musleabihf.musl-root",
126   "arm-unknown-linux-musleabihf install directory")
127 v("musl-root-armv5te", "target.armv5te-unknown-linux-musleabi.musl-root",
128   "armv5te-unknown-linux-musleabi install directory")
129 v("musl-root-armv7", "target.armv7-unknown-linux-musleabihf.musl-root",
130   "armv7-unknown-linux-musleabihf install directory")
131 v("musl-root-aarch64", "target.aarch64-unknown-linux-musl.musl-root",
132   "aarch64-unknown-linux-musl install directory")
133 v("musl-root-mips", "target.mips-unknown-linux-musl.musl-root",
134   "mips-unknown-linux-musl install directory")
135 v("musl-root-mipsel", "target.mipsel-unknown-linux-musl.musl-root",
136   "mipsel-unknown-linux-musl install directory")
137 v("qemu-armhf-rootfs", "target.arm-unknown-linux-gnueabihf.qemu-rootfs",
138   "rootfs in qemu testing, you probably don't want to use this")
139 v("qemu-aarch64-rootfs", "target.aarch64-unknown-linux-gnu.qemu-rootfs",
140   "rootfs in qemu testing, you probably don't want to use this")
141 v("experimental-targets", "llvm.experimental-targets",
142   "experimental LLVM targets to build")
143 v("release-channel", "rust.channel", "the name of the release channel to build")
144
145 # Used on systems where "cc" is unavailable
146 v("default-linker", "rust.default-linker", "the default linker")
147
148 # Many of these are saved below during the "writing configuration" step
149 # (others are conditionally saved).
150 o("manage-submodules", "build.submodules", "let the build manage the git submodules")
151 o("jemalloc", "rust.use-jemalloc", "build liballoc with jemalloc")
152 o("full-bootstrap", "build.full-bootstrap", "build three compilers instead of two")
153 o("extended", "build.extended", "build an extended rust tool set")
154
155 v("tools", None, "List of extended tools will be installed")
156 v("build", "build.build", "GNUs ./configure syntax LLVM build triple")
157 v("host", None, "GNUs ./configure syntax LLVM host triples")
158 v("target", None, "GNUs ./configure syntax LLVM target triples")
159
160 v("set", None, "set arbitrary key/value pairs in TOML configuration")
161
162
163 def p(msg):
164     print("configure: " + msg)
165
166
167 def err(msg):
168     print("configure: error: " + msg)
169     sys.exit(1)
170
171
172 if '--help' in sys.argv or '-h' in sys.argv:
173     print('Usage: ./configure [options]')
174     print('')
175     print('Options')
176     for option in options:
177         if 'android' in option.name:
178             # no one needs to know about these obscure options
179             continue
180         if option.value:
181             print('\t{:30} {}'.format('--{}=VAL'.format(option.name), option.desc))
182         else:
183             print('\t{:30} {}'.format('--enable-{}'.format(option.name), option.desc))
184     print('')
185     print('This configure script is a thin configuration shim over the true')
186     print('configuration system, `config.toml`. You can explore the comments')
187     print('in `config.toml.example` next to this configure script to see')
188     print('more information about what each option is. Additionally you can')
189     print('pass `--set` as an argument to set arbitrary key/value pairs')
190     print('in the TOML configuration if desired')
191     print('')
192     print('Also note that all options which take `--enable` can similarly')
193     print('be passed with `--disable-foo` to forcibly disable the option')
194     sys.exit(0)
195
196 # Parse all command line arguments into one of these three lists, handling
197 # boolean and value-based options separately
198 unknown_args = []
199 need_value_args = []
200 known_args = {}
201
202 p("processing command line")
203 i = 1
204 while i < len(sys.argv):
205     arg = sys.argv[i]
206     i += 1
207     if not arg.startswith('--'):
208         unknown_args.append(arg)
209         continue
210
211     found = False
212     for option in options:
213         value = None
214         if option.value:
215             keyval = arg[2:].split('=', 1)
216             key = keyval[0]
217             if option.name != key:
218                 continue
219
220             if len(keyval) > 1:
221                 value = keyval[1]
222             elif i < len(sys.argv):
223                 value = sys.argv[i]
224                 i += 1
225             else:
226                 need_value_args.append(arg)
227                 continue
228         else:
229             if arg[2:] == 'enable-' + option.name:
230                 value = True
231             elif arg[2:] == 'disable-' + option.name:
232                 value = False
233             else:
234                 continue
235
236         found = True
237         if option.name not in known_args:
238             known_args[option.name] = []
239         known_args[option.name].append((option, value))
240         break
241
242     if not found:
243         unknown_args.append(arg)
244 p("")
245
246 # Note: here and a few other places, we use [-1] to apply the *last* value
247 # passed.  But if option-checking is enabled, then the known_args loop will
248 # also assert that options are only passed once.
249 option_checking = ('option-checking' not in known_args
250                    or known_args['option-checking'][-1][1])
251 if option_checking:
252     if len(unknown_args) > 0:
253         err("Option '" + unknown_args[0] + "' is not recognized")
254     if len(need_value_args) > 0:
255         err("Option '{0}' needs a value ({0}=val)".format(need_value_args[0]))
256
257 # Parse all known arguments into a configuration structure that reflects the
258 # TOML we're going to write out
259 config = {}
260
261
262 def build():
263     if 'build' in known_args:
264         return known_args['build'][-1][1]
265     return bootstrap.default_build_triple()
266
267
268 def set(key, value):
269     s = "{:20} := {}".format(key, value)
270     if len(s) < 70:
271         p(s)
272     else:
273         p(s[:70] + " ...")
274
275     arr = config
276     parts = key.split('.')
277     for i, part in enumerate(parts):
278         if i == len(parts) - 1:
279             arr[part] = value
280         else:
281             if part not in arr:
282                 arr[part] = {}
283             arr = arr[part]
284
285
286 for key in known_args:
287     # The `set` option is special and can be passed a bunch of times
288     if key == 'set':
289         for option, value in known_args[key]:
290             keyval = value.split('=', 1)
291             if len(keyval) == 1 or keyval[1] == "true":
292                 value = True
293             elif keyval[1] == "false":
294                 value = False
295             else:
296                 value = keyval[1]
297             set(keyval[0], value)
298         continue
299
300     # Ensure each option is only passed once
301     arr = known_args[key]
302     if option_checking and len(arr) > 1:
303         err("Option '{}' provided more than once".format(key))
304     option, value = arr[-1]
305
306     # If we have a clear avenue to set our value in rustbuild, do so
307     if option.rustbuild is not None:
308         set(option.rustbuild, value)
309         continue
310
311     # Otherwise we're a "special" option and need some extra handling, so do
312     # that here.
313     if option.name == 'sccache':
314         set('llvm.ccache', 'sccache')
315     elif option.name == 'local-rust':
316         for path in os.environ['PATH'].split(os.pathsep):
317             if os.path.exists(path + '/rustc'):
318                 set('build.rustc', path + '/rustc')
319                 break
320         for path in os.environ['PATH'].split(os.pathsep):
321             if os.path.exists(path + '/cargo'):
322                 set('build.cargo', path + '/cargo')
323                 break
324     elif option.name == 'local-rust-root':
325         set('build.rustc', value + '/bin/rustc')
326         set('build.cargo', value + '/bin/cargo')
327     elif option.name == 'llvm-root':
328         set('target.{}.llvm-config'.format(build()), value + '/bin/llvm-config')
329     elif option.name == 'llvm-config':
330         set('target.{}.llvm-config'.format(build()), value)
331     elif option.name == 'llvm-filecheck':
332         set('target.{}.llvm-filecheck'.format(build()), value)
333     elif option.name == 'jemalloc-root':
334         set('target.{}.jemalloc'.format(build()), value + '/libjemalloc_pic.a')
335     elif option.name == 'tools':
336         set('build.tools', value.split(','))
337     elif option.name == 'host':
338         set('build.host', value.split(','))
339     elif option.name == 'target':
340         set('build.target', value.split(','))
341     elif option.name == 'emscripten':
342         set('rust.codegen-backends', ['llvm', 'emscripten'])
343     elif option.name == 'full-tools':
344         set('rust.codegen-backends', ['llvm', 'emscripten'])
345         set('rust.lld', True)
346         set('rust.llvm-tools', True)
347         set('build.extended', True)
348     elif option.name == 'option-checking':
349         # this was handled above
350         pass
351     else:
352         raise RuntimeError("unhandled option {}".format(option.name))
353
354 set('build.configure-args', sys.argv[1:])
355
356 # "Parse" the `config.toml.example` file into the various sections, and we'll
357 # use this as a template of a `config.toml` to write out which preserves
358 # all the various comments and whatnot.
359 #
360 # Note that the `target` section is handled separately as we'll duplicate it
361 # per configured target, so there's a bit of special handling for that here.
362 sections = {}
363 cur_section = None
364 sections[None] = []
365 section_order = [None]
366 targets = {}
367
368 for line in open(rust_dir + '/config.toml.example').read().split("\n"):
369     if line.startswith('['):
370         cur_section = line[1:-1]
371         if cur_section.startswith('target'):
372             cur_section = 'target'
373         elif '.' in cur_section:
374             raise RuntimeError("don't know how to deal with section: {}".format(cur_section))
375         sections[cur_section] = [line]
376         section_order.append(cur_section)
377     else:
378         sections[cur_section].append(line)
379
380 # Fill out the `targets` array by giving all configured targets a copy of the
381 # `target` section we just loaded from the example config
382 configured_targets = [build()]
383 if 'build' in config:
384     if 'host' in config['build']:
385         configured_targets += config['build']['host']
386     if 'target' in config['build']:
387         configured_targets += config['build']['target']
388 if 'target' in config:
389     for target in config['target']:
390         configured_targets.append(target)
391 for target in configured_targets:
392     targets[target] = sections['target'][:]
393     targets[target][0] = targets[target][0].replace("x86_64-unknown-linux-gnu", target)
394
395
396 def is_number(value):
397   try:
398     float(value)
399     return True
400   except ValueError:
401     return False
402
403 # Here we walk through the constructed configuration we have from the parsed
404 # command line arguments. We then apply each piece of configuration by
405 # basically just doing a `sed` to change the various configuration line to what
406 # we've got configure.
407 def to_toml(value):
408     if isinstance(value, bool):
409         if value:
410             return "true"
411         else:
412             return "false"
413     elif isinstance(value, list):
414         return '[' + ', '.join(map(to_toml, value)) + ']'
415     elif isinstance(value, str):
416         # Don't put quotes around numeric values
417         if is_number(value):
418             return value
419         else:
420             return "'" + value + "'"
421     else:
422         raise RuntimeError('no toml')
423
424
425 def configure_section(lines, config):
426     for key in config:
427         value = config[key]
428         found = False
429         for i, line in enumerate(lines):
430             if not line.startswith('#' + key + ' = '):
431                 continue
432             found = True
433             lines[i] = "{} = {}".format(key, to_toml(value))
434             break
435         if not found:
436             raise RuntimeError("failed to find config line for {}".format(key))
437
438
439 for section_key in config:
440     section_config = config[section_key]
441     if section_key not in sections:
442         raise RuntimeError("config key {} not in sections".format(section_key))
443
444     if section_key == 'target':
445         for target in section_config:
446             configure_section(targets[target], section_config[target])
447     else:
448         configure_section(sections[section_key], section_config)
449
450 # Now that we've built up our `config.toml`, write it all out in the same
451 # order that we read it in.
452 p("")
453 p("writing `config.toml` in current directory")
454 with bootstrap.output('config.toml') as f:
455     for section in section_order:
456         if section == 'target':
457             for target in targets:
458                 for line in targets[target]:
459                     f.write(line + "\n")
460         else:
461             for line in sections[section]:
462                 f.write(line + "\n")
463
464 with bootstrap.output('Makefile') as f:
465     contents = os.path.join(rust_dir, 'src', 'bootstrap', 'mk', 'Makefile.in')
466     contents = open(contents).read()
467     contents = contents.replace("$(CFG_SRC_DIR)", rust_dir + '/')
468     contents = contents.replace("$(CFG_PYTHON)", sys.executable)
469     f.write(contents)
470
471 p("")
472 p("run `python {}/x.py --help`".format(rust_dir))
473 p("")