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