]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Rollup merge of #61116 - scottmcm:vcpp-download-link, r=alexcrichton
[rust.git] / src / bootstrap / builder.rs
1 use std::any::Any;
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
4 use std::collections::HashMap;
5 use std::env;
6 use std::fmt::Debug;
7 use std::fs;
8 use std::hash::Hash;
9 use std::ops::Deref;
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
13
14 use build_helper::t;
15
16 use crate::cache::{Cache, Interned, INTERNER};
17 use crate::check;
18 use crate::compile;
19 use crate::dist;
20 use crate::doc;
21 use crate::flags::Subcommand;
22 use crate::install;
23 use crate::native;
24 use crate::test;
25 use crate::tool;
26 use crate::util::{self, add_lib_path, exe, libdir};
27 use crate::{Build, DocTests, Mode, GitRepo};
28
29 pub use crate::Compiler;
30
31 use petgraph::graph::NodeIndex;
32 use petgraph::Graph;
33
34 pub struct Builder<'a> {
35     pub build: &'a Build,
36     pub top_stage: u32,
37     pub kind: Kind,
38     cache: Cache,
39     stack: RefCell<Vec<Box<dyn Any>>>,
40     time_spent_on_dependencies: Cell<Duration>,
41     pub paths: Vec<PathBuf>,
42     graph_nodes: RefCell<HashMap<String, NodeIndex>>,
43     graph: RefCell<Graph<String, bool>>,
44     parent: Cell<Option<NodeIndex>>,
45 }
46
47 impl<'a> Deref for Builder<'a> {
48     type Target = Build;
49
50     fn deref(&self) -> &Self::Target {
51         self.build
52     }
53 }
54
55 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
56     /// `PathBuf` when directories are created or to return a `Compiler` once
57     /// it's been assembled.
58     type Output: Clone;
59
60     const DEFAULT: bool = false;
61
62     /// Run this rule for all hosts without cross compiling.
63     const ONLY_HOSTS: bool = false;
64
65     /// Primary function to execute this rule. Can call `builder.ensure()`
66     /// with other steps to run those.
67     fn run(self, builder: &Builder<'_>) -> Self::Output;
68
69     /// When bootstrap is passed a set of paths, this controls whether this rule
70     /// will execute. However, it does not get called in a "default" context
71     /// when we are not passed any paths; in that case, `make_run` is called
72     /// directly.
73     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
74
75     /// Builds up a "root" rule, either as a default rule or from a path passed
76     /// to us.
77     ///
78     /// When path is `None`, we are executing in a context where no paths were
79     /// passed. When `./x.py build` is run, for example, this rule could get
80     /// called if it is in the correct list below with a path of `None`.
81     fn make_run(_run: RunConfig<'_>) {
82         // It is reasonable to not have an implementation of make_run for rules
83         // who do not want to get called from the root context. This means that
84         // they are likely dependencies (e.g., sysroot creation) or similar, and
85         // as such calling them from ./x.py isn't logical.
86         unimplemented!()
87     }
88 }
89
90 pub struct RunConfig<'a> {
91     pub builder: &'a Builder<'a>,
92     pub host: Interned<String>,
93     pub target: Interned<String>,
94     pub path: PathBuf,
95 }
96
97 struct StepDescription {
98     default: bool,
99     only_hosts: bool,
100     should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
101     make_run: fn(RunConfig<'_>),
102     name: &'static str,
103 }
104
105 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
106 pub enum PathSet {
107     Set(BTreeSet<PathBuf>),
108     Suite(PathBuf),
109 }
110
111 impl PathSet {
112     fn empty() -> PathSet {
113         PathSet::Set(BTreeSet::new())
114     }
115
116     fn one<P: Into<PathBuf>>(path: P) -> PathSet {
117         let mut set = BTreeSet::new();
118         set.insert(path.into());
119         PathSet::Set(set)
120     }
121
122     fn has(&self, needle: &Path) -> bool {
123         match self {
124             PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
125             PathSet::Suite(suite) => suite.ends_with(needle),
126         }
127     }
128
129     fn path(&self, builder: &Builder<'_>) -> PathBuf {
130         match self {
131             PathSet::Set(set) => set
132                 .iter()
133                 .next()
134                 .unwrap_or(&builder.build.src)
135                 .to_path_buf(),
136             PathSet::Suite(path) => PathBuf::from(path),
137         }
138     }
139 }
140
141 impl StepDescription {
142     fn from<S: Step>() -> StepDescription {
143         StepDescription {
144             default: S::DEFAULT,
145             only_hosts: S::ONLY_HOSTS,
146             should_run: S::should_run,
147             make_run: S::make_run,
148             name: unsafe { ::std::intrinsics::type_name::<S>() },
149         }
150     }
151
152     fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
153         if builder.config.exclude.iter().any(|e| pathset.has(e)) {
154             eprintln!("Skipping {:?} because it is excluded", pathset);
155             return;
156         } else if !builder.config.exclude.is_empty() {
157             eprintln!(
158                 "{:?} not skipped for {:?} -- not in {:?}",
159                 pathset, self.name, builder.config.exclude
160             );
161         }
162         let hosts = &builder.hosts;
163
164         // Determine the targets participating in this rule.
165         let targets = if self.only_hosts {
166             if !builder.config.run_host_only {
167                 return; // don't run anything
168             } else {
169                 &builder.hosts
170             }
171         } else {
172             &builder.targets
173         };
174
175         for host in hosts {
176             for target in targets {
177                 let run = RunConfig {
178                     builder,
179                     path: pathset.path(builder),
180                     host: *host,
181                     target: *target,
182                 };
183                 (self.make_run)(run);
184             }
185         }
186     }
187
188     fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
189         let should_runs = v
190             .iter()
191             .map(|desc| (desc.should_run)(ShouldRun::new(builder)))
192             .collect::<Vec<_>>();
193
194         // sanity checks on rules
195         for (desc, should_run) in v.iter().zip(&should_runs) {
196             assert!(
197                 !should_run.paths.is_empty(),
198                 "{:?} should have at least one pathset",
199                 desc.name
200             );
201         }
202
203         if paths.is_empty() {
204             for (desc, should_run) in v.iter().zip(should_runs) {
205                 if desc.default && should_run.is_really_default {
206                     for pathset in &should_run.paths {
207                         desc.maybe_run(builder, pathset);
208                     }
209                 }
210             }
211         } else {
212             for path in paths {
213                 // strip CurDir prefix if present
214                 let path = match path.strip_prefix(".") {
215                     Ok(p) => p,
216                     Err(_) => path,
217                 };
218
219                 let mut attempted_run = false;
220                 for (desc, should_run) in v.iter().zip(&should_runs) {
221                     if let Some(suite) = should_run.is_suite_path(path) {
222                         attempted_run = true;
223                         desc.maybe_run(builder, suite);
224                     } else if let Some(pathset) = should_run.pathset_for_path(path) {
225                         attempted_run = true;
226                         desc.maybe_run(builder, pathset);
227                     }
228                 }
229
230                 if !attempted_run {
231                     panic!("Error: no rules matched {}.", path.display());
232                 }
233             }
234         }
235     }
236 }
237
238 #[derive(Clone)]
239 pub struct ShouldRun<'a> {
240     pub builder: &'a Builder<'a>,
241     // use a BTreeSet to maintain sort order
242     paths: BTreeSet<PathSet>,
243
244     // If this is a default rule, this is an additional constraint placed on
245     // its run. Generally something like compiler docs being enabled.
246     is_really_default: bool,
247 }
248
249 impl<'a> ShouldRun<'a> {
250     fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
251         ShouldRun {
252             builder,
253             paths: BTreeSet::new(),
254             is_really_default: true, // by default no additional conditions
255         }
256     }
257
258     pub fn default_condition(mut self, cond: bool) -> Self {
259         self.is_really_default = cond;
260         self
261     }
262
263     // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
264     // ever be used, but as we transition to having all rules properly handle passing krate(...) by
265     // actually doing something different for every crate passed.
266     pub fn all_krates(mut self, name: &str) -> Self {
267         let mut set = BTreeSet::new();
268         for krate in self.builder.in_tree_crates(name) {
269             set.insert(PathBuf::from(&krate.path));
270         }
271         self.paths.insert(PathSet::Set(set));
272         self
273     }
274
275     pub fn krate(mut self, name: &str) -> Self {
276         for krate in self.builder.in_tree_crates(name) {
277             self.paths.insert(PathSet::one(&krate.path));
278         }
279         self
280     }
281
282     // single, non-aliased path
283     pub fn path(self, path: &str) -> Self {
284         self.paths(&[path])
285     }
286
287     // multiple aliases for the same job
288     pub fn paths(mut self, paths: &[&str]) -> Self {
289         self.paths
290             .insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
291         self
292     }
293
294     pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
295         self.paths.iter().find(|pathset| match pathset {
296             PathSet::Suite(p) => path.starts_with(p),
297             PathSet::Set(_) => false,
298         })
299     }
300
301     pub fn suite_path(mut self, suite: &str) -> Self {
302         self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
303         self
304     }
305
306     // allows being more explicit about why should_run in Step returns the value passed to it
307     pub fn never(mut self) -> ShouldRun<'a> {
308         self.paths.insert(PathSet::empty());
309         self
310     }
311
312     fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
313         self.paths.iter().find(|pathset| pathset.has(path))
314     }
315 }
316
317 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
318 pub enum Kind {
319     Build,
320     Check,
321     Test,
322     Bench,
323     Dist,
324     Doc,
325     Install,
326 }
327
328 impl<'a> Builder<'a> {
329     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
330         macro_rules! describe {
331             ($($rule:ty),+ $(,)?) => {{
332                 vec![$(StepDescription::from::<$rule>()),+]
333             }};
334         }
335         match kind {
336             Kind::Build => describe!(
337                 compile::Std,
338                 compile::Test,
339                 compile::Rustc,
340                 compile::CodegenBackend,
341                 compile::StartupObjects,
342                 tool::BuildManifest,
343                 tool::Rustbook,
344                 tool::ErrorIndex,
345                 tool::UnstableBookGen,
346                 tool::Tidy,
347                 tool::Linkchecker,
348                 tool::CargoTest,
349                 tool::Compiletest,
350                 tool::RemoteTestServer,
351                 tool::RemoteTestClient,
352                 tool::RustInstaller,
353                 tool::Cargo,
354                 tool::Rls,
355                 tool::Rustdoc,
356                 tool::Clippy,
357                 native::Llvm,
358                 tool::Rustfmt,
359                 tool::Miri,
360                 native::Lld
361             ),
362             Kind::Check => describe!(
363                 check::Std,
364                 check::Test,
365                 check::Rustc,
366                 check::CodegenBackend,
367                 check::Rustdoc
368             ),
369             Kind::Test => describe!(
370                 test::Tidy,
371                 test::Ui,
372                 test::RunPass,
373                 test::CompileFail,
374                 test::RunFail,
375                 test::RunPassValgrind,
376                 test::MirOpt,
377                 test::Codegen,
378                 test::CodegenUnits,
379                 test::Assembly,
380                 test::Incremental,
381                 test::Debuginfo,
382                 test::UiFullDeps,
383                 test::RunPassFullDeps,
384                 test::Rustdoc,
385                 test::Pretty,
386                 test::RunPassPretty,
387                 test::RunFailPretty,
388                 test::RunPassValgrindPretty,
389                 test::Crate,
390                 test::CrateLibrustc,
391                 test::CrateRustdoc,
392                 test::Linkcheck,
393                 test::Cargotest,
394                 test::Cargo,
395                 test::Rls,
396                 test::ErrorIndex,
397                 test::Distcheck,
398                 test::RunMakeFullDeps,
399                 test::Nomicon,
400                 test::Reference,
401                 test::RustdocBook,
402                 test::RustByExample,
403                 test::TheBook,
404                 test::UnstableBook,
405                 test::RustcBook,
406                 test::EmbeddedBook,
407                 test::EditionGuide,
408                 test::Rustfmt,
409                 test::Miri,
410                 test::Clippy,
411                 test::CompiletestTest,
412                 test::RustdocJSStd,
413                 test::RustdocJSNotStd,
414                 test::RustdocTheme,
415                 test::RustdocUi,
416                 // Run bootstrap close to the end as it's unlikely to fail
417                 test::Bootstrap,
418                 // Run run-make last, since these won't pass without make on Windows
419                 test::RunMake,
420             ),
421             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
422             Kind::Doc => describe!(
423                 doc::UnstableBook,
424                 doc::UnstableBookGen,
425                 doc::TheBook,
426                 doc::Standalone,
427                 doc::Std,
428                 doc::Test,
429                 doc::WhitelistedRustc,
430                 doc::Rustc,
431                 doc::Rustdoc,
432                 doc::ErrorIndex,
433                 doc::Nomicon,
434                 doc::Reference,
435                 doc::RustdocBook,
436                 doc::RustByExample,
437                 doc::RustcBook,
438                 doc::CargoBook,
439                 doc::EmbeddedBook,
440                 doc::EditionGuide,
441             ),
442             Kind::Dist => describe!(
443                 dist::Docs,
444                 dist::RustcDocs,
445                 dist::Mingw,
446                 dist::Rustc,
447                 dist::DebuggerScripts,
448                 dist::Std,
449                 dist::Analysis,
450                 dist::Src,
451                 dist::PlainSourceTarball,
452                 dist::Cargo,
453                 dist::Rls,
454                 dist::Rustfmt,
455                 dist::Clippy,
456                 dist::Miri,
457                 dist::LlvmTools,
458                 dist::Lldb,
459                 dist::Extended,
460                 dist::HashSign
461             ),
462             Kind::Install => describe!(
463                 install::Docs,
464                 install::Std,
465                 install::Cargo,
466                 install::Rls,
467                 install::Rustfmt,
468                 install::Clippy,
469                 install::Miri,
470                 install::Analysis,
471                 install::Src,
472                 install::Rustc
473             ),
474         }
475     }
476
477     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
478         let kind = match subcommand {
479             "build" => Kind::Build,
480             "doc" => Kind::Doc,
481             "test" => Kind::Test,
482             "bench" => Kind::Bench,
483             "dist" => Kind::Dist,
484             "install" => Kind::Install,
485             _ => return None,
486         };
487
488         let builder = Builder {
489             build,
490             top_stage: build.config.stage.unwrap_or(2),
491             kind,
492             cache: Cache::new(),
493             stack: RefCell::new(Vec::new()),
494             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
495             paths: vec![],
496             graph_nodes: RefCell::new(HashMap::new()),
497             graph: RefCell::new(Graph::new()),
498             parent: Cell::new(None),
499         };
500
501         let builder = &builder;
502         let mut should_run = ShouldRun::new(builder);
503         for desc in Builder::get_step_descriptions(builder.kind) {
504             should_run = (desc.should_run)(should_run);
505         }
506         let mut help = String::from("Available paths:\n");
507         for pathset in should_run.paths {
508             if let PathSet::Set(set) = pathset {
509                 set.iter().for_each(|path| {
510                     help.push_str(
511                         format!("    ./x.py {} {}\n", subcommand, path.display()).as_str(),
512                     )
513                 })
514             }
515         }
516         Some(help)
517     }
518
519     pub fn new(build: &Build) -> Builder<'_> {
520         let (kind, paths) = match build.config.cmd {
521             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
522             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
523             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
524             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
525             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
526             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
527             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
528             Subcommand::Clean { .. } => panic!(),
529         };
530
531         let builder = Builder {
532             build,
533             top_stage: build.config.stage.unwrap_or(2),
534             kind,
535             cache: Cache::new(),
536             stack: RefCell::new(Vec::new()),
537             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
538             paths: paths.to_owned(),
539             graph_nodes: RefCell::new(HashMap::new()),
540             graph: RefCell::new(Graph::new()),
541             parent: Cell::new(None),
542         };
543
544         if kind == Kind::Dist {
545             assert!(
546                 !builder.config.test_miri,
547                 "Do not distribute with miri enabled.\n\
548                 The distributed libraries would include all MIR (increasing binary size).
549                 The distributed MIR would include validation statements."
550             );
551         }
552
553         builder
554     }
555
556     pub fn execute_cli(&self) -> Graph<String, bool> {
557         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
558         self.graph.borrow().clone()
559     }
560
561     pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
562         let paths = paths.unwrap_or(&[]);
563         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
564     }
565
566     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
567         StepDescription::run(v, self, paths);
568     }
569
570     /// Obtain a compiler at a given stage and for a given host. Explicitly does
571     /// not take `Compiler` since all `Compiler` instances are meant to be
572     /// obtained through this function, since it ensures that they are valid
573     /// (i.e., built and assembled).
574     pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
575         self.ensure(compile::Assemble {
576             target_compiler: Compiler { stage, host },
577         })
578     }
579
580     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
581         self.ensure(compile::Sysroot { compiler })
582     }
583
584     /// Returns the libdir where the standard library and other artifacts are
585     /// found for a compiler's sysroot.
586     pub fn sysroot_libdir(
587         &self,
588         compiler: Compiler,
589         target: Interned<String>,
590     ) -> Interned<PathBuf> {
591         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
592         struct Libdir {
593             compiler: Compiler,
594             target: Interned<String>,
595         }
596         impl Step for Libdir {
597             type Output = Interned<PathBuf>;
598
599             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
600                 run.never()
601             }
602
603             fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
604                 let compiler = self.compiler;
605                 let config = &builder.build.config;
606                 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
607                     builder.build.config.libdir_relative().unwrap()
608                 } else {
609                     Path::new("lib")
610                 };
611                 let sysroot = builder
612                     .sysroot(self.compiler)
613                     .join(lib)
614                     .join("rustlib")
615                     .join(self.target)
616                     .join("lib");
617                 let _ = fs::remove_dir_all(&sysroot);
618                 t!(fs::create_dir_all(&sysroot));
619                 INTERNER.intern_path(sysroot)
620             }
621         }
622         self.ensure(Libdir { compiler, target })
623     }
624
625     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
626         self.sysroot_libdir(compiler, compiler.host)
627             .with_file_name(self.config.rust_codegen_backends_dir.clone())
628     }
629
630     /// Returns the compiler's libdir where it stores the dynamic libraries that
631     /// it itself links against.
632     ///
633     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
634     /// Windows.
635     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
636         if compiler.is_snapshot(self) {
637             self.rustc_snapshot_libdir()
638         } else {
639             match self.config.libdir_relative() {
640                 Some(relative_libdir) if compiler.stage >= 1
641                     => self.sysroot(compiler).join(relative_libdir),
642                 _ => self.sysroot(compiler).join(libdir(&compiler.host))
643             }
644         }
645     }
646
647     /// Returns the compiler's relative libdir where it stores the dynamic libraries that
648     /// it itself links against.
649     ///
650     /// For example this returns `lib` on Unix and `bin` on
651     /// Windows.
652     pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
653         if compiler.is_snapshot(self) {
654             libdir(&self.config.build).as_ref()
655         } else {
656             match self.config.libdir_relative() {
657                 Some(relative_libdir) if compiler.stage >= 1
658                     => relative_libdir,
659                 _ => libdir(&compiler.host).as_ref()
660             }
661         }
662     }
663
664     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
665     /// library lookup path.
666     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
667         // Windows doesn't need dylib path munging because the dlls for the
668         // compiler live next to the compiler and the system will find them
669         // automatically.
670         if cfg!(windows) {
671             return;
672         }
673
674         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
675     }
676
677     /// Gets a path to the compiler specified.
678     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
679         if compiler.is_snapshot(self) {
680             self.initial_rustc.clone()
681         } else {
682             self.sysroot(compiler)
683                 .join("bin")
684                 .join(exe("rustc", &compiler.host))
685         }
686     }
687
688     /// Gets the paths to all of the compiler's codegen backends.
689     fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
690         fs::read_dir(self.sysroot_codegen_backends(compiler))
691             .into_iter()
692             .flatten()
693             .filter_map(Result::ok)
694             .map(|entry| entry.path())
695     }
696
697     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
698         self.ensure(tool::Rustdoc { compiler })
699     }
700
701     pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
702         let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
703         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
704             .env("RUSTC_SYSROOT", self.sysroot(compiler))
705             // Note that this is *not* the sysroot_libdir because rustdoc must be linked
706             // equivalently to rustc.
707             .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
708             .env("CFG_RELEASE_CHANNEL", &self.config.channel)
709             .env("RUSTDOC_REAL", self.rustdoc(compiler))
710             .env("RUSTDOC_CRATE_VERSION", self.rust_version())
711             .env("RUSTC_BOOTSTRAP", "1");
712
713         // Remove make-related flags that can cause jobserver problems.
714         cmd.env_remove("MAKEFLAGS");
715         cmd.env_remove("MFLAGS");
716
717         if let Some(linker) = self.linker(compiler.host) {
718             cmd.env("RUSTC_TARGET_LINKER", linker);
719         }
720         cmd
721     }
722
723     /// Prepares an invocation of `cargo` to be run.
724     ///
725     /// This will create a `Command` that represents a pending execution of
726     /// Cargo. This cargo will be configured to use `compiler` as the actual
727     /// rustc compiler, its output will be scoped by `mode`'s output directory,
728     /// it will pass the `--target` flag for the specified `target`, and will be
729     /// executing the Cargo command `cmd`.
730     pub fn cargo(
731         &self,
732         compiler: Compiler,
733         mode: Mode,
734         target: Interned<String>,
735         cmd: &str,
736     ) -> Command {
737         let mut cargo = Command::new(&self.initial_cargo);
738         let out_dir = self.stage_out(compiler, mode);
739
740         // command specific path, we call clear_if_dirty with this
741         let mut my_out = match cmd {
742             "build" => self.cargo_out(compiler, mode, target),
743
744             // This is the intended out directory for crate documentation.
745             "doc" | "rustdoc" =>  self.crate_doc_out(target),
746
747             _ => self.stage_out(compiler, mode),
748         };
749
750         // This is for the original compiler, but if we're forced to use stage 1, then
751         // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
752         // we copy the libs forward.
753         let cmp = if self.force_use_stage1(compiler, target) {
754             self.compiler(1, compiler.host)
755         } else {
756             compiler
757         };
758
759         let libstd_stamp = match cmd {
760             "check" => check::libstd_stamp(self, cmp, target),
761             _ => compile::libstd_stamp(self, cmp, target),
762         };
763
764         let libtest_stamp = match cmd {
765             "check" => check::libtest_stamp(self, cmp, target),
766             _ => compile::libstd_stamp(self, cmp, target),
767         };
768
769         let librustc_stamp = match cmd {
770             "check" => check::librustc_stamp(self, cmp, target),
771             _ => compile::librustc_stamp(self, cmp, target),
772         };
773
774         if cmd == "doc" || cmd == "rustdoc" {
775             if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen {
776                 // This is the intended out directory for compiler documentation.
777                 my_out = self.compiler_doc_out(target);
778             }
779             let rustdoc = self.rustdoc(compiler);
780             self.clear_if_dirty(&my_out, &rustdoc);
781         } else if cmd != "test" {
782             match mode {
783                 Mode::Std => {
784                     self.clear_if_dirty(&my_out, &self.rustc(compiler));
785                     for backend in self.codegen_backends(compiler) {
786                         self.clear_if_dirty(&my_out, &backend);
787                     }
788                 },
789                 Mode::Test => {
790                     self.clear_if_dirty(&my_out, &libstd_stamp);
791                 },
792                 Mode::Rustc => {
793                     self.clear_if_dirty(&my_out, &self.rustc(compiler));
794                     self.clear_if_dirty(&my_out, &libstd_stamp);
795                     self.clear_if_dirty(&my_out, &libtest_stamp);
796                 },
797                 Mode::Codegen => {
798                     self.clear_if_dirty(&my_out, &librustc_stamp);
799                 },
800                 Mode::ToolBootstrap => { },
801                 Mode::ToolStd => {
802                     self.clear_if_dirty(&my_out, &libstd_stamp);
803                 },
804                 Mode::ToolTest => {
805                     self.clear_if_dirty(&my_out, &libstd_stamp);
806                     self.clear_if_dirty(&my_out, &libtest_stamp);
807                 },
808                 Mode::ToolRustc => {
809                     self.clear_if_dirty(&my_out, &libstd_stamp);
810                     self.clear_if_dirty(&my_out, &libtest_stamp);
811                     self.clear_if_dirty(&my_out, &librustc_stamp);
812                 },
813             }
814         }
815
816         cargo
817             .env("CARGO_TARGET_DIR", out_dir)
818             .arg(cmd);
819
820         // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
821         // needs to not accidentally link to libLLVM in stage0/lib.
822         cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
823         if let Some(e) = env::var_os(util::dylib_path_var()) {
824             cargo.env("REAL_LIBRARY_PATH", e);
825         }
826
827         if cmd != "install" {
828             cargo.arg("--target")
829                  .arg(target);
830         } else {
831             assert_eq!(target, compiler.host);
832         }
833
834         // Set a flag for `check` so that certain build scripts can do less work
835         // (e.g., not building/requiring LLVM).
836         if cmd == "check" {
837             cargo.env("RUST_CHECK", "1");
838         }
839
840         match mode {
841             Mode::Std | Mode::Test | Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTest=> {},
842             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
843                 // Build proc macros both for the host and the target
844                 if target != compiler.host && cmd != "check" {
845                     cargo.arg("-Zdual-proc-macros");
846                     cargo.env("RUST_DUAL_PROC_MACROS", "1");
847                 }
848             },
849         }
850
851         cargo.arg("-j").arg(self.jobs().to_string());
852         // Remove make-related flags to ensure Cargo can correctly set things up
853         cargo.env_remove("MAKEFLAGS");
854         cargo.env_remove("MFLAGS");
855
856         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
857         // Force cargo to output binaries with disambiguating hashes in the name
858         let mut metadata = if compiler.stage == 0 {
859             // Treat stage0 like a special channel, whether it's a normal prior-
860             // release rustc or a local rebuild with the same version, so we
861             // never mix these libraries by accident.
862             "bootstrap".to_string()
863         } else {
864             self.config.channel.to_string()
865         };
866         // We want to make sure that none of the dependencies between
867         // std/test/rustc unify with one another. This is done for weird linkage
868         // reasons but the gist of the problem is that if librustc, libtest, and
869         // libstd all depend on libc from crates.io (which they actually do) we
870         // want to make sure they all get distinct versions. Things get really
871         // weird if we try to unify all these dependencies right now, namely
872         // around how many times the library is linked in dynamic libraries and
873         // such. If rustc were a static executable or if we didn't ship dylibs
874         // this wouldn't be a problem, but we do, so it is. This is in general
875         // just here to make sure things build right. If you can remove this and
876         // things still build right, please do!
877         match mode {
878             Mode::Std => metadata.push_str("std"),
879             Mode::Test => metadata.push_str("test"),
880             _ => {},
881         }
882         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
883
884         let stage;
885         if compiler.stage == 0 && self.local_rebuild {
886             // Assume the local-rebuild rustc already has stage1 features.
887             stage = 1;
888         } else {
889             stage = compiler.stage;
890         }
891
892         let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
893         if stage != 0 {
894             let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
895             if !extra_args.is_empty() {
896                 extra_args.push_str(" ");
897             }
898             extra_args.push_str(&s);
899         }
900
901         if !extra_args.is_empty() {
902             cargo.env(
903                 "RUSTFLAGS",
904                 format!(
905                     "{} {}",
906                     env::var("RUSTFLAGS").unwrap_or_default(),
907                     extra_args
908                 ),
909             );
910         }
911
912         let want_rustdoc = self.doc_tests != DocTests::No;
913
914         // We synthetically interpret a stage0 compiler used to build tools as a
915         // "raw" compiler in that it's the exact snapshot we download. Normally
916         // the stage0 build means it uses libraries build by the stage0
917         // compiler, but for tools we just use the precompiled libraries that
918         // we've downloaded
919         let use_snapshot = mode == Mode::ToolBootstrap;
920         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
921
922         let maybe_sysroot = self.sysroot(compiler);
923         let sysroot = if use_snapshot {
924             self.rustc_snapshot_sysroot()
925         } else {
926             &maybe_sysroot
927         };
928         let libdir = self.rustc_libdir(compiler);
929
930         // Customize the compiler we're running. Specify the compiler to cargo
931         // as our shim and then pass it some various options used to configure
932         // how the actual compiler itself is called.
933         //
934         // These variables are primarily all read by
935         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
936         cargo
937             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
938             .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
939             .env("RUSTC_REAL", self.rustc(compiler))
940             .env("RUSTC_STAGE", stage.to_string())
941             .env(
942                 "RUSTC_DEBUG_ASSERTIONS",
943                 self.config.rust_debug_assertions.to_string(),
944             )
945             .env("RUSTC_SYSROOT", &sysroot)
946             .env("RUSTC_LIBDIR", &libdir)
947             .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
948             .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
949             .env(
950                 "RUSTDOC_REAL",
951                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
952                     self.rustdoc(compiler)
953                 } else {
954                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
955                 },
956             )
957             .env("TEST_MIRI", self.config.test_miri.to_string())
958             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
959
960         if let Some(host_linker) = self.linker(compiler.host) {
961             cargo.env("RUSTC_HOST_LINKER", host_linker);
962         }
963         if let Some(target_linker) = self.linker(target) {
964             cargo.env("RUSTC_TARGET_LINKER", target_linker);
965         }
966         if let Some(ref error_format) = self.config.rustc_error_format {
967             cargo.env("RUSTC_ERROR_FORMAT", error_format);
968         }
969         if cmd != "build" && cmd != "check" && cmd != "rustc" && want_rustdoc {
970             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
971         }
972
973         let debuginfo_level = match mode {
974             Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
975             Mode::Std | Mode::Test => self.config.rust_debuginfo_level_std,
976             Mode::ToolBootstrap | Mode::ToolStd |
977             Mode::ToolTest | Mode::ToolRustc => self.config.rust_debuginfo_level_tools,
978         };
979         cargo.env("RUSTC_DEBUGINFO_LEVEL", debuginfo_level.to_string());
980
981         if !mode.is_tool() {
982             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
983
984             // Currently the compiler depends on crates from crates.io, and
985             // then other crates can depend on the compiler (e.g., proc-macro
986             // crates). Let's say, for example that rustc itself depends on the
987             // bitflags crate. If an external crate then depends on the
988             // bitflags crate as well, we need to make sure they don't
989             // conflict, even if they pick the same version of bitflags. We'll
990             // want to make sure that e.g., a plugin and rustc each get their
991             // own copy of bitflags.
992
993             // Cargo ensures that this works in general through the -C metadata
994             // flag. This flag will frob the symbols in the binary to make sure
995             // they're different, even though the source code is the exact
996             // same. To solve this problem for the compiler we extend Cargo's
997             // already-passed -C metadata flag with our own. Our rustc.rs
998             // wrapper around the actual rustc will detect -C metadata being
999             // passed and frob it with this extra string we're passing in.
1000             cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
1001         }
1002
1003         if let Some(x) = self.crt_static(target) {
1004             cargo.env("RUSTC_CRT_STATIC", x.to_string());
1005         }
1006
1007         if let Some(x) = self.crt_static(compiler.host) {
1008             cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1009         }
1010
1011         if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
1012             cargo.env("RUSTC_DEBUGINFO_MAP", map);
1013         }
1014
1015         // Enable usage of unstable features
1016         cargo.env("RUSTC_BOOTSTRAP", "1");
1017         self.add_rust_test_threads(&mut cargo);
1018
1019         // Almost all of the crates that we compile as part of the bootstrap may
1020         // have a build script, including the standard library. To compile a
1021         // build script, however, it itself needs a standard library! This
1022         // introduces a bit of a pickle when we're compiling the standard
1023         // library itself.
1024         //
1025         // To work around this we actually end up using the snapshot compiler
1026         // (stage0) for compiling build scripts of the standard library itself.
1027         // The stage0 compiler is guaranteed to have a libstd available for use.
1028         //
1029         // For other crates, however, we know that we've already got a standard
1030         // library up and running, so we can use the normal compiler to compile
1031         // build scripts in that situation.
1032         if mode == Mode::Std {
1033             cargo
1034                 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1035                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1036         } else {
1037             cargo
1038                 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1039                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1040         }
1041
1042         if self.config.incremental {
1043             cargo.env("CARGO_INCREMENTAL", "1");
1044         } else {
1045             // Don't rely on any default setting for incr. comp. in Cargo
1046             cargo.env("CARGO_INCREMENTAL", "0");
1047         }
1048
1049         if let Some(ref on_fail) = self.config.on_fail {
1050             cargo.env("RUSTC_ON_FAIL", on_fail);
1051         }
1052
1053         if self.config.print_step_timings {
1054             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1055         }
1056
1057         if self.config.backtrace_on_ice {
1058             cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1059         }
1060
1061         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1062
1063         if self.config.deny_warnings {
1064             cargo.env("RUSTC_DENY_WARNINGS", "1");
1065         }
1066
1067         // Throughout the build Cargo can execute a number of build scripts
1068         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1069         // obtained previously to those build scripts.
1070         // Build scripts use either the `cc` crate or `configure/make` so we pass
1071         // the options through environment variables that are fetched and understood by both.
1072         //
1073         // FIXME: the guard against msvc shouldn't need to be here
1074         if target.contains("msvc") {
1075             if let Some(ref cl) = self.config.llvm_clang_cl {
1076                 cargo.env("CC", cl).env("CXX", cl);
1077             }
1078         } else {
1079             let ccache = self.config.ccache.as_ref();
1080             let ccacheify = |s: &Path| {
1081                 let ccache = match ccache {
1082                     Some(ref s) => s,
1083                     None => return s.display().to_string(),
1084                 };
1085                 // FIXME: the cc-rs crate only recognizes the literal strings
1086                 // `ccache` and `sccache` when doing caching compilations, so we
1087                 // mirror that here. It should probably be fixed upstream to
1088                 // accept a new env var or otherwise work with custom ccache
1089                 // vars.
1090                 match &ccache[..] {
1091                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1092                     _ => s.display().to_string(),
1093                 }
1094             };
1095             let cc = ccacheify(&self.cc(target));
1096             cargo.env(format!("CC_{}", target), &cc);
1097
1098             let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1099             cargo
1100                 .env(format!("CFLAGS_{}", target), cflags.clone());
1101
1102             if let Some(ar) = self.ar(target) {
1103                 let ranlib = format!("{} s", ar.display());
1104                 cargo
1105                     .env(format!("AR_{}", target), ar)
1106                     .env(format!("RANLIB_{}", target), ranlib);
1107             }
1108
1109             if let Ok(cxx) = self.cxx(target) {
1110                 let cxx = ccacheify(&cxx);
1111                 cargo
1112                     .env(format!("CXX_{}", target), &cxx)
1113                     .env(format!("CXXFLAGS_{}", target), cflags);
1114             }
1115         }
1116
1117         if (cmd == "build" || cmd == "rustc")
1118             && mode == Mode::Std
1119             && self.config.extended
1120             && compiler.is_final_stage(self)
1121         {
1122             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
1123         }
1124
1125         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1126         cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1127
1128         // Environment variables *required* throughout the build
1129         //
1130         // FIXME: should update code to not require this env var
1131         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1132
1133         // Set this for all builds to make sure doc builds also get it.
1134         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1135
1136         // This one's a bit tricky. As of the time of this writing the compiler
1137         // links to the `winapi` crate on crates.io. This crate provides raw
1138         // bindings to Windows system functions, sort of like libc does for
1139         // Unix. This crate also, however, provides "import libraries" for the
1140         // MinGW targets. There's an import library per dll in the windows
1141         // distribution which is what's linked to. These custom import libraries
1142         // are used because the winapi crate can reference Windows functions not
1143         // present in the MinGW import libraries.
1144         //
1145         // For example MinGW may ship libdbghelp.a, but it may not have
1146         // references to all the functions in the dbghelp dll. Instead the
1147         // custom import library for dbghelp in the winapi crates has all this
1148         // information.
1149         //
1150         // Unfortunately for us though the import libraries are linked by
1151         // default via `-ldylib=winapi_foo`. That is, they're linked with the
1152         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1153         // conflict with the system MinGW ones). This consequently means that
1154         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1155         // DLL) when linked against *again*, for example with procedural macros
1156         // or plugins, will trigger the propagation logic of `-ldylib`, passing
1157         // `-lwinapi_foo` to the linker again. This isn't actually available in
1158         // our distribution, however, so the link fails.
1159         //
1160         // To solve this problem we tell winapi to not use its bundled import
1161         // libraries. This means that it will link to the system MinGW import
1162         // libraries by default, and the `-ldylib=foo` directives will still get
1163         // passed to the final linker, but they'll look like `-lfoo` which can
1164         // be resolved because MinGW has the import library. The downside is we
1165         // don't get newer functions from Windows, but we don't use any of them
1166         // anyway.
1167         if !mode.is_tool() {
1168             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1169         }
1170
1171         for _ in 1..self.verbosity {
1172             cargo.arg("-v");
1173         }
1174
1175         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1176             (Mode::Std, Some(n), _) |
1177             (Mode::Test, Some(n), _) |
1178             (_, _, Some(n)) => {
1179                 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
1180             }
1181             _ => {
1182                 // Don't set anything
1183             }
1184         }
1185
1186         if self.config.rust_optimize {
1187             // FIXME: cargo bench/install do not accept `--release`
1188             if cmd != "bench" && cmd != "install" {
1189                 cargo.arg("--release");
1190             }
1191         }
1192
1193         if self.config.locked_deps {
1194             cargo.arg("--locked");
1195         }
1196         if self.config.vendor || self.is_sudo {
1197             cargo.arg("--frozen");
1198         }
1199
1200         self.ci_env.force_coloring_in_ci(&mut cargo);
1201
1202         cargo
1203     }
1204
1205     /// Ensure that a given step is built, returning its output. This will
1206     /// cache the step, so it is safe (and good!) to call this as often as
1207     /// needed to ensure that all dependencies are built.
1208     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1209         {
1210             let mut stack = self.stack.borrow_mut();
1211             for stack_step in stack.iter() {
1212                 // should skip
1213                 if stack_step
1214                     .downcast_ref::<S>()
1215                     .map_or(true, |stack_step| *stack_step != step)
1216                 {
1217                     continue;
1218                 }
1219                 let mut out = String::new();
1220                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1221                 for el in stack.iter().rev() {
1222                     out += &format!("\t{:?}\n", el);
1223                 }
1224                 panic!(out);
1225             }
1226             if let Some(out) = self.cache.get(&step) {
1227                 self.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
1228
1229                 {
1230                     let mut graph = self.graph.borrow_mut();
1231                     let parent = self.parent.get();
1232                     let us = *self
1233                         .graph_nodes
1234                         .borrow_mut()
1235                         .entry(format!("{:?}", step))
1236                         .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1237                     if let Some(parent) = parent {
1238                         graph.add_edge(parent, us, false);
1239                     }
1240                 }
1241
1242                 return out;
1243             }
1244             self.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
1245             stack.push(Box::new(step.clone()));
1246         }
1247
1248         let prev_parent = self.parent.get();
1249
1250         {
1251             let mut graph = self.graph.borrow_mut();
1252             let parent = self.parent.get();
1253             let us = *self
1254                 .graph_nodes
1255                 .borrow_mut()
1256                 .entry(format!("{:?}", step))
1257                 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1258             self.parent.set(Some(us));
1259             if let Some(parent) = parent {
1260                 graph.add_edge(parent, us, true);
1261             }
1262         }
1263
1264         let (out, dur) = {
1265             let start = Instant::now();
1266             let zero = Duration::new(0, 0);
1267             let parent = self.time_spent_on_dependencies.replace(zero);
1268             let out = step.clone().run(self);
1269             let dur = start.elapsed();
1270             let deps = self.time_spent_on_dependencies.replace(parent + dur);
1271             (out, dur - deps)
1272         };
1273
1274         self.parent.set(prev_parent);
1275
1276         if self.config.print_step_timings && dur > Duration::from_millis(100) {
1277             println!(
1278                 "[TIMING] {:?} -- {}.{:03}",
1279                 step,
1280                 dur.as_secs(),
1281                 dur.subsec_nanos() / 1_000_000
1282             );
1283         }
1284
1285         {
1286             let mut stack = self.stack.borrow_mut();
1287             let cur_step = stack.pop().expect("step stack empty");
1288             assert_eq!(cur_step.downcast_ref(), Some(&step));
1289         }
1290         self.verbose(&format!(
1291             "{}< {:?}",
1292             "  ".repeat(self.stack.borrow().len()),
1293             step
1294         ));
1295         self.cache.put(step, out.clone());
1296         out
1297     }
1298 }
1299
1300 #[cfg(test)]
1301 mod __test {
1302     use super::*;
1303     use crate::config::Config;
1304     use std::thread;
1305
1306     use pretty_assertions::assert_eq;
1307
1308     fn configure(host: &[&str], target: &[&str]) -> Config {
1309         let mut config = Config::default_opts();
1310         // don't save toolstates
1311         config.save_toolstates = None;
1312         config.run_host_only = true;
1313         config.dry_run = true;
1314         // try to avoid spurious failures in dist where we create/delete each others file
1315         let dir = config.out.join("tmp-rustbuild-tests").join(
1316             &thread::current()
1317                 .name()
1318                 .unwrap_or("unknown")
1319                 .replace(":", "-"),
1320         );
1321         t!(fs::create_dir_all(&dir));
1322         config.out = dir;
1323         config.build = INTERNER.intern_str("A");
1324         config.hosts = vec![config.build]
1325             .clone()
1326             .into_iter()
1327             .chain(host.iter().map(|s| INTERNER.intern_str(s)))
1328             .collect::<Vec<_>>();
1329         config.targets = config
1330             .hosts
1331             .clone()
1332             .into_iter()
1333             .chain(target.iter().map(|s| INTERNER.intern_str(s)))
1334             .collect::<Vec<_>>();
1335         config
1336     }
1337
1338     fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
1339         v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
1340     }
1341
1342     #[test]
1343     fn dist_baseline() {
1344         let build = Build::new(configure(&[], &[]));
1345         let mut builder = Builder::new(&build);
1346         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1347
1348         let a = INTERNER.intern_str("A");
1349
1350         assert_eq!(
1351             first(builder.cache.all::<dist::Docs>()),
1352             &[dist::Docs { stage: 2, host: a },]
1353         );
1354         assert_eq!(
1355             first(builder.cache.all::<dist::Mingw>()),
1356             &[dist::Mingw { host: a },]
1357         );
1358         assert_eq!(
1359             first(builder.cache.all::<dist::Rustc>()),
1360             &[dist::Rustc {
1361                 compiler: Compiler { host: a, stage: 2 }
1362             },]
1363         );
1364         assert_eq!(
1365             first(builder.cache.all::<dist::Std>()),
1366             &[dist::Std {
1367                 compiler: Compiler { host: a, stage: 2 },
1368                 target: a,
1369             },]
1370         );
1371         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1372     }
1373
1374     #[test]
1375     fn dist_with_targets() {
1376         let build = Build::new(configure(&[], &["B"]));
1377         let mut builder = Builder::new(&build);
1378         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1379
1380         let a = INTERNER.intern_str("A");
1381         let b = INTERNER.intern_str("B");
1382
1383         assert_eq!(
1384             first(builder.cache.all::<dist::Docs>()),
1385             &[
1386                 dist::Docs { stage: 2, host: a },
1387                 dist::Docs { stage: 2, host: b },
1388             ]
1389         );
1390         assert_eq!(
1391             first(builder.cache.all::<dist::Mingw>()),
1392             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1393         );
1394         assert_eq!(
1395             first(builder.cache.all::<dist::Rustc>()),
1396             &[dist::Rustc {
1397                 compiler: Compiler { host: a, stage: 2 }
1398             },]
1399         );
1400         assert_eq!(
1401             first(builder.cache.all::<dist::Std>()),
1402             &[
1403                 dist::Std {
1404                     compiler: Compiler { host: a, stage: 2 },
1405                     target: a,
1406                 },
1407                 dist::Std {
1408                     compiler: Compiler { host: a, stage: 2 },
1409                     target: b,
1410                 },
1411             ]
1412         );
1413         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1414     }
1415
1416     #[test]
1417     fn dist_with_hosts() {
1418         let build = Build::new(configure(&["B"], &[]));
1419         let mut builder = Builder::new(&build);
1420         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1421
1422         let a = INTERNER.intern_str("A");
1423         let b = INTERNER.intern_str("B");
1424
1425         assert_eq!(
1426             first(builder.cache.all::<dist::Docs>()),
1427             &[
1428                 dist::Docs { stage: 2, host: a },
1429                 dist::Docs { stage: 2, host: b },
1430             ]
1431         );
1432         assert_eq!(
1433             first(builder.cache.all::<dist::Mingw>()),
1434             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1435         );
1436         assert_eq!(
1437             first(builder.cache.all::<dist::Rustc>()),
1438             &[
1439                 dist::Rustc {
1440                     compiler: Compiler { host: a, stage: 2 }
1441                 },
1442                 dist::Rustc {
1443                     compiler: Compiler { host: b, stage: 2 }
1444                 },
1445             ]
1446         );
1447         assert_eq!(
1448             first(builder.cache.all::<dist::Std>()),
1449             &[
1450                 dist::Std {
1451                     compiler: Compiler { host: a, stage: 2 },
1452                     target: a,
1453                 },
1454                 dist::Std {
1455                     compiler: Compiler { host: a, stage: 2 },
1456                     target: b,
1457                 },
1458             ]
1459         );
1460         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1461     }
1462
1463     #[test]
1464     fn dist_with_targets_and_hosts() {
1465         let build = Build::new(configure(&["B"], &["C"]));
1466         let mut builder = Builder::new(&build);
1467         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1468
1469         let a = INTERNER.intern_str("A");
1470         let b = INTERNER.intern_str("B");
1471         let c = INTERNER.intern_str("C");
1472
1473         assert_eq!(
1474             first(builder.cache.all::<dist::Docs>()),
1475             &[
1476                 dist::Docs { stage: 2, host: a },
1477                 dist::Docs { stage: 2, host: b },
1478                 dist::Docs { stage: 2, host: c },
1479             ]
1480         );
1481         assert_eq!(
1482             first(builder.cache.all::<dist::Mingw>()),
1483             &[
1484                 dist::Mingw { host: a },
1485                 dist::Mingw { host: b },
1486                 dist::Mingw { host: c },
1487             ]
1488         );
1489         assert_eq!(
1490             first(builder.cache.all::<dist::Rustc>()),
1491             &[
1492                 dist::Rustc {
1493                     compiler: Compiler { host: a, stage: 2 }
1494                 },
1495                 dist::Rustc {
1496                     compiler: Compiler { host: b, stage: 2 }
1497                 },
1498             ]
1499         );
1500         assert_eq!(
1501             first(builder.cache.all::<dist::Std>()),
1502             &[
1503                 dist::Std {
1504                     compiler: Compiler { host: a, stage: 2 },
1505                     target: a,
1506                 },
1507                 dist::Std {
1508                     compiler: Compiler { host: a, stage: 2 },
1509                     target: b,
1510                 },
1511                 dist::Std {
1512                     compiler: Compiler { host: a, stage: 2 },
1513                     target: c,
1514                 },
1515             ]
1516         );
1517         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1518     }
1519
1520     #[test]
1521     fn dist_with_target_flag() {
1522         let mut config = configure(&["B"], &["C"]);
1523         config.run_host_only = false; // as-if --target=C was passed
1524         let build = Build::new(config);
1525         let mut builder = Builder::new(&build);
1526         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1527
1528         let a = INTERNER.intern_str("A");
1529         let b = INTERNER.intern_str("B");
1530         let c = INTERNER.intern_str("C");
1531
1532         assert_eq!(
1533             first(builder.cache.all::<dist::Docs>()),
1534             &[
1535                 dist::Docs { stage: 2, host: a },
1536                 dist::Docs { stage: 2, host: b },
1537                 dist::Docs { stage: 2, host: c },
1538             ]
1539         );
1540         assert_eq!(
1541             first(builder.cache.all::<dist::Mingw>()),
1542             &[
1543                 dist::Mingw { host: a },
1544                 dist::Mingw { host: b },
1545                 dist::Mingw { host: c },
1546             ]
1547         );
1548         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1549         assert_eq!(
1550             first(builder.cache.all::<dist::Std>()),
1551             &[
1552                 dist::Std {
1553                     compiler: Compiler { host: a, stage: 2 },
1554                     target: a,
1555                 },
1556                 dist::Std {
1557                     compiler: Compiler { host: a, stage: 2 },
1558                     target: b,
1559                 },
1560                 dist::Std {
1561                     compiler: Compiler { host: a, stage: 2 },
1562                     target: c,
1563                 },
1564             ]
1565         );
1566         assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1567     }
1568
1569     #[test]
1570     fn dist_with_same_targets_and_hosts() {
1571         let build = Build::new(configure(&["B"], &["B"]));
1572         let mut builder = Builder::new(&build);
1573         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1574
1575         let a = INTERNER.intern_str("A");
1576         let b = INTERNER.intern_str("B");
1577
1578         assert_eq!(
1579             first(builder.cache.all::<dist::Docs>()),
1580             &[
1581                 dist::Docs { stage: 2, host: a },
1582                 dist::Docs { stage: 2, host: b },
1583             ]
1584         );
1585         assert_eq!(
1586             first(builder.cache.all::<dist::Mingw>()),
1587             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1588         );
1589         assert_eq!(
1590             first(builder.cache.all::<dist::Rustc>()),
1591             &[
1592                 dist::Rustc {
1593                     compiler: Compiler { host: a, stage: 2 }
1594                 },
1595                 dist::Rustc {
1596                     compiler: Compiler { host: b, stage: 2 }
1597                 },
1598             ]
1599         );
1600         assert_eq!(
1601             first(builder.cache.all::<dist::Std>()),
1602             &[
1603                 dist::Std {
1604                     compiler: Compiler { host: a, stage: 2 },
1605                     target: a,
1606                 },
1607                 dist::Std {
1608                     compiler: Compiler { host: a, stage: 2 },
1609                     target: b,
1610                 },
1611             ]
1612         );
1613         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1614         assert_eq!(
1615             first(builder.cache.all::<compile::Std>()),
1616             &[
1617                 compile::Std {
1618                     compiler: Compiler { host: a, stage: 0 },
1619                     target: a,
1620                 },
1621                 compile::Std {
1622                     compiler: Compiler { host: a, stage: 1 },
1623                     target: a,
1624                 },
1625                 compile::Std {
1626                     compiler: Compiler { host: a, stage: 2 },
1627                     target: a,
1628                 },
1629                 compile::Std {
1630                     compiler: Compiler { host: a, stage: 1 },
1631                     target: b,
1632                 },
1633                 compile::Std {
1634                     compiler: Compiler { host: a, stage: 2 },
1635                     target: b,
1636                 },
1637             ]
1638         );
1639         assert_eq!(
1640             first(builder.cache.all::<compile::Test>()),
1641             &[
1642                 compile::Test {
1643                     compiler: Compiler { host: a, stage: 0 },
1644                     target: a,
1645                 },
1646                 compile::Test {
1647                     compiler: Compiler { host: a, stage: 1 },
1648                     target: a,
1649                 },
1650                 compile::Test {
1651                     compiler: Compiler { host: a, stage: 2 },
1652                     target: a,
1653                 },
1654                 compile::Test {
1655                     compiler: Compiler { host: a, stage: 1 },
1656                     target: b,
1657                 },
1658                 compile::Test {
1659                     compiler: Compiler { host: a, stage: 2 },
1660                     target: b,
1661                 },
1662             ]
1663         );
1664         assert_eq!(
1665             first(builder.cache.all::<compile::Assemble>()),
1666             &[
1667                 compile::Assemble {
1668                     target_compiler: Compiler { host: a, stage: 0 },
1669                 },
1670                 compile::Assemble {
1671                     target_compiler: Compiler { host: a, stage: 1 },
1672                 },
1673                 compile::Assemble {
1674                     target_compiler: Compiler { host: a, stage: 2 },
1675                 },
1676                 compile::Assemble {
1677                     target_compiler: Compiler { host: b, stage: 2 },
1678                 },
1679             ]
1680         );
1681     }
1682
1683     #[test]
1684     fn build_default() {
1685         let build = Build::new(configure(&["B"], &["C"]));
1686         let mut builder = Builder::new(&build);
1687         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1688
1689         let a = INTERNER.intern_str("A");
1690         let b = INTERNER.intern_str("B");
1691         let c = INTERNER.intern_str("C");
1692
1693         assert!(!builder.cache.all::<compile::Std>().is_empty());
1694         assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1695         assert_eq!(
1696             first(builder.cache.all::<compile::Rustc>()),
1697             &[
1698                 compile::Rustc {
1699                     compiler: Compiler { host: a, stage: 0 },
1700                     target: a,
1701                 },
1702                 compile::Rustc {
1703                     compiler: Compiler { host: a, stage: 1 },
1704                     target: a,
1705                 },
1706                 compile::Rustc {
1707                     compiler: Compiler { host: a, stage: 2 },
1708                     target: a,
1709                 },
1710                 compile::Rustc {
1711                     compiler: Compiler { host: b, stage: 2 },
1712                     target: a,
1713                 },
1714                 compile::Rustc {
1715                     compiler: Compiler { host: a, stage: 0 },
1716                     target: b,
1717                 },
1718                 compile::Rustc {
1719                     compiler: Compiler { host: a, stage: 1 },
1720                     target: b,
1721                 },
1722                 compile::Rustc {
1723                     compiler: Compiler { host: a, stage: 2 },
1724                     target: b,
1725                 },
1726                 compile::Rustc {
1727                     compiler: Compiler { host: b, stage: 2 },
1728                     target: b,
1729                 },
1730             ]
1731         );
1732
1733         assert_eq!(
1734             first(builder.cache.all::<compile::Test>()),
1735             &[
1736                 compile::Test {
1737                     compiler: Compiler { host: a, stage: 0 },
1738                     target: a,
1739                 },
1740                 compile::Test {
1741                     compiler: Compiler { host: a, stage: 1 },
1742                     target: a,
1743                 },
1744                 compile::Test {
1745                     compiler: Compiler { host: a, stage: 2 },
1746                     target: a,
1747                 },
1748                 compile::Test {
1749                     compiler: Compiler { host: b, stage: 2 },
1750                     target: a,
1751                 },
1752                 compile::Test {
1753                     compiler: Compiler { host: a, stage: 0 },
1754                     target: b,
1755                 },
1756                 compile::Test {
1757                     compiler: Compiler { host: a, stage: 1 },
1758                     target: b,
1759                 },
1760                 compile::Test {
1761                     compiler: Compiler { host: a, stage: 2 },
1762                     target: b,
1763                 },
1764                 compile::Test {
1765                     compiler: Compiler { host: b, stage: 2 },
1766                     target: b,
1767                 },
1768                 compile::Test {
1769                     compiler: Compiler { host: a, stage: 2 },
1770                     target: c,
1771                 },
1772                 compile::Test {
1773                     compiler: Compiler { host: b, stage: 2 },
1774                     target: c,
1775                 },
1776             ]
1777         );
1778     }
1779
1780     #[test]
1781     fn build_with_target_flag() {
1782         let mut config = configure(&["B"], &["C"]);
1783         config.run_host_only = false;
1784         let build = Build::new(config);
1785         let mut builder = Builder::new(&build);
1786         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1787
1788         let a = INTERNER.intern_str("A");
1789         let b = INTERNER.intern_str("B");
1790         let c = INTERNER.intern_str("C");
1791
1792         assert!(!builder.cache.all::<compile::Std>().is_empty());
1793         assert_eq!(
1794             first(builder.cache.all::<compile::Assemble>()),
1795             &[
1796                 compile::Assemble {
1797                     target_compiler: Compiler { host: a, stage: 0 },
1798                 },
1799                 compile::Assemble {
1800                     target_compiler: Compiler { host: a, stage: 1 },
1801                 },
1802                 compile::Assemble {
1803                     target_compiler: Compiler { host: b, stage: 1 },
1804                 },
1805                 compile::Assemble {
1806                     target_compiler: Compiler { host: a, stage: 2 },
1807                 },
1808                 compile::Assemble {
1809                     target_compiler: Compiler { host: b, stage: 2 },
1810                 },
1811             ]
1812         );
1813         assert_eq!(
1814             first(builder.cache.all::<compile::Rustc>()),
1815             &[
1816                 compile::Rustc {
1817                     compiler: Compiler { host: a, stage: 0 },
1818                     target: a,
1819                 },
1820                 compile::Rustc {
1821                     compiler: Compiler { host: a, stage: 1 },
1822                     target: a,
1823                 },
1824                 compile::Rustc {
1825                     compiler: Compiler { host: a, stage: 0 },
1826                     target: b,
1827                 },
1828                 compile::Rustc {
1829                     compiler: Compiler { host: a, stage: 1 },
1830                     target: b,
1831                 },
1832             ]
1833         );
1834
1835         assert_eq!(
1836             first(builder.cache.all::<compile::Test>()),
1837             &[
1838                 compile::Test {
1839                     compiler: Compiler { host: a, stage: 0 },
1840                     target: a,
1841                 },
1842                 compile::Test {
1843                     compiler: Compiler { host: a, stage: 1 },
1844                     target: a,
1845                 },
1846                 compile::Test {
1847                     compiler: Compiler { host: a, stage: 2 },
1848                     target: a,
1849                 },
1850                 compile::Test {
1851                     compiler: Compiler { host: b, stage: 2 },
1852                     target: a,
1853                 },
1854                 compile::Test {
1855                     compiler: Compiler { host: a, stage: 0 },
1856                     target: b,
1857                 },
1858                 compile::Test {
1859                     compiler: Compiler { host: a, stage: 1 },
1860                     target: b,
1861                 },
1862                 compile::Test {
1863                     compiler: Compiler { host: a, stage: 2 },
1864                     target: b,
1865                 },
1866                 compile::Test {
1867                     compiler: Compiler { host: b, stage: 2 },
1868                     target: b,
1869                 },
1870                 compile::Test {
1871                     compiler: Compiler { host: a, stage: 2 },
1872                     target: c,
1873                 },
1874                 compile::Test {
1875                     compiler: Compiler { host: b, stage: 2 },
1876                     target: c,
1877                 },
1878             ]
1879         );
1880     }
1881
1882     #[test]
1883     fn test_with_no_doc_stage0() {
1884         let mut config = configure(&[], &[]);
1885         config.stage = Some(0);
1886         config.cmd = Subcommand::Test {
1887             paths: vec!["src/libstd".into()],
1888             test_args: vec![],
1889             rustc_args: vec![],
1890             fail_fast: true,
1891             doc_tests: DocTests::No,
1892             bless: false,
1893             compare_mode: None,
1894             rustfix_coverage: false,
1895         };
1896
1897         let build = Build::new(config);
1898         let mut builder = Builder::new(&build);
1899
1900         let host = INTERNER.intern_str("A");
1901
1902         builder.run_step_descriptions(
1903             &[StepDescription::from::<test::Crate>()],
1904             &["src/libstd".into()],
1905         );
1906
1907         // Ensure we don't build any compiler artifacts.
1908         assert!(!builder.cache.contains::<compile::Rustc>());
1909         assert_eq!(
1910             first(builder.cache.all::<test::Crate>()),
1911             &[test::Crate {
1912                 compiler: Compiler { host, stage: 0 },
1913                 target: host,
1914                 mode: Mode::Std,
1915                 test_kind: test::TestKind::Test,
1916                 krate: INTERNER.intern_str("std"),
1917             },]
1918         );
1919     }
1920
1921     #[test]
1922     fn test_exclude() {
1923         let mut config = configure(&[], &[]);
1924         config.exclude = vec![
1925             "src/test/run-pass".into(),
1926             "src/tools/tidy".into(),
1927         ];
1928         config.cmd = Subcommand::Test {
1929             paths: Vec::new(),
1930             test_args: Vec::new(),
1931             rustc_args: Vec::new(),
1932             fail_fast: true,
1933             doc_tests: DocTests::No,
1934             bless: false,
1935             compare_mode: None,
1936             rustfix_coverage: false,
1937         };
1938
1939         let build = Build::new(config);
1940         let builder = Builder::new(&build);
1941         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Test), &[]);
1942
1943         // Ensure we have really excluded run-pass & tidy
1944         assert!(!builder.cache.contains::<test::RunPass>());
1945         assert!(!builder.cache.contains::<test::Tidy>());
1946
1947         // Ensure other tests are not affected.
1948         assert!(builder.cache.contains::<test::RunPassFullDeps>());
1949         assert!(builder.cache.contains::<test::RustdocUi>());
1950     }
1951 }