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