]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/config.rs
Rollup merge of #76867 - poliorcetics:intra-doc-core-iter, r=jyn514
[rust.git] / src / bootstrap / config.rs
1 //! Serialized configuration of a build.
2 //!
3 //! This module implements parsing `config.toml` configuration files to tweak
4 //! how the build runs.
5
6 use std::cmp;
7 use std::collections::{HashMap, HashSet};
8 use std::env;
9 use std::ffi::OsString;
10 use std::fmt;
11 use std::fs;
12 use std::path::{Path, PathBuf};
13
14 use crate::cache::{Interned, INTERNER};
15 use crate::flags::Flags;
16 pub use crate::flags::Subcommand;
17 use crate::util::exe;
18 use build_helper::t;
19 use merge::Merge;
20 use serde::Deserialize;
21
22 macro_rules! check_ci_llvm {
23     ($name:expr) => {
24         assert!(
25             $name.is_none(),
26             "setting {} is incompatible with download-ci-llvm.",
27             stringify!($name)
28         );
29     };
30 }
31
32 /// Global configuration for the entire build and/or bootstrap.
33 ///
34 /// This structure is derived from a combination of both `config.toml` and
35 /// `config.mk`. As of the time of this writing it's unlikely that `config.toml`
36 /// is used all that much, so this is primarily filled out by `config.mk` which
37 /// is generated from `./configure`.
38 ///
39 /// Note that this structure is not decoded directly into, but rather it is
40 /// filled out from the decoded forms of the structs below. For documentation
41 /// each field, see the corresponding fields in
42 /// `config.toml.example`.
43 #[derive(Default)]
44 pub struct Config {
45     pub ccache: Option<String>,
46     /// Call Build::ninja() instead of this.
47     pub ninja_in_file: bool,
48     pub verbose: usize,
49     pub submodules: bool,
50     pub fast_submodules: bool,
51     pub compiler_docs: bool,
52     pub docs: bool,
53     pub locked_deps: bool,
54     pub vendor: bool,
55     pub target_config: HashMap<TargetSelection, Target>,
56     pub full_bootstrap: bool,
57     pub extended: bool,
58     pub tools: Option<HashSet<String>>,
59     pub sanitizers: bool,
60     pub profiler: bool,
61     pub ignore_git: bool,
62     pub exclude: Vec<PathBuf>,
63     pub rustc_error_format: Option<String>,
64     pub json_output: bool,
65     pub test_compare_mode: bool,
66     pub llvm_libunwind: bool,
67
68     pub skip_only_host_steps: bool,
69
70     pub on_fail: Option<String>,
71     pub stage: u32,
72     pub keep_stage: Vec<u32>,
73     pub src: PathBuf,
74     pub jobs: Option<u32>,
75     pub cmd: Subcommand,
76     pub incremental: bool,
77     pub dry_run: bool,
78
79     pub deny_warnings: bool,
80     pub backtrace_on_ice: bool,
81
82     // llvm codegen options
83     pub llvm_skip_rebuild: bool,
84     pub llvm_assertions: bool,
85     pub llvm_optimize: bool,
86     pub llvm_thin_lto: bool,
87     pub llvm_release_debuginfo: bool,
88     pub llvm_version_check: bool,
89     pub llvm_static_stdcpp: bool,
90     pub llvm_link_shared: bool,
91     pub llvm_clang_cl: Option<String>,
92     pub llvm_targets: Option<String>,
93     pub llvm_experimental_targets: Option<String>,
94     pub llvm_link_jobs: Option<u32>,
95     pub llvm_version_suffix: Option<String>,
96     pub llvm_use_linker: Option<String>,
97     pub llvm_allow_old_toolchain: Option<bool>,
98     pub llvm_from_ci: bool,
99
100     pub use_lld: bool,
101     pub lld_enabled: bool,
102     pub llvm_tools_enabled: bool,
103
104     pub llvm_cflags: Option<String>,
105     pub llvm_cxxflags: Option<String>,
106     pub llvm_ldflags: Option<String>,
107     pub llvm_use_libcxx: bool,
108
109     // rust codegen options
110     pub rust_optimize: bool,
111     pub rust_codegen_units: Option<u32>,
112     pub rust_codegen_units_std: Option<u32>,
113     pub rust_debug_assertions: bool,
114     pub rust_debug_assertions_std: bool,
115     pub rust_debug_logging: bool,
116     pub rust_debuginfo_level_rustc: u32,
117     pub rust_debuginfo_level_std: u32,
118     pub rust_debuginfo_level_tools: u32,
119     pub rust_debuginfo_level_tests: u32,
120     pub rust_rpath: bool,
121     pub rustc_parallel: bool,
122     pub rustc_default_linker: Option<String>,
123     pub rust_optimize_tests: bool,
124     pub rust_dist_src: bool,
125     pub rust_codegen_backends: Vec<Interned<String>>,
126     pub rust_verify_llvm_ir: bool,
127     pub rust_thin_lto_import_instr_limit: Option<u32>,
128     pub rust_remap_debuginfo: bool,
129     pub rust_new_symbol_mangling: bool,
130
131     pub build: TargetSelection,
132     pub hosts: Vec<TargetSelection>,
133     pub targets: Vec<TargetSelection>,
134     pub local_rebuild: bool,
135     pub jemalloc: bool,
136     pub control_flow_guard: bool,
137
138     // dist misc
139     pub dist_sign_folder: Option<PathBuf>,
140     pub dist_upload_addr: Option<String>,
141     pub dist_gpg_password_file: Option<PathBuf>,
142
143     // libstd features
144     pub backtrace: bool, // support for RUST_BACKTRACE
145
146     // misc
147     pub low_priority: bool,
148     pub channel: String,
149     pub verbose_tests: bool,
150     pub save_toolstates: Option<PathBuf>,
151     pub print_step_timings: bool,
152     pub missing_tools: bool,
153
154     // Fallback musl-root for all targets
155     pub musl_root: Option<PathBuf>,
156     pub prefix: Option<PathBuf>,
157     pub sysconfdir: Option<PathBuf>,
158     pub datadir: Option<PathBuf>,
159     pub docdir: Option<PathBuf>,
160     pub bindir: PathBuf,
161     pub libdir: Option<PathBuf>,
162     pub mandir: Option<PathBuf>,
163     pub codegen_tests: bool,
164     pub nodejs: Option<PathBuf>,
165     pub gdb: Option<PathBuf>,
166     pub python: Option<PathBuf>,
167     pub cargo_native_static: bool,
168     pub configure_args: Vec<String>,
169
170     // These are either the stage0 downloaded binaries or the locally installed ones.
171     pub initial_cargo: PathBuf,
172     pub initial_rustc: PathBuf,
173     pub initial_rustfmt: Option<PathBuf>,
174     pub out: PathBuf,
175 }
176
177 #[derive(Debug, Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
178 pub struct TargetSelection {
179     pub triple: Interned<String>,
180     file: Option<Interned<String>>,
181 }
182
183 impl TargetSelection {
184     pub fn from_user(selection: &str) -> Self {
185         let path = Path::new(selection);
186
187         let (triple, file) = if path.exists() {
188             let triple = path
189                 .file_stem()
190                 .expect("Target specification file has no file stem")
191                 .to_str()
192                 .expect("Target specification file stem is not UTF-8");
193
194             (triple, Some(selection))
195         } else {
196             (selection, None)
197         };
198
199         let triple = INTERNER.intern_str(triple);
200         let file = file.map(|f| INTERNER.intern_str(f));
201
202         Self { triple, file }
203     }
204
205     pub fn rustc_target_arg(&self) -> &str {
206         self.file.as_ref().unwrap_or(&self.triple)
207     }
208
209     pub fn contains(&self, needle: &str) -> bool {
210         self.triple.contains(needle)
211     }
212
213     pub fn starts_with(&self, needle: &str) -> bool {
214         self.triple.starts_with(needle)
215     }
216
217     pub fn ends_with(&self, needle: &str) -> bool {
218         self.triple.ends_with(needle)
219     }
220 }
221
222 impl fmt::Display for TargetSelection {
223     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224         write!(f, "{}", self.triple)?;
225         if let Some(file) = self.file {
226             write!(f, "({})", file)?;
227         }
228         Ok(())
229     }
230 }
231
232 impl PartialEq<&str> for TargetSelection {
233     fn eq(&self, other: &&str) -> bool {
234         self.triple == *other
235     }
236 }
237
238 /// Per-target configuration stored in the global configuration structure.
239 #[derive(Default)]
240 pub struct Target {
241     /// Some(path to llvm-config) if using an external LLVM.
242     pub llvm_config: Option<PathBuf>,
243     /// Some(path to FileCheck) if one was specified.
244     pub llvm_filecheck: Option<PathBuf>,
245     pub cc: Option<PathBuf>,
246     pub cxx: Option<PathBuf>,
247     pub ar: Option<PathBuf>,
248     pub ranlib: Option<PathBuf>,
249     pub linker: Option<PathBuf>,
250     pub ndk: Option<PathBuf>,
251     pub crt_static: Option<bool>,
252     pub musl_root: Option<PathBuf>,
253     pub musl_libdir: Option<PathBuf>,
254     pub wasi_root: Option<PathBuf>,
255     pub qemu_rootfs: Option<PathBuf>,
256     pub no_std: bool,
257 }
258
259 impl Target {
260     pub fn from_triple(triple: &str) -> Self {
261         let mut target: Self = Default::default();
262         if triple.contains("-none") || triple.contains("nvptx") {
263             target.no_std = true;
264         }
265         target
266     }
267 }
268 /// Structure of the `config.toml` file that configuration is read from.
269 ///
270 /// This structure uses `Decodable` to automatically decode a TOML configuration
271 /// file into this format, and then this is traversed and written into the above
272 /// `Config` structure.
273 #[derive(Deserialize, Default)]
274 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
275 struct TomlConfig {
276     build: Option<Build>,
277     install: Option<Install>,
278     llvm: Option<Llvm>,
279     rust: Option<Rust>,
280     target: Option<HashMap<String, TomlTarget>>,
281     dist: Option<Dist>,
282     profile: Option<String>,
283 }
284
285 impl Merge for TomlConfig {
286     fn merge(&mut self, TomlConfig { build, install, llvm, rust, dist, target, profile: _ }: Self) {
287         fn do_merge<T: Merge>(x: &mut Option<T>, y: Option<T>) {
288             if let Some(new) = y {
289                 if let Some(original) = x {
290                     original.merge(new);
291                 } else {
292                     *x = Some(new);
293                 }
294             }
295         };
296         do_merge(&mut self.build, build);
297         do_merge(&mut self.install, install);
298         do_merge(&mut self.llvm, llvm);
299         do_merge(&mut self.rust, rust);
300         do_merge(&mut self.dist, dist);
301         assert!(target.is_none(), "merging target-specific config is not currently supported");
302     }
303 }
304
305 /// TOML representation of various global build decisions.
306 #[derive(Deserialize, Default, Clone, Merge)]
307 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
308 struct Build {
309     build: Option<String>,
310     host: Option<Vec<String>>,
311     target: Option<Vec<String>>,
312     // This is ignored, the rust code always gets the build directory from the `BUILD_DIR` env variable
313     build_dir: Option<String>,
314     cargo: Option<String>,
315     rustc: Option<String>,
316     rustfmt: Option<PathBuf>,
317     docs: Option<bool>,
318     compiler_docs: Option<bool>,
319     submodules: Option<bool>,
320     fast_submodules: Option<bool>,
321     gdb: Option<String>,
322     nodejs: Option<String>,
323     python: Option<String>,
324     locked_deps: Option<bool>,
325     vendor: Option<bool>,
326     full_bootstrap: Option<bool>,
327     extended: Option<bool>,
328     tools: Option<HashSet<String>>,
329     verbose: Option<usize>,
330     sanitizers: Option<bool>,
331     profiler: Option<bool>,
332     cargo_native_static: Option<bool>,
333     low_priority: Option<bool>,
334     configure_args: Option<Vec<String>>,
335     local_rebuild: Option<bool>,
336     print_step_timings: Option<bool>,
337     doc_stage: Option<u32>,
338     build_stage: Option<u32>,
339     test_stage: Option<u32>,
340     install_stage: Option<u32>,
341     dist_stage: Option<u32>,
342     bench_stage: Option<u32>,
343 }
344
345 /// TOML representation of various global install decisions.
346 #[derive(Deserialize, Default, Clone, Merge)]
347 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
348 struct Install {
349     prefix: Option<String>,
350     sysconfdir: Option<String>,
351     docdir: Option<String>,
352     bindir: Option<String>,
353     libdir: Option<String>,
354     mandir: Option<String>,
355     datadir: Option<String>,
356
357     // standard paths, currently unused
358     infodir: Option<String>,
359     localstatedir: Option<String>,
360 }
361
362 /// TOML representation of how the LLVM build is configured.
363 #[derive(Deserialize, Default, Merge)]
364 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
365 struct Llvm {
366     skip_rebuild: Option<bool>,
367     optimize: Option<bool>,
368     thin_lto: Option<bool>,
369     release_debuginfo: Option<bool>,
370     assertions: Option<bool>,
371     ccache: Option<StringOrBool>,
372     version_check: Option<bool>,
373     static_libstdcpp: Option<bool>,
374     ninja: Option<bool>,
375     targets: Option<String>,
376     experimental_targets: Option<String>,
377     link_jobs: Option<u32>,
378     link_shared: Option<bool>,
379     version_suffix: Option<String>,
380     clang_cl: Option<String>,
381     cflags: Option<String>,
382     cxxflags: Option<String>,
383     ldflags: Option<String>,
384     use_libcxx: Option<bool>,
385     use_linker: Option<String>,
386     allow_old_toolchain: Option<bool>,
387     download_ci_llvm: Option<bool>,
388 }
389
390 #[derive(Deserialize, Default, Clone, Merge)]
391 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
392 struct Dist {
393     sign_folder: Option<String>,
394     gpg_password_file: Option<String>,
395     upload_addr: Option<String>,
396     src_tarball: Option<bool>,
397     missing_tools: Option<bool>,
398 }
399
400 #[derive(Deserialize)]
401 #[serde(untagged)]
402 enum StringOrBool {
403     String(String),
404     Bool(bool),
405 }
406
407 impl Default for StringOrBool {
408     fn default() -> StringOrBool {
409         StringOrBool::Bool(false)
410     }
411 }
412
413 /// TOML representation of how the Rust build is configured.
414 #[derive(Deserialize, Default, Merge)]
415 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
416 struct Rust {
417     optimize: Option<bool>,
418     debug: Option<bool>,
419     codegen_units: Option<u32>,
420     codegen_units_std: Option<u32>,
421     debug_assertions: Option<bool>,
422     debug_assertions_std: Option<bool>,
423     debug_logging: Option<bool>,
424     debuginfo_level: Option<u32>,
425     debuginfo_level_rustc: Option<u32>,
426     debuginfo_level_std: Option<u32>,
427     debuginfo_level_tools: Option<u32>,
428     debuginfo_level_tests: Option<u32>,
429     backtrace: Option<bool>,
430     incremental: Option<bool>,
431     parallel_compiler: Option<bool>,
432     default_linker: Option<String>,
433     channel: Option<String>,
434     musl_root: Option<String>,
435     rpath: Option<bool>,
436     verbose_tests: Option<bool>,
437     optimize_tests: Option<bool>,
438     codegen_tests: Option<bool>,
439     ignore_git: Option<bool>,
440     dist_src: Option<bool>,
441     save_toolstates: Option<String>,
442     codegen_backends: Option<Vec<String>>,
443     lld: Option<bool>,
444     use_lld: Option<bool>,
445     llvm_tools: Option<bool>,
446     deny_warnings: Option<bool>,
447     backtrace_on_ice: Option<bool>,
448     verify_llvm_ir: Option<bool>,
449     thin_lto_import_instr_limit: Option<u32>,
450     remap_debuginfo: Option<bool>,
451     jemalloc: Option<bool>,
452     test_compare_mode: Option<bool>,
453     llvm_libunwind: Option<bool>,
454     control_flow_guard: Option<bool>,
455     new_symbol_mangling: Option<bool>,
456 }
457
458 /// TOML representation of how each build target is configured.
459 #[derive(Deserialize, Default, Merge)]
460 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
461 struct TomlTarget {
462     cc: Option<String>,
463     cxx: Option<String>,
464     ar: Option<String>,
465     ranlib: Option<String>,
466     linker: Option<String>,
467     llvm_config: Option<String>,
468     llvm_filecheck: Option<String>,
469     android_ndk: Option<String>,
470     crt_static: Option<bool>,
471     musl_root: Option<String>,
472     musl_libdir: Option<String>,
473     wasi_root: Option<String>,
474     qemu_rootfs: Option<String>,
475     no_std: Option<bool>,
476 }
477
478 impl Config {
479     fn path_from_python(var_key: &str) -> PathBuf {
480         match env::var_os(var_key) {
481             Some(var_val) => Self::normalize_python_path(var_val),
482             _ => panic!("expected '{}' to be set", var_key),
483         }
484     }
485
486     /// Normalizes paths from Python slightly. We don't trust paths from Python (#49785).
487     fn normalize_python_path(path: OsString) -> PathBuf {
488         Path::new(&path).components().collect()
489     }
490
491     pub fn default_opts() -> Config {
492         let mut config = Config::default();
493         config.llvm_optimize = true;
494         config.ninja_in_file = true;
495         config.llvm_version_check = true;
496         config.backtrace = true;
497         config.rust_optimize = true;
498         config.rust_optimize_tests = true;
499         config.submodules = true;
500         config.fast_submodules = true;
501         config.docs = true;
502         config.rust_rpath = true;
503         config.channel = "dev".to_string();
504         config.codegen_tests = true;
505         config.ignore_git = false;
506         config.rust_dist_src = true;
507         config.rust_codegen_backends = vec![INTERNER.intern_str("llvm")];
508         config.deny_warnings = true;
509         config.missing_tools = false;
510
511         // set by bootstrap.py
512         config.build = TargetSelection::from_user(&env!("BUILD_TRIPLE"));
513         let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
514         // Undo `src/bootstrap`
515         config.src = manifest_dir.parent().unwrap().parent().unwrap().to_owned();
516         config.out = Config::path_from_python("BUILD_DIR");
517
518         config.initial_cargo = PathBuf::from(env!("CARGO"));
519         config.initial_rustc = PathBuf::from(env!("RUSTC"));
520
521         config
522     }
523
524     pub fn parse(args: &[String]) -> Config {
525         let flags = Flags::parse(&args);
526
527         let mut config = Config::default_opts();
528         config.exclude = flags.exclude;
529         config.rustc_error_format = flags.rustc_error_format;
530         config.json_output = flags.json_output;
531         config.on_fail = flags.on_fail;
532         config.jobs = flags.jobs.map(threads_from_config);
533         config.cmd = flags.cmd;
534         config.incremental = flags.incremental;
535         config.dry_run = flags.dry_run;
536         config.keep_stage = flags.keep_stage;
537         config.bindir = "bin".into(); // default
538         if let Some(value) = flags.deny_warnings {
539             config.deny_warnings = value;
540         }
541
542         if config.dry_run {
543             let dir = config.out.join("tmp-dry-run");
544             t!(fs::create_dir_all(&dir));
545             config.out = dir;
546         }
547
548         #[cfg(test)]
549         let get_toml = |_| TomlConfig::default();
550         #[cfg(not(test))]
551         let get_toml = |file: PathBuf| {
552             use std::process;
553
554             let contents = t!(fs::read_to_string(&file), "configuration file did not exist");
555             match toml::from_str(&contents) {
556                 Ok(table) => table,
557                 Err(err) => {
558                     println!("failed to parse TOML configuration '{}': {}", file.display(), err);
559                     process::exit(2);
560                 }
561             }
562         };
563
564         let mut toml = flags.config.map(get_toml).unwrap_or_else(TomlConfig::default);
565         if let Some(include) = &toml.profile {
566             let mut include_path = config.src.clone();
567             include_path.push("src");
568             include_path.push("bootstrap");
569             include_path.push("defaults");
570             include_path.push(format!("config.toml.{}", include));
571             let included_toml = get_toml(include_path);
572             toml.merge(included_toml);
573         }
574
575         let build = toml.build.unwrap_or_default();
576
577         // If --target was specified but --host wasn't specified, don't run any host-only tests.
578         let has_hosts = build.host.is_some() || flags.host.is_some();
579         let has_targets = build.target.is_some() || flags.target.is_some();
580         config.skip_only_host_steps = !has_hosts && has_targets;
581
582         config.hosts = if let Some(arg_host) = flags.host {
583             arg_host
584         } else if let Some(file_host) = build.host {
585             file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
586         } else {
587             vec![config.build]
588         };
589         config.targets = if let Some(arg_target) = flags.target {
590             arg_target
591         } else if let Some(file_target) = build.target {
592             file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
593         } else {
594             // If target is *not* configured, then default to the host
595             // toolchains.
596             config.hosts.clone()
597         };
598
599         config.nodejs = build.nodejs.map(PathBuf::from);
600         config.gdb = build.gdb.map(PathBuf::from);
601         config.python = build.python.map(PathBuf::from);
602         set(&mut config.low_priority, build.low_priority);
603         set(&mut config.compiler_docs, build.compiler_docs);
604         set(&mut config.docs, build.docs);
605         set(&mut config.submodules, build.submodules);
606         set(&mut config.fast_submodules, build.fast_submodules);
607         set(&mut config.locked_deps, build.locked_deps);
608         set(&mut config.vendor, build.vendor);
609         set(&mut config.full_bootstrap, build.full_bootstrap);
610         set(&mut config.extended, build.extended);
611         config.tools = build.tools;
612         if build.rustfmt.is_some() {
613             config.initial_rustfmt = build.rustfmt;
614         }
615         set(&mut config.verbose, build.verbose);
616         set(&mut config.sanitizers, build.sanitizers);
617         set(&mut config.profiler, build.profiler);
618         set(&mut config.cargo_native_static, build.cargo_native_static);
619         set(&mut config.configure_args, build.configure_args);
620         set(&mut config.local_rebuild, build.local_rebuild);
621         set(&mut config.print_step_timings, build.print_step_timings);
622
623         // See https://github.com/rust-lang/compiler-team/issues/326
624         config.stage = match config.cmd {
625             Subcommand::Doc { .. } => flags.stage.or(build.doc_stage).unwrap_or(0),
626             Subcommand::Build { .. } => flags.stage.or(build.build_stage).unwrap_or(1),
627             Subcommand::Test { .. } => flags.stage.or(build.test_stage).unwrap_or(1),
628             Subcommand::Bench { .. } => flags.stage.or(build.bench_stage).unwrap_or(2),
629             Subcommand::Dist { .. } => flags.stage.or(build.dist_stage).unwrap_or(2),
630             Subcommand::Install { .. } => flags.stage.or(build.install_stage).unwrap_or(2),
631             // These are all bootstrap tools, which don't depend on the compiler.
632             // The stage we pass shouldn't matter, but use 0 just in case.
633             Subcommand::Clean { .. }
634             | Subcommand::Check { .. }
635             | Subcommand::Clippy { .. }
636             | Subcommand::Fix { .. }
637             | Subcommand::Run { .. }
638             | Subcommand::Format { .. } => flags.stage.unwrap_or(0),
639         };
640
641         // CI should always run stage 2 builds, unless it specifically states otherwise
642         #[cfg(not(test))]
643         if flags.stage.is_none() && crate::CiEnv::current() != crate::CiEnv::None {
644             match config.cmd {
645                 Subcommand::Test { .. }
646                 | Subcommand::Doc { .. }
647                 | Subcommand::Build { .. }
648                 | Subcommand::Bench { .. }
649                 | Subcommand::Dist { .. }
650                 | Subcommand::Install { .. } => {
651                     assert_eq!(
652                         config.stage, 2,
653                         "x.py should be run with `--stage 2` on CI, but was run with `--stage {}`",
654                         config.stage,
655                     );
656                 }
657                 Subcommand::Clean { .. }
658                 | Subcommand::Check { .. }
659                 | Subcommand::Clippy { .. }
660                 | Subcommand::Fix { .. }
661                 | Subcommand::Run { .. }
662                 | Subcommand::Format { .. } => {}
663             }
664         }
665
666         config.verbose = cmp::max(config.verbose, flags.verbose);
667
668         if let Some(install) = toml.install {
669             config.prefix = install.prefix.map(PathBuf::from);
670             config.sysconfdir = install.sysconfdir.map(PathBuf::from);
671             config.datadir = install.datadir.map(PathBuf::from);
672             config.docdir = install.docdir.map(PathBuf::from);
673             set(&mut config.bindir, install.bindir.map(PathBuf::from));
674             config.libdir = install.libdir.map(PathBuf::from);
675             config.mandir = install.mandir.map(PathBuf::from);
676         }
677
678         // We want the llvm-skip-rebuild flag to take precedence over the
679         // skip-rebuild config.toml option so we store it separately
680         // so that we can infer the right value
681         let mut llvm_skip_rebuild = flags.llvm_skip_rebuild;
682
683         // Store off these values as options because if they're not provided
684         // we'll infer default values for them later
685         let mut llvm_assertions = None;
686         let mut debug = None;
687         let mut debug_assertions = None;
688         let mut debug_assertions_std = None;
689         let mut debug_logging = None;
690         let mut debuginfo_level = None;
691         let mut debuginfo_level_rustc = None;
692         let mut debuginfo_level_std = None;
693         let mut debuginfo_level_tools = None;
694         let mut debuginfo_level_tests = None;
695         let mut optimize = None;
696         let mut ignore_git = None;
697
698         if let Some(llvm) = toml.llvm {
699             match llvm.ccache {
700                 Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
701                 Some(StringOrBool::Bool(true)) => {
702                     config.ccache = Some("ccache".to_string());
703                 }
704                 Some(StringOrBool::Bool(false)) | None => {}
705             }
706             set(&mut config.ninja_in_file, llvm.ninja);
707             llvm_assertions = llvm.assertions;
708             llvm_skip_rebuild = llvm_skip_rebuild.or(llvm.skip_rebuild);
709             set(&mut config.llvm_optimize, llvm.optimize);
710             set(&mut config.llvm_thin_lto, llvm.thin_lto);
711             set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo);
712             set(&mut config.llvm_version_check, llvm.version_check);
713             set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp);
714             set(&mut config.llvm_link_shared, llvm.link_shared);
715             config.llvm_targets = llvm.targets.clone();
716             config.llvm_experimental_targets = llvm.experimental_targets.clone();
717             config.llvm_link_jobs = llvm.link_jobs;
718             config.llvm_version_suffix = llvm.version_suffix.clone();
719             config.llvm_clang_cl = llvm.clang_cl.clone();
720
721             config.llvm_cflags = llvm.cflags.clone();
722             config.llvm_cxxflags = llvm.cxxflags.clone();
723             config.llvm_ldflags = llvm.ldflags.clone();
724             set(&mut config.llvm_use_libcxx, llvm.use_libcxx);
725             config.llvm_use_linker = llvm.use_linker.clone();
726             config.llvm_allow_old_toolchain = llvm.allow_old_toolchain;
727             config.llvm_from_ci = llvm.download_ci_llvm.unwrap_or(false);
728
729             if config.llvm_from_ci {
730                 // None of the LLVM options, except assertions, are supported
731                 // when using downloaded LLVM. We could just ignore these but
732                 // that's potentially confusing, so force them to not be
733                 // explicitly set. The defaults and CI defaults don't
734                 // necessarily match but forcing people to match (somewhat
735                 // arbitrary) CI configuration locally seems bad/hard.
736                 check_ci_llvm!(llvm.optimize);
737                 check_ci_llvm!(llvm.thin_lto);
738                 check_ci_llvm!(llvm.release_debuginfo);
739                 check_ci_llvm!(llvm.link_shared);
740                 check_ci_llvm!(llvm.static_libstdcpp);
741                 check_ci_llvm!(llvm.targets);
742                 check_ci_llvm!(llvm.experimental_targets);
743                 check_ci_llvm!(llvm.link_jobs);
744                 check_ci_llvm!(llvm.link_shared);
745                 check_ci_llvm!(llvm.clang_cl);
746                 check_ci_llvm!(llvm.version_suffix);
747                 check_ci_llvm!(llvm.cflags);
748                 check_ci_llvm!(llvm.cxxflags);
749                 check_ci_llvm!(llvm.ldflags);
750                 check_ci_llvm!(llvm.use_libcxx);
751                 check_ci_llvm!(llvm.use_linker);
752                 check_ci_llvm!(llvm.allow_old_toolchain);
753
754                 // CI-built LLVM is shared
755                 config.llvm_link_shared = true;
756             }
757
758             if config.llvm_thin_lto {
759                 // If we're building with ThinLTO on, we want to link to LLVM
760                 // shared, to avoid re-doing ThinLTO (which happens in the link
761                 // step) with each stage.
762                 config.llvm_link_shared = true;
763             }
764         }
765
766         if let Some(rust) = toml.rust {
767             debug = rust.debug;
768             debug_assertions = rust.debug_assertions;
769             debug_assertions_std = rust.debug_assertions_std;
770             debug_logging = rust.debug_logging;
771             debuginfo_level = rust.debuginfo_level;
772             debuginfo_level_rustc = rust.debuginfo_level_rustc;
773             debuginfo_level_std = rust.debuginfo_level_std;
774             debuginfo_level_tools = rust.debuginfo_level_tools;
775             debuginfo_level_tests = rust.debuginfo_level_tests;
776             optimize = rust.optimize;
777             ignore_git = rust.ignore_git;
778             set(&mut config.rust_new_symbol_mangling, rust.new_symbol_mangling);
779             set(&mut config.rust_optimize_tests, rust.optimize_tests);
780             set(&mut config.codegen_tests, rust.codegen_tests);
781             set(&mut config.rust_rpath, rust.rpath);
782             set(&mut config.jemalloc, rust.jemalloc);
783             set(&mut config.test_compare_mode, rust.test_compare_mode);
784             set(&mut config.llvm_libunwind, rust.llvm_libunwind);
785             set(&mut config.backtrace, rust.backtrace);
786             set(&mut config.channel, rust.channel);
787             set(&mut config.rust_dist_src, rust.dist_src);
788             set(&mut config.verbose_tests, rust.verbose_tests);
789             // in the case "false" is set explicitly, do not overwrite the command line args
790             if let Some(true) = rust.incremental {
791                 config.incremental = true;
792             }
793             set(&mut config.use_lld, rust.use_lld);
794             set(&mut config.lld_enabled, rust.lld);
795             set(&mut config.llvm_tools_enabled, rust.llvm_tools);
796             config.rustc_parallel = rust.parallel_compiler.unwrap_or(false);
797             config.rustc_default_linker = rust.default_linker;
798             config.musl_root = rust.musl_root.map(PathBuf::from);
799             config.save_toolstates = rust.save_toolstates.map(PathBuf::from);
800             set(&mut config.deny_warnings, flags.deny_warnings.or(rust.deny_warnings));
801             set(&mut config.backtrace_on_ice, rust.backtrace_on_ice);
802             set(&mut config.rust_verify_llvm_ir, rust.verify_llvm_ir);
803             config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit;
804             set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo);
805             set(&mut config.control_flow_guard, rust.control_flow_guard);
806
807             if let Some(ref backends) = rust.codegen_backends {
808                 config.rust_codegen_backends =
809                     backends.iter().map(|s| INTERNER.intern_str(s)).collect();
810             }
811
812             config.rust_codegen_units = rust.codegen_units.map(threads_from_config);
813             config.rust_codegen_units_std = rust.codegen_units_std.map(threads_from_config);
814         }
815
816         if let Some(t) = toml.target {
817             for (triple, cfg) in t {
818                 let mut target = Target::from_triple(&triple);
819
820                 if let Some(ref s) = cfg.llvm_config {
821                     target.llvm_config = Some(config.src.join(s));
822                 }
823                 if let Some(ref s) = cfg.llvm_filecheck {
824                     target.llvm_filecheck = Some(config.src.join(s));
825                 }
826                 if let Some(ref s) = cfg.android_ndk {
827                     target.ndk = Some(config.src.join(s));
828                 }
829                 if let Some(s) = cfg.no_std {
830                     target.no_std = s;
831                 }
832                 target.cc = cfg.cc.map(PathBuf::from);
833                 target.cxx = cfg.cxx.map(PathBuf::from);
834                 target.ar = cfg.ar.map(PathBuf::from);
835                 target.ranlib = cfg.ranlib.map(PathBuf::from);
836                 target.linker = cfg.linker.map(PathBuf::from);
837                 target.crt_static = cfg.crt_static;
838                 target.musl_root = cfg.musl_root.map(PathBuf::from);
839                 target.musl_libdir = cfg.musl_libdir.map(PathBuf::from);
840                 target.wasi_root = cfg.wasi_root.map(PathBuf::from);
841                 target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from);
842
843                 config.target_config.insert(TargetSelection::from_user(&triple), target);
844             }
845         }
846
847         if config.llvm_from_ci {
848             let triple = &config.build.triple;
849             let mut build_target = config
850                 .target_config
851                 .entry(config.build)
852                 .or_insert_with(|| Target::from_triple(&triple));
853
854             check_ci_llvm!(build_target.llvm_config);
855             check_ci_llvm!(build_target.llvm_filecheck);
856             let ci_llvm_bin = config.out.join(&*config.build.triple).join("ci-llvm/bin");
857             build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", config.build)));
858             build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", config.build)));
859         }
860
861         if let Some(t) = toml.dist {
862             config.dist_sign_folder = t.sign_folder.map(PathBuf::from);
863             config.dist_gpg_password_file = t.gpg_password_file.map(PathBuf::from);
864             config.dist_upload_addr = t.upload_addr;
865             set(&mut config.rust_dist_src, t.src_tarball);
866             set(&mut config.missing_tools, t.missing_tools);
867         }
868
869         // Cargo does not provide a RUSTFMT environment variable, so we
870         // synthesize it manually. Note that we also later check the config.toml
871         // and set this to that path if necessary.
872         let rustfmt = config.initial_rustc.with_file_name(exe("rustfmt", config.build));
873         config.initial_rustfmt = if rustfmt.exists() { Some(rustfmt) } else { None };
874
875         // Now that we've reached the end of our configuration, infer the
876         // default values for all options that we haven't otherwise stored yet.
877
878         config.llvm_skip_rebuild = llvm_skip_rebuild.unwrap_or(false);
879
880         let default = false;
881         config.llvm_assertions = llvm_assertions.unwrap_or(default);
882
883         let default = true;
884         config.rust_optimize = optimize.unwrap_or(default);
885
886         let default = debug == Some(true);
887         config.rust_debug_assertions = debug_assertions.unwrap_or(default);
888         config.rust_debug_assertions_std =
889             debug_assertions_std.unwrap_or(config.rust_debug_assertions);
890
891         config.rust_debug_logging = debug_logging.unwrap_or(config.rust_debug_assertions);
892
893         let with_defaults = |debuginfo_level_specific: Option<u32>| {
894             debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
895                 1
896             } else {
897                 0
898             })
899         };
900         config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
901         config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
902         config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
903         config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(0);
904
905         let default = config.channel == "dev";
906         config.ignore_git = ignore_git.unwrap_or(default);
907
908         config
909     }
910
911     /// Try to find the relative path of `bindir`, otherwise return it in full.
912     pub fn bindir_relative(&self) -> &Path {
913         let bindir = &self.bindir;
914         if bindir.is_absolute() {
915             // Try to make it relative to the prefix.
916             if let Some(prefix) = &self.prefix {
917                 if let Ok(stripped) = bindir.strip_prefix(prefix) {
918                     return stripped;
919                 }
920             }
921         }
922         bindir
923     }
924
925     /// Try to find the relative path of `libdir`.
926     pub fn libdir_relative(&self) -> Option<&Path> {
927         let libdir = self.libdir.as_ref()?;
928         if libdir.is_relative() {
929             Some(libdir)
930         } else {
931             // Try to make it relative to the prefix.
932             libdir.strip_prefix(self.prefix.as_ref()?).ok()
933         }
934     }
935
936     pub fn verbose(&self) -> bool {
937         self.verbose > 0
938     }
939
940     pub fn very_verbose(&self) -> bool {
941         self.verbose > 1
942     }
943
944     pub fn llvm_enabled(&self) -> bool {
945         self.rust_codegen_backends.contains(&INTERNER.intern_str("llvm"))
946     }
947 }
948
949 fn set<T>(field: &mut T, val: Option<T>) {
950     if let Some(v) = val {
951         *field = v;
952     }
953 }
954
955 fn threads_from_config(v: u32) -> u32 {
956     match v {
957         0 => num_cpus::get() as u32,
958         n => n,
959     }
960 }