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