]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Allow a dirty MirBuilt for make_extern and make_method_extern
[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     /// Build 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::Rustfmt,
404                 test::Miri,
405                 test::Clippy,
406                 test::CompiletestTest,
407                 test::RustdocJS,
408                 test::RustdocTheme,
409                 // Run bootstrap close to the end as it's unlikely to fail
410                 test::Bootstrap,
411                 // Run run-make last, since these won't pass without make on Windows
412                 test::RunMake,
413                 test::RustdocUi
414             ),
415             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
416             Kind::Doc => describe!(
417                 doc::UnstableBook,
418                 doc::UnstableBookGen,
419                 doc::TheBook,
420                 doc::Standalone,
421                 doc::Std,
422                 doc::Test,
423                 doc::WhitelistedRustc,
424                 doc::Rustc,
425                 doc::Rustdoc,
426                 doc::ErrorIndex,
427                 doc::Nomicon,
428                 doc::Reference,
429                 doc::RustdocBook,
430                 doc::RustByExample,
431                 doc::RustcBook,
432                 doc::CargoBook,
433                 doc::EmbeddedBook,
434                 doc::EditionGuide,
435             ),
436             Kind::Dist => describe!(
437                 dist::Docs,
438                 dist::RustcDocs,
439                 dist::Mingw,
440                 dist::Rustc,
441                 dist::DebuggerScripts,
442                 dist::Std,
443                 dist::Analysis,
444                 dist::Src,
445                 dist::PlainSourceTarball,
446                 dist::Cargo,
447                 dist::Rls,
448                 dist::Rustfmt,
449                 dist::Clippy,
450                 dist::Miri,
451                 dist::LlvmTools,
452                 dist::Lldb,
453                 dist::Extended,
454                 dist::HashSign
455             ),
456             Kind::Install => describe!(
457                 install::Docs,
458                 install::Std,
459                 install::Cargo,
460                 install::Rls,
461                 install::Rustfmt,
462                 install::Clippy,
463                 install::Miri,
464                 install::Analysis,
465                 install::Src,
466                 install::Rustc
467             ),
468         }
469     }
470
471     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
472         let kind = match subcommand {
473             "build" => Kind::Build,
474             "doc" => Kind::Doc,
475             "test" => Kind::Test,
476             "bench" => Kind::Bench,
477             "dist" => Kind::Dist,
478             "install" => Kind::Install,
479             _ => return None,
480         };
481
482         let builder = Builder {
483             build,
484             top_stage: build.config.stage.unwrap_or(2),
485             kind,
486             cache: Cache::new(),
487             stack: RefCell::new(Vec::new()),
488             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
489             paths: vec![],
490             graph_nodes: RefCell::new(HashMap::new()),
491             graph: RefCell::new(Graph::new()),
492             parent: Cell::new(None),
493         };
494
495         let builder = &builder;
496         let mut should_run = ShouldRun::new(builder);
497         for desc in Builder::get_step_descriptions(builder.kind) {
498             should_run = (desc.should_run)(should_run);
499         }
500         let mut help = String::from("Available paths:\n");
501         for pathset in should_run.paths {
502             if let PathSet::Set(set) = pathset {
503                 set.iter().for_each(|path| {
504                     help.push_str(
505                         format!("    ./x.py {} {}\n", subcommand, path.display()).as_str(),
506                     )
507                 })
508             }
509         }
510         Some(help)
511     }
512
513     pub fn new(build: &Build) -> Builder {
514         let (kind, paths) = match build.config.cmd {
515             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
516             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
517             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
518             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
519             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
520             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
521             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
522             Subcommand::Clean { .. } => panic!(),
523         };
524
525         let builder = Builder {
526             build,
527             top_stage: build.config.stage.unwrap_or(2),
528             kind,
529             cache: Cache::new(),
530             stack: RefCell::new(Vec::new()),
531             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
532             paths: paths.to_owned(),
533             graph_nodes: RefCell::new(HashMap::new()),
534             graph: RefCell::new(Graph::new()),
535             parent: Cell::new(None),
536         };
537
538         if kind == Kind::Dist {
539             assert!(
540                 !builder.config.test_miri,
541                 "Do not distribute with miri enabled.\n\
542                 The distributed libraries would include all MIR (increasing binary size).
543                 The distributed MIR would include validation statements."
544             );
545         }
546
547         builder
548     }
549
550     pub fn execute_cli(&self) -> Graph<String, bool> {
551         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
552         self.graph.borrow().clone()
553     }
554
555     pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
556         let paths = paths.unwrap_or(&[]);
557         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
558     }
559
560     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
561         StepDescription::run(v, self, paths);
562     }
563
564     /// Obtain a compiler at a given stage and for a given host. Explicitly does
565     /// not take `Compiler` since all `Compiler` instances are meant to be
566     /// obtained through this function, since it ensures that they are valid
567     /// (i.e., built and assembled).
568     pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
569         self.ensure(compile::Assemble {
570             target_compiler: Compiler { stage, host },
571         })
572     }
573
574     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
575         self.ensure(compile::Sysroot { compiler })
576     }
577
578     /// Returns the libdir where the standard library and other artifacts are
579     /// found for a compiler's sysroot.
580     pub fn sysroot_libdir(
581         &self,
582         compiler: Compiler,
583         target: Interned<String>,
584     ) -> Interned<PathBuf> {
585         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
586         struct Libdir {
587             compiler: Compiler,
588             target: Interned<String>,
589         }
590         impl Step for Libdir {
591             type Output = Interned<PathBuf>;
592
593             fn should_run(run: ShouldRun) -> ShouldRun {
594                 run.never()
595             }
596
597             fn run(self, builder: &Builder) -> Interned<PathBuf> {
598                 let compiler = self.compiler;
599                 let config = &builder.build.config;
600                 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
601                     builder.build.config.libdir_relative().unwrap()
602                 } else {
603                     Path::new("lib")
604                 };
605                 let sysroot = builder
606                     .sysroot(self.compiler)
607                     .join(lib)
608                     .join("rustlib")
609                     .join(self.target)
610                     .join("lib");
611                 let _ = fs::remove_dir_all(&sysroot);
612                 t!(fs::create_dir_all(&sysroot));
613                 INTERNER.intern_path(sysroot)
614             }
615         }
616         self.ensure(Libdir { compiler, target })
617     }
618
619     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
620         self.sysroot_libdir(compiler, compiler.host)
621             .with_file_name(self.config.rust_codegen_backends_dir.clone())
622     }
623
624     /// Returns the compiler's libdir where it stores the dynamic libraries that
625     /// it itself links against.
626     ///
627     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
628     /// Windows.
629     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
630         if compiler.is_snapshot(self) {
631             self.rustc_snapshot_libdir()
632         } else {
633             self.sysroot(compiler).join(libdir(&compiler.host))
634         }
635     }
636
637     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
638     /// library lookup path.
639     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
640         // Windows doesn't need dylib path munging because the dlls for the
641         // compiler live next to the compiler and the system will find them
642         // automatically.
643         if cfg!(windows) {
644             return;
645         }
646
647         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
648     }
649
650     /// Get a path to the compiler specified.
651     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
652         if compiler.is_snapshot(self) {
653             self.initial_rustc.clone()
654         } else {
655             self.sysroot(compiler)
656                 .join("bin")
657                 .join(exe("rustc", &compiler.host))
658         }
659     }
660
661     /// Get the paths to all of the compiler's codegen backends.
662     fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
663         fs::read_dir(self.sysroot_codegen_backends(compiler))
664             .into_iter()
665             .flatten()
666             .filter_map(Result::ok)
667             .map(|entry| entry.path())
668     }
669
670     pub fn rustdoc(&self, host: Interned<String>) -> PathBuf {
671         self.ensure(tool::Rustdoc { host })
672     }
673
674     pub fn rustdoc_cmd(&self, host: Interned<String>) -> Command {
675         let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
676         let compiler = self.compiler(self.top_stage, host);
677         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
678             .env("RUSTC_SYSROOT", self.sysroot(compiler))
679             .env(
680                 "RUSTDOC_LIBDIR",
681                 self.sysroot_libdir(compiler, self.config.build),
682             )
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 = sysroot.join(libdir(&compiler.host));
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.sysroot_libdir(compiler, self.config.build));
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         // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful.
1022         if self.config.deny_warnings && !(mode == Mode::Std && stage == 0) {
1023             cargo.env("RUSTC_DENY_WARNINGS", "1");
1024         }
1025
1026         // Throughout the build Cargo can execute a number of build scripts
1027         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1028         // obtained previously to those build scripts.
1029         // Build scripts use either the `cc` crate or `configure/make` so we pass
1030         // the options through environment variables that are fetched and understood by both.
1031         //
1032         // FIXME: the guard against msvc shouldn't need to be here
1033         if target.contains("msvc") {
1034             if let Some(ref cl) = self.config.llvm_clang_cl {
1035                 cargo.env("CC", cl).env("CXX", cl);
1036             }
1037         } else {
1038             let ccache = self.config.ccache.as_ref();
1039             let ccacheify = |s: &Path| {
1040                 let ccache = match ccache {
1041                     Some(ref s) => s,
1042                     None => return s.display().to_string(),
1043                 };
1044                 // FIXME: the cc-rs crate only recognizes the literal strings
1045                 // `ccache` and `sccache` when doing caching compilations, so we
1046                 // mirror that here. It should probably be fixed upstream to
1047                 // accept a new env var or otherwise work with custom ccache
1048                 // vars.
1049                 match &ccache[..] {
1050                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1051                     _ => s.display().to_string(),
1052                 }
1053             };
1054             let cc = ccacheify(&self.cc(target));
1055             cargo.env(format!("CC_{}", target), &cc);
1056
1057             let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1058             cargo
1059                 .env(format!("CFLAGS_{}", target), cflags.clone());
1060
1061             if let Some(ar) = self.ar(target) {
1062                 let ranlib = format!("{} s", ar.display());
1063                 cargo
1064                     .env(format!("AR_{}", target), ar)
1065                     .env(format!("RANLIB_{}", target), ranlib);
1066             }
1067
1068             if let Ok(cxx) = self.cxx(target) {
1069                 let cxx = ccacheify(&cxx);
1070                 cargo
1071                     .env(format!("CXX_{}", target), &cxx)
1072                     .env(format!("CXXFLAGS_{}", target), cflags);
1073             }
1074         }
1075
1076         if (cmd == "build" || cmd == "rustc")
1077             && mode == Mode::Std
1078             && self.config.extended
1079             && compiler.is_final_stage(self)
1080         {
1081             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
1082         }
1083
1084         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1085         cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1086
1087         // Environment variables *required* throughout the build
1088         //
1089         // FIXME: should update code to not require this env var
1090         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1091
1092         // Set this for all builds to make sure doc builds also get it.
1093         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1094
1095         // This one's a bit tricky. As of the time of this writing the compiler
1096         // links to the `winapi` crate on crates.io. This crate provides raw
1097         // bindings to Windows system functions, sort of like libc does for
1098         // Unix. This crate also, however, provides "import libraries" for the
1099         // MinGW targets. There's an import library per dll in the windows
1100         // distribution which is what's linked to. These custom import libraries
1101         // are used because the winapi crate can reference Windows functions not
1102         // present in the MinGW import libraries.
1103         //
1104         // For example MinGW may ship libdbghelp.a, but it may not have
1105         // references to all the functions in the dbghelp dll. Instead the
1106         // custom import library for dbghelp in the winapi crates has all this
1107         // information.
1108         //
1109         // Unfortunately for us though the import libraries are linked by
1110         // default via `-ldylib=winapi_foo`. That is, they're linked with the
1111         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1112         // conflict with the system MinGW ones). This consequently means that
1113         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1114         // DLL) when linked against *again*, for example with procedural macros
1115         // or plugins, will trigger the propagation logic of `-ldylib`, passing
1116         // `-lwinapi_foo` to the linker again. This isn't actually available in
1117         // our distribution, however, so the link fails.
1118         //
1119         // To solve this problem we tell winapi to not use its bundled import
1120         // libraries. This means that it will link to the system MinGW import
1121         // libraries by default, and the `-ldylib=foo` directives will still get
1122         // passed to the final linker, but they'll look like `-lfoo` which can
1123         // be resolved because MinGW has the import library. The downside is we
1124         // don't get newer functions from Windows, but we don't use any of them
1125         // anyway.
1126         if !mode.is_tool() {
1127             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1128         }
1129
1130         for _ in 1..self.verbosity {
1131             cargo.arg("-v");
1132         }
1133
1134         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1135             (Mode::Std, Some(n), _) |
1136             (Mode::Test, Some(n), _) |
1137             (_, _, Some(n)) => {
1138                 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
1139             }
1140             _ => {
1141                 // Don't set anything
1142             }
1143         }
1144
1145         if self.config.rust_optimize {
1146             // FIXME: cargo bench/install do not accept `--release`
1147             if cmd != "bench" && cmd != "install" {
1148                 cargo.arg("--release");
1149             }
1150         }
1151
1152         if self.config.locked_deps {
1153             cargo.arg("--locked");
1154         }
1155         if self.config.vendor || self.is_sudo {
1156             cargo.arg("--frozen");
1157         }
1158
1159         self.ci_env.force_coloring_in_ci(&mut cargo);
1160
1161         cargo
1162     }
1163
1164     /// Ensure that a given step is built, returning its output. This will
1165     /// cache the step, so it is safe (and good!) to call this as often as
1166     /// needed to ensure that all dependencies are built.
1167     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1168         {
1169             let mut stack = self.stack.borrow_mut();
1170             for stack_step in stack.iter() {
1171                 // should skip
1172                 if stack_step
1173                     .downcast_ref::<S>()
1174                     .map_or(true, |stack_step| *stack_step != step)
1175                 {
1176                     continue;
1177                 }
1178                 let mut out = String::new();
1179                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1180                 for el in stack.iter().rev() {
1181                     out += &format!("\t{:?}\n", el);
1182                 }
1183                 panic!(out);
1184             }
1185             if let Some(out) = self.cache.get(&step) {
1186                 self.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
1187
1188                 {
1189                     let mut graph = self.graph.borrow_mut();
1190                     let parent = self.parent.get();
1191                     let us = *self
1192                         .graph_nodes
1193                         .borrow_mut()
1194                         .entry(format!("{:?}", step))
1195                         .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1196                     if let Some(parent) = parent {
1197                         graph.add_edge(parent, us, false);
1198                     }
1199                 }
1200
1201                 return out;
1202             }
1203             self.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
1204             stack.push(Box::new(step.clone()));
1205         }
1206
1207         let prev_parent = self.parent.get();
1208
1209         {
1210             let mut graph = self.graph.borrow_mut();
1211             let parent = self.parent.get();
1212             let us = *self
1213                 .graph_nodes
1214                 .borrow_mut()
1215                 .entry(format!("{:?}", step))
1216                 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1217             self.parent.set(Some(us));
1218             if let Some(parent) = parent {
1219                 graph.add_edge(parent, us, true);
1220             }
1221         }
1222
1223         let (out, dur) = {
1224             let start = Instant::now();
1225             let zero = Duration::new(0, 0);
1226             let parent = self.time_spent_on_dependencies.replace(zero);
1227             let out = step.clone().run(self);
1228             let dur = start.elapsed();
1229             let deps = self.time_spent_on_dependencies.replace(parent + dur);
1230             (out, dur - deps)
1231         };
1232
1233         self.parent.set(prev_parent);
1234
1235         if self.config.print_step_timings && dur > Duration::from_millis(100) {
1236             println!(
1237                 "[TIMING] {:?} -- {}.{:03}",
1238                 step,
1239                 dur.as_secs(),
1240                 dur.subsec_nanos() / 1_000_000
1241             );
1242         }
1243
1244         {
1245             let mut stack = self.stack.borrow_mut();
1246             let cur_step = stack.pop().expect("step stack empty");
1247             assert_eq!(cur_step.downcast_ref(), Some(&step));
1248         }
1249         self.verbose(&format!(
1250             "{}< {:?}",
1251             "  ".repeat(self.stack.borrow().len()),
1252             step
1253         ));
1254         self.cache.put(step, out.clone());
1255         out
1256     }
1257 }
1258
1259 #[cfg(test)]
1260 mod __test {
1261     use super::*;
1262     use crate::config::Config;
1263     use std::thread;
1264
1265     fn configure(host: &[&str], target: &[&str]) -> Config {
1266         let mut config = Config::default_opts();
1267         // don't save toolstates
1268         config.save_toolstates = None;
1269         config.run_host_only = true;
1270         config.dry_run = true;
1271         // try to avoid spurious failures in dist where we create/delete each others file
1272         let dir = config.out.join("tmp-rustbuild-tests").join(
1273             &thread::current()
1274                 .name()
1275                 .unwrap_or("unknown")
1276                 .replace(":", "-"),
1277         );
1278         t!(fs::create_dir_all(&dir));
1279         config.out = dir;
1280         config.build = INTERNER.intern_str("A");
1281         config.hosts = vec![config.build]
1282             .clone()
1283             .into_iter()
1284             .chain(host.iter().map(|s| INTERNER.intern_str(s)))
1285             .collect::<Vec<_>>();
1286         config.targets = config
1287             .hosts
1288             .clone()
1289             .into_iter()
1290             .chain(target.iter().map(|s| INTERNER.intern_str(s)))
1291             .collect::<Vec<_>>();
1292         config
1293     }
1294
1295     fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
1296         v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
1297     }
1298
1299     #[test]
1300     fn dist_baseline() {
1301         let build = Build::new(configure(&[], &[]));
1302         let mut builder = Builder::new(&build);
1303         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1304
1305         let a = INTERNER.intern_str("A");
1306
1307         assert_eq!(
1308             first(builder.cache.all::<dist::Docs>()),
1309             &[dist::Docs { stage: 2, host: a },]
1310         );
1311         assert_eq!(
1312             first(builder.cache.all::<dist::Mingw>()),
1313             &[dist::Mingw { host: a },]
1314         );
1315         assert_eq!(
1316             first(builder.cache.all::<dist::Rustc>()),
1317             &[dist::Rustc {
1318                 compiler: Compiler { host: a, stage: 2 }
1319             },]
1320         );
1321         assert_eq!(
1322             first(builder.cache.all::<dist::Std>()),
1323             &[dist::Std {
1324                 compiler: Compiler { host: a, stage: 2 },
1325                 target: a,
1326             },]
1327         );
1328         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1329     }
1330
1331     #[test]
1332     fn dist_with_targets() {
1333         let build = Build::new(configure(&[], &["B"]));
1334         let mut builder = Builder::new(&build);
1335         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1336
1337         let a = INTERNER.intern_str("A");
1338         let b = INTERNER.intern_str("B");
1339
1340         assert_eq!(
1341             first(builder.cache.all::<dist::Docs>()),
1342             &[
1343                 dist::Docs { stage: 2, host: a },
1344                 dist::Docs { stage: 2, host: b },
1345             ]
1346         );
1347         assert_eq!(
1348             first(builder.cache.all::<dist::Mingw>()),
1349             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1350         );
1351         assert_eq!(
1352             first(builder.cache.all::<dist::Rustc>()),
1353             &[dist::Rustc {
1354                 compiler: Compiler { host: a, stage: 2 }
1355             },]
1356         );
1357         assert_eq!(
1358             first(builder.cache.all::<dist::Std>()),
1359             &[
1360                 dist::Std {
1361                     compiler: Compiler { host: a, stage: 2 },
1362                     target: a,
1363                 },
1364                 dist::Std {
1365                     compiler: Compiler { host: a, stage: 2 },
1366                     target: b,
1367                 },
1368             ]
1369         );
1370         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1371     }
1372
1373     #[test]
1374     fn dist_with_hosts() {
1375         let build = Build::new(configure(&["B"], &[]));
1376         let mut builder = Builder::new(&build);
1377         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1378
1379         let a = INTERNER.intern_str("A");
1380         let b = INTERNER.intern_str("B");
1381
1382         assert_eq!(
1383             first(builder.cache.all::<dist::Docs>()),
1384             &[
1385                 dist::Docs { stage: 2, host: a },
1386                 dist::Docs { stage: 2, host: b },
1387             ]
1388         );
1389         assert_eq!(
1390             first(builder.cache.all::<dist::Mingw>()),
1391             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1392         );
1393         assert_eq!(
1394             first(builder.cache.all::<dist::Rustc>()),
1395             &[
1396                 dist::Rustc {
1397                     compiler: Compiler { host: a, stage: 2 }
1398                 },
1399                 dist::Rustc {
1400                     compiler: Compiler { host: b, stage: 2 }
1401                 },
1402             ]
1403         );
1404         assert_eq!(
1405             first(builder.cache.all::<dist::Std>()),
1406             &[
1407                 dist::Std {
1408                     compiler: Compiler { host: a, stage: 2 },
1409                     target: a,
1410                 },
1411                 dist::Std {
1412                     compiler: Compiler { host: a, stage: 2 },
1413                     target: b,
1414                 },
1415             ]
1416         );
1417         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1418     }
1419
1420     #[test]
1421     fn dist_with_targets_and_hosts() {
1422         let build = Build::new(configure(&["B"], &["C"]));
1423         let mut builder = Builder::new(&build);
1424         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1425
1426         let a = INTERNER.intern_str("A");
1427         let b = INTERNER.intern_str("B");
1428         let c = INTERNER.intern_str("C");
1429
1430         assert_eq!(
1431             first(builder.cache.all::<dist::Docs>()),
1432             &[
1433                 dist::Docs { stage: 2, host: a },
1434                 dist::Docs { stage: 2, host: b },
1435                 dist::Docs { stage: 2, host: c },
1436             ]
1437         );
1438         assert_eq!(
1439             first(builder.cache.all::<dist::Mingw>()),
1440             &[
1441                 dist::Mingw { host: a },
1442                 dist::Mingw { host: b },
1443                 dist::Mingw { host: c },
1444             ]
1445         );
1446         assert_eq!(
1447             first(builder.cache.all::<dist::Rustc>()),
1448             &[
1449                 dist::Rustc {
1450                     compiler: Compiler { host: a, stage: 2 }
1451                 },
1452                 dist::Rustc {
1453                     compiler: Compiler { host: b, stage: 2 }
1454                 },
1455             ]
1456         );
1457         assert_eq!(
1458             first(builder.cache.all::<dist::Std>()),
1459             &[
1460                 dist::Std {
1461                     compiler: Compiler { host: a, stage: 2 },
1462                     target: a,
1463                 },
1464                 dist::Std {
1465                     compiler: Compiler { host: a, stage: 2 },
1466                     target: b,
1467                 },
1468                 dist::Std {
1469                     compiler: Compiler { host: a, stage: 2 },
1470                     target: c,
1471                 },
1472             ]
1473         );
1474         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1475     }
1476
1477     #[test]
1478     fn dist_with_target_flag() {
1479         let mut config = configure(&["B"], &["C"]);
1480         config.run_host_only = false; // as-if --target=C was passed
1481         let build = Build::new(config);
1482         let mut builder = Builder::new(&build);
1483         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1484
1485         let a = INTERNER.intern_str("A");
1486         let b = INTERNER.intern_str("B");
1487         let c = INTERNER.intern_str("C");
1488
1489         assert_eq!(
1490             first(builder.cache.all::<dist::Docs>()),
1491             &[
1492                 dist::Docs { stage: 2, host: a },
1493                 dist::Docs { stage: 2, host: b },
1494                 dist::Docs { stage: 2, host: c },
1495             ]
1496         );
1497         assert_eq!(
1498             first(builder.cache.all::<dist::Mingw>()),
1499             &[
1500                 dist::Mingw { host: a },
1501                 dist::Mingw { host: b },
1502                 dist::Mingw { host: c },
1503             ]
1504         );
1505         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1506         assert_eq!(
1507             first(builder.cache.all::<dist::Std>()),
1508             &[
1509                 dist::Std {
1510                     compiler: Compiler { host: a, stage: 2 },
1511                     target: a,
1512                 },
1513                 dist::Std {
1514                     compiler: Compiler { host: a, stage: 2 },
1515                     target: b,
1516                 },
1517                 dist::Std {
1518                     compiler: Compiler { host: a, stage: 2 },
1519                     target: c,
1520                 },
1521             ]
1522         );
1523         assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1524     }
1525
1526     #[test]
1527     fn dist_with_same_targets_and_hosts() {
1528         let build = Build::new(configure(&["B"], &["B"]));
1529         let mut builder = Builder::new(&build);
1530         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1531
1532         let a = INTERNER.intern_str("A");
1533         let b = INTERNER.intern_str("B");
1534
1535         assert_eq!(
1536             first(builder.cache.all::<dist::Docs>()),
1537             &[
1538                 dist::Docs { stage: 2, host: a },
1539                 dist::Docs { stage: 2, host: b },
1540             ]
1541         );
1542         assert_eq!(
1543             first(builder.cache.all::<dist::Mingw>()),
1544             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1545         );
1546         assert_eq!(
1547             first(builder.cache.all::<dist::Rustc>()),
1548             &[
1549                 dist::Rustc {
1550                     compiler: Compiler { host: a, stage: 2 }
1551                 },
1552                 dist::Rustc {
1553                     compiler: Compiler { host: b, stage: 2 }
1554                 },
1555             ]
1556         );
1557         assert_eq!(
1558             first(builder.cache.all::<dist::Std>()),
1559             &[
1560                 dist::Std {
1561                     compiler: Compiler { host: a, stage: 2 },
1562                     target: a,
1563                 },
1564                 dist::Std {
1565                     compiler: Compiler { host: a, stage: 2 },
1566                     target: b,
1567                 },
1568             ]
1569         );
1570         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1571         assert_eq!(
1572             first(builder.cache.all::<compile::Std>()),
1573             &[
1574                 compile::Std {
1575                     compiler: Compiler { host: a, stage: 0 },
1576                     target: a,
1577                 },
1578                 compile::Std {
1579                     compiler: Compiler { host: a, stage: 1 },
1580                     target: a,
1581                 },
1582                 compile::Std {
1583                     compiler: Compiler { host: a, stage: 2 },
1584                     target: a,
1585                 },
1586                 compile::Std {
1587                     compiler: Compiler { host: a, stage: 1 },
1588                     target: b,
1589                 },
1590                 compile::Std {
1591                     compiler: Compiler { host: a, stage: 2 },
1592                     target: b,
1593                 },
1594             ]
1595         );
1596         assert_eq!(
1597             first(builder.cache.all::<compile::Test>()),
1598             &[
1599                 compile::Test {
1600                     compiler: Compiler { host: a, stage: 0 },
1601                     target: a,
1602                 },
1603                 compile::Test {
1604                     compiler: Compiler { host: a, stage: 1 },
1605                     target: a,
1606                 },
1607                 compile::Test {
1608                     compiler: Compiler { host: a, stage: 2 },
1609                     target: a,
1610                 },
1611                 compile::Test {
1612                     compiler: Compiler { host: a, stage: 1 },
1613                     target: b,
1614                 },
1615                 compile::Test {
1616                     compiler: Compiler { host: a, stage: 2 },
1617                     target: b,
1618                 },
1619             ]
1620         );
1621         assert_eq!(
1622             first(builder.cache.all::<compile::Assemble>()),
1623             &[
1624                 compile::Assemble {
1625                     target_compiler: Compiler { host: a, stage: 0 },
1626                 },
1627                 compile::Assemble {
1628                     target_compiler: Compiler { host: a, stage: 1 },
1629                 },
1630                 compile::Assemble {
1631                     target_compiler: Compiler { host: a, stage: 2 },
1632                 },
1633                 compile::Assemble {
1634                     target_compiler: Compiler { host: b, stage: 2 },
1635                 },
1636             ]
1637         );
1638     }
1639
1640     #[test]
1641     fn build_default() {
1642         let build = Build::new(configure(&["B"], &["C"]));
1643         let mut builder = Builder::new(&build);
1644         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1645
1646         let a = INTERNER.intern_str("A");
1647         let b = INTERNER.intern_str("B");
1648         let c = INTERNER.intern_str("C");
1649
1650         assert!(!builder.cache.all::<compile::Std>().is_empty());
1651         assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1652         assert_eq!(
1653             first(builder.cache.all::<compile::Rustc>()),
1654             &[
1655                 compile::Rustc {
1656                     compiler: Compiler { host: a, stage: 0 },
1657                     target: a,
1658                 },
1659                 compile::Rustc {
1660                     compiler: Compiler { host: a, stage: 1 },
1661                     target: a,
1662                 },
1663                 compile::Rustc {
1664                     compiler: Compiler { host: a, stage: 2 },
1665                     target: a,
1666                 },
1667                 compile::Rustc {
1668                     compiler: Compiler { host: b, stage: 2 },
1669                     target: a,
1670                 },
1671                 compile::Rustc {
1672                     compiler: Compiler { host: a, stage: 0 },
1673                     target: b,
1674                 },
1675                 compile::Rustc {
1676                     compiler: Compiler { host: a, stage: 1 },
1677                     target: b,
1678                 },
1679                 compile::Rustc {
1680                     compiler: Compiler { host: a, stage: 2 },
1681                     target: b,
1682                 },
1683                 compile::Rustc {
1684                     compiler: Compiler { host: b, stage: 2 },
1685                     target: b,
1686                 },
1687             ]
1688         );
1689
1690         assert_eq!(
1691             first(builder.cache.all::<compile::Test>()),
1692             &[
1693                 compile::Test {
1694                     compiler: Compiler { host: a, stage: 0 },
1695                     target: a,
1696                 },
1697                 compile::Test {
1698                     compiler: Compiler { host: a, stage: 1 },
1699                     target: a,
1700                 },
1701                 compile::Test {
1702                     compiler: Compiler { host: a, stage: 2 },
1703                     target: a,
1704                 },
1705                 compile::Test {
1706                     compiler: Compiler { host: b, stage: 2 },
1707                     target: a,
1708                 },
1709                 compile::Test {
1710                     compiler: Compiler { host: a, stage: 0 },
1711                     target: b,
1712                 },
1713                 compile::Test {
1714                     compiler: Compiler { host: a, stage: 1 },
1715                     target: b,
1716                 },
1717                 compile::Test {
1718                     compiler: Compiler { host: a, stage: 2 },
1719                     target: b,
1720                 },
1721                 compile::Test {
1722                     compiler: Compiler { host: b, stage: 2 },
1723                     target: b,
1724                 },
1725                 compile::Test {
1726                     compiler: Compiler { host: a, stage: 2 },
1727                     target: c,
1728                 },
1729                 compile::Test {
1730                     compiler: Compiler { host: b, stage: 2 },
1731                     target: c,
1732                 },
1733             ]
1734         );
1735     }
1736
1737     #[test]
1738     fn build_with_target_flag() {
1739         let mut config = configure(&["B"], &["C"]);
1740         config.run_host_only = false;
1741         let build = Build::new(config);
1742         let mut builder = Builder::new(&build);
1743         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1744
1745         let a = INTERNER.intern_str("A");
1746         let b = INTERNER.intern_str("B");
1747         let c = INTERNER.intern_str("C");
1748
1749         assert!(!builder.cache.all::<compile::Std>().is_empty());
1750         assert_eq!(
1751             first(builder.cache.all::<compile::Assemble>()),
1752             &[
1753                 compile::Assemble {
1754                     target_compiler: Compiler { host: a, stage: 0 },
1755                 },
1756                 compile::Assemble {
1757                     target_compiler: Compiler { host: a, stage: 1 },
1758                 },
1759                 compile::Assemble {
1760                     target_compiler: Compiler { host: b, stage: 1 },
1761                 },
1762                 compile::Assemble {
1763                     target_compiler: Compiler { host: a, stage: 2 },
1764                 },
1765                 compile::Assemble {
1766                     target_compiler: Compiler { host: b, stage: 2 },
1767                 },
1768             ]
1769         );
1770         assert_eq!(
1771             first(builder.cache.all::<compile::Rustc>()),
1772             &[
1773                 compile::Rustc {
1774                     compiler: Compiler { host: a, stage: 0 },
1775                     target: a,
1776                 },
1777                 compile::Rustc {
1778                     compiler: Compiler { host: a, stage: 1 },
1779                     target: a,
1780                 },
1781                 compile::Rustc {
1782                     compiler: Compiler { host: a, stage: 0 },
1783                     target: b,
1784                 },
1785                 compile::Rustc {
1786                     compiler: Compiler { host: a, stage: 1 },
1787                     target: b,
1788                 },
1789             ]
1790         );
1791
1792         assert_eq!(
1793             first(builder.cache.all::<compile::Test>()),
1794             &[
1795                 compile::Test {
1796                     compiler: Compiler { host: a, stage: 0 },
1797                     target: a,
1798                 },
1799                 compile::Test {
1800                     compiler: Compiler { host: a, stage: 1 },
1801                     target: a,
1802                 },
1803                 compile::Test {
1804                     compiler: Compiler { host: a, stage: 2 },
1805                     target: a,
1806                 },
1807                 compile::Test {
1808                     compiler: Compiler { host: b, stage: 2 },
1809                     target: a,
1810                 },
1811                 compile::Test {
1812                     compiler: Compiler { host: a, stage: 0 },
1813                     target: b,
1814                 },
1815                 compile::Test {
1816                     compiler: Compiler { host: a, stage: 1 },
1817                     target: b,
1818                 },
1819                 compile::Test {
1820                     compiler: Compiler { host: a, stage: 2 },
1821                     target: b,
1822                 },
1823                 compile::Test {
1824                     compiler: Compiler { host: b, stage: 2 },
1825                     target: b,
1826                 },
1827                 compile::Test {
1828                     compiler: Compiler { host: a, stage: 2 },
1829                     target: c,
1830                 },
1831                 compile::Test {
1832                     compiler: Compiler { host: b, stage: 2 },
1833                     target: c,
1834                 },
1835             ]
1836         );
1837     }
1838
1839     #[test]
1840     fn test_with_no_doc_stage0() {
1841         let mut config = configure(&[], &[]);
1842         config.stage = Some(0);
1843         config.cmd = Subcommand::Test {
1844             paths: vec!["src/libstd".into()],
1845             test_args: vec![],
1846             rustc_args: vec![],
1847             fail_fast: true,
1848             doc_tests: DocTests::No,
1849             bless: false,
1850             compare_mode: None,
1851         };
1852
1853         let build = Build::new(config);
1854         let mut builder = Builder::new(&build);
1855
1856         let host = INTERNER.intern_str("A");
1857
1858         builder.run_step_descriptions(
1859             &[StepDescription::from::<test::Crate>()],
1860             &["src/libstd".into()],
1861         );
1862
1863         // Ensure we don't build any compiler artifacts.
1864         assert!(!builder.cache.contains::<compile::Rustc>());
1865         assert_eq!(
1866             first(builder.cache.all::<test::Crate>()),
1867             &[test::Crate {
1868                 compiler: Compiler { host, stage: 0 },
1869                 target: host,
1870                 mode: Mode::Std,
1871                 test_kind: test::TestKind::Test,
1872                 krate: INTERNER.intern_str("std"),
1873             },]
1874         );
1875     }
1876
1877     #[test]
1878     fn test_exclude() {
1879         let mut config = configure(&[], &[]);
1880         config.exclude = vec![
1881             "src/test/run-pass".into(),
1882             "src/tools/tidy".into(),
1883         ];
1884         config.cmd = Subcommand::Test {
1885             paths: Vec::new(),
1886             test_args: Vec::new(),
1887             rustc_args: Vec::new(),
1888             fail_fast: true,
1889             doc_tests: DocTests::No,
1890             bless: false,
1891             compare_mode: None,
1892         };
1893
1894         let build = Build::new(config);
1895         let builder = Builder::new(&build);
1896         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Test), &[]);
1897
1898         // Ensure we have really excluded run-pass & tidy
1899         assert!(!builder.cache.contains::<test::RunPass>());
1900         assert!(!builder.cache.contains::<test::Tidy>());
1901
1902         // Ensure other tests are not affected.
1903         assert!(builder.cache.contains::<test::RunPassFullDeps>());
1904         assert!(builder.cache.contains::<test::RustdocUi>());
1905     }
1906 }