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