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