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