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