]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Auto merge of #61300 - indygreg:upgrade-cross-make, r=sanxiyn
[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     /// Similar to `compiler`, except handles the full-bootstrap option to
585     /// silently use the stage1 compiler instead of a stage2 compiler if one is
586     /// requested.
587     ///
588     /// Note that this does *not* have the side effect of creating
589     /// `compiler(stage, host)`, unlike `compiler` above which does have such
590     /// a side effect. The returned compiler here can only be used to compile
591     /// new artifacts, it can't be used to rely on the presence of a particular
592     /// sysroot.
593     ///
594     /// See `force_use_stage1` for documentation on what each argument is.
595     pub fn compiler_for(
596         &self,
597         stage: u32,
598         host: Interned<String>,
599         target: Interned<String>,
600     ) -> Compiler {
601         if self.build.force_use_stage1(Compiler { stage, host }, target) {
602             self.compiler(1, self.config.build)
603         } else {
604             self.compiler(stage, host)
605         }
606     }
607
608     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
609         self.ensure(compile::Sysroot { compiler })
610     }
611
612     /// Returns the libdir where the standard library and other artifacts are
613     /// found for a compiler's sysroot.
614     pub fn sysroot_libdir(
615         &self,
616         compiler: Compiler,
617         target: Interned<String>,
618     ) -> Interned<PathBuf> {
619         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
620         struct Libdir {
621             compiler: Compiler,
622             target: Interned<String>,
623         }
624         impl Step for Libdir {
625             type Output = Interned<PathBuf>;
626
627             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
628                 run.never()
629             }
630
631             fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
632                 let compiler = self.compiler;
633                 let config = &builder.build.config;
634                 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
635                     builder.build.config.libdir_relative().unwrap()
636                 } else {
637                     Path::new("lib")
638                 };
639                 let sysroot = builder
640                     .sysroot(self.compiler)
641                     .join(lib)
642                     .join("rustlib")
643                     .join(self.target)
644                     .join("lib");
645                 let _ = fs::remove_dir_all(&sysroot);
646                 t!(fs::create_dir_all(&sysroot));
647                 INTERNER.intern_path(sysroot)
648             }
649         }
650         self.ensure(Libdir { compiler, target })
651     }
652
653     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
654         self.sysroot_libdir(compiler, compiler.host)
655             .with_file_name(self.config.rust_codegen_backends_dir.clone())
656     }
657
658     /// Returns the compiler's libdir where it stores the dynamic libraries that
659     /// it itself links against.
660     ///
661     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
662     /// Windows.
663     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
664         if compiler.is_snapshot(self) {
665             self.rustc_snapshot_libdir()
666         } else {
667             match self.config.libdir_relative() {
668                 Some(relative_libdir) if compiler.stage >= 1
669                     => self.sysroot(compiler).join(relative_libdir),
670                 _ => self.sysroot(compiler).join(libdir(&compiler.host))
671             }
672         }
673     }
674
675     /// Returns the compiler's relative libdir where it stores the dynamic libraries that
676     /// it itself links against.
677     ///
678     /// For example this returns `lib` on Unix and `bin` on
679     /// Windows.
680     pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
681         if compiler.is_snapshot(self) {
682             libdir(&self.config.build).as_ref()
683         } else {
684             match self.config.libdir_relative() {
685                 Some(relative_libdir) if compiler.stage >= 1
686                     => relative_libdir,
687                 _ => libdir(&compiler.host).as_ref()
688             }
689         }
690     }
691
692     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
693     /// library lookup path.
694     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
695         // Windows doesn't need dylib path munging because the dlls for the
696         // compiler live next to the compiler and the system will find them
697         // automatically.
698         if cfg!(windows) {
699             return;
700         }
701
702         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
703     }
704
705     /// Gets a path to the compiler specified.
706     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
707         if compiler.is_snapshot(self) {
708             self.initial_rustc.clone()
709         } else {
710             self.sysroot(compiler)
711                 .join("bin")
712                 .join(exe("rustc", &compiler.host))
713         }
714     }
715
716     /// Gets the paths to all of the compiler's codegen backends.
717     fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
718         fs::read_dir(self.sysroot_codegen_backends(compiler))
719             .into_iter()
720             .flatten()
721             .filter_map(Result::ok)
722             .map(|entry| entry.path())
723     }
724
725     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
726         self.ensure(tool::Rustdoc { compiler })
727     }
728
729     pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
730         let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
731         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
732             .env("RUSTC_SYSROOT", self.sysroot(compiler))
733             // Note that this is *not* the sysroot_libdir because rustdoc must be linked
734             // equivalently to rustc.
735             .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
736             .env("CFG_RELEASE_CHANNEL", &self.config.channel)
737             .env("RUSTDOC_REAL", self.rustdoc(compiler))
738             .env("RUSTDOC_CRATE_VERSION", self.rust_version())
739             .env("RUSTC_BOOTSTRAP", "1");
740
741         // Remove make-related flags that can cause jobserver problems.
742         cmd.env_remove("MAKEFLAGS");
743         cmd.env_remove("MFLAGS");
744
745         if let Some(linker) = self.linker(compiler.host) {
746             cmd.env("RUSTC_TARGET_LINKER", linker);
747         }
748         cmd
749     }
750
751     /// Prepares an invocation of `cargo` to be run.
752     ///
753     /// This will create a `Command` that represents a pending execution of
754     /// Cargo. This cargo will be configured to use `compiler` as the actual
755     /// rustc compiler, its output will be scoped by `mode`'s output directory,
756     /// it will pass the `--target` flag for the specified `target`, and will be
757     /// executing the Cargo command `cmd`.
758     pub fn cargo(
759         &self,
760         compiler: Compiler,
761         mode: Mode,
762         target: Interned<String>,
763         cmd: &str,
764     ) -> Command {
765         let mut cargo = Command::new(&self.initial_cargo);
766         let out_dir = self.stage_out(compiler, mode);
767
768         // command specific path, we call clear_if_dirty with this
769         let mut my_out = match cmd {
770             "build" => self.cargo_out(compiler, mode, target),
771
772             // This is the intended out directory for crate documentation.
773             "doc" | "rustdoc" =>  self.crate_doc_out(target),
774
775             _ => self.stage_out(compiler, mode),
776         };
777
778         // This is for the original compiler, but if we're forced to use stage 1, then
779         // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
780         // we copy the libs forward.
781         let cmp = self.compiler_for(compiler.stage, compiler.host, target);
782
783         let libstd_stamp = match cmd {
784             "check" | "clippy" | "fix" => check::libstd_stamp(self, cmp, target),
785             _ => compile::libstd_stamp(self, cmp, target),
786         };
787
788         let libtest_stamp = match cmd {
789             "check" | "clippy" | "fix" => check::libtest_stamp(self, cmp, target),
790             _ => compile::libstd_stamp(self, cmp, target),
791         };
792
793         let librustc_stamp = match cmd {
794             "check" | "clippy" | "fix" => check::librustc_stamp(self, cmp, target),
795             _ => compile::librustc_stamp(self, cmp, target),
796         };
797
798         if cmd == "doc" || cmd == "rustdoc" {
799             if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen {
800                 // This is the intended out directory for compiler documentation.
801                 my_out = self.compiler_doc_out(target);
802             }
803             let rustdoc = self.rustdoc(compiler);
804             self.clear_if_dirty(&my_out, &rustdoc);
805         } else if cmd != "test" {
806             match mode {
807                 Mode::Std => {
808                     self.clear_if_dirty(&my_out, &self.rustc(compiler));
809                     for backend in self.codegen_backends(compiler) {
810                         self.clear_if_dirty(&my_out, &backend);
811                     }
812                 },
813                 Mode::Test => {
814                     self.clear_if_dirty(&my_out, &libstd_stamp);
815                 },
816                 Mode::Rustc => {
817                     self.clear_if_dirty(&my_out, &self.rustc(compiler));
818                     self.clear_if_dirty(&my_out, &libstd_stamp);
819                     self.clear_if_dirty(&my_out, &libtest_stamp);
820                 },
821                 Mode::Codegen => {
822                     self.clear_if_dirty(&my_out, &librustc_stamp);
823                 },
824                 Mode::ToolBootstrap => { },
825                 Mode::ToolStd => {
826                     self.clear_if_dirty(&my_out, &libstd_stamp);
827                 },
828                 Mode::ToolTest => {
829                     self.clear_if_dirty(&my_out, &libstd_stamp);
830                     self.clear_if_dirty(&my_out, &libtest_stamp);
831                 },
832                 Mode::ToolRustc => {
833                     self.clear_if_dirty(&my_out, &libstd_stamp);
834                     self.clear_if_dirty(&my_out, &libtest_stamp);
835                     self.clear_if_dirty(&my_out, &librustc_stamp);
836                 },
837             }
838         }
839
840         cargo
841             .env("CARGO_TARGET_DIR", out_dir)
842             .arg(cmd);
843
844         // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
845         // needs to not accidentally link to libLLVM in stage0/lib.
846         cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
847         if let Some(e) = env::var_os(util::dylib_path_var()) {
848             cargo.env("REAL_LIBRARY_PATH", e);
849         }
850
851         if cmd != "install" {
852             cargo.arg("--target")
853                  .arg(target);
854         } else {
855             assert_eq!(target, compiler.host);
856         }
857
858         // Set a flag for `check`/`clippy`/`fix`, so that certain build
859         // scripts can do less work (e.g. not building/requiring LLVM).
860         if cmd == "check" || cmd == "clippy" || cmd == "fix" {
861             cargo.env("RUST_CHECK", "1");
862         }
863
864         match mode {
865             Mode::Std | Mode::Test | Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTest=> {},
866             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
867                 // Build proc macros both for the host and the target
868                 if target != compiler.host && cmd != "check" {
869                     cargo.arg("-Zdual-proc-macros");
870                     cargo.env("RUST_DUAL_PROC_MACROS", "1");
871                 }
872             },
873         }
874
875         cargo.arg("-j").arg(self.jobs().to_string());
876         // Remove make-related flags to ensure Cargo can correctly set things up
877         cargo.env_remove("MAKEFLAGS");
878         cargo.env_remove("MFLAGS");
879
880         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
881         // Force cargo to output binaries with disambiguating hashes in the name
882         let mut metadata = if compiler.stage == 0 {
883             // Treat stage0 like a special channel, whether it's a normal prior-
884             // release rustc or a local rebuild with the same version, so we
885             // never mix these libraries by accident.
886             "bootstrap".to_string()
887         } else {
888             self.config.channel.to_string()
889         };
890         // We want to make sure that none of the dependencies between
891         // std/test/rustc unify with one another. This is done for weird linkage
892         // reasons but the gist of the problem is that if librustc, libtest, and
893         // libstd all depend on libc from crates.io (which they actually do) we
894         // want to make sure they all get distinct versions. Things get really
895         // weird if we try to unify all these dependencies right now, namely
896         // around how many times the library is linked in dynamic libraries and
897         // such. If rustc were a static executable or if we didn't ship dylibs
898         // this wouldn't be a problem, but we do, so it is. This is in general
899         // just here to make sure things build right. If you can remove this and
900         // things still build right, please do!
901         match mode {
902             Mode::Std => metadata.push_str("std"),
903             Mode::Test => metadata.push_str("test"),
904             _ => {},
905         }
906         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
907
908         let stage;
909         if compiler.stage == 0 && self.local_rebuild {
910             // Assume the local-rebuild rustc already has stage1 features.
911             stage = 1;
912         } else {
913             stage = compiler.stage;
914         }
915
916         let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
917         if stage != 0 {
918             let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
919             if !extra_args.is_empty() {
920                 extra_args.push_str(" ");
921             }
922             extra_args.push_str(&s);
923         }
924
925         if cmd == "clippy" {
926             extra_args.push_str("-Zforce-unstable-if-unmarked -Zunstable-options \
927                 --json-rendered=termcolor");
928         }
929
930         if !extra_args.is_empty() {
931             cargo.env(
932                 "RUSTFLAGS",
933                 format!(
934                     "{} {}",
935                     env::var("RUSTFLAGS").unwrap_or_default(),
936                     extra_args
937                 ),
938             );
939         }
940
941         let want_rustdoc = self.doc_tests != DocTests::No;
942
943         // We synthetically interpret a stage0 compiler used to build tools as a
944         // "raw" compiler in that it's the exact snapshot we download. Normally
945         // the stage0 build means it uses libraries build by the stage0
946         // compiler, but for tools we just use the precompiled libraries that
947         // we've downloaded
948         let use_snapshot = mode == Mode::ToolBootstrap;
949         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
950
951         let maybe_sysroot = self.sysroot(compiler);
952         let sysroot = if use_snapshot {
953             self.rustc_snapshot_sysroot()
954         } else {
955             &maybe_sysroot
956         };
957         let libdir = self.rustc_libdir(compiler);
958
959         // Customize the compiler we're running. Specify the compiler to cargo
960         // as our shim and then pass it some various options used to configure
961         // how the actual compiler itself is called.
962         //
963         // These variables are primarily all read by
964         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
965         cargo
966             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
967             .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
968             .env("RUSTC_REAL", self.rustc(compiler))
969             .env("RUSTC_STAGE", stage.to_string())
970             .env(
971                 "RUSTC_DEBUG_ASSERTIONS",
972                 self.config.rust_debug_assertions.to_string(),
973             )
974             .env("RUSTC_SYSROOT", &sysroot)
975             .env("RUSTC_LIBDIR", &libdir)
976             .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
977             .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
978             .env(
979                 "RUSTDOC_REAL",
980                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
981                     self.rustdoc(compiler)
982                 } else {
983                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
984                 },
985             )
986             .env("TEST_MIRI", self.config.test_miri.to_string())
987             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
988
989         if let Some(host_linker) = self.linker(compiler.host) {
990             cargo.env("RUSTC_HOST_LINKER", host_linker);
991         }
992         if let Some(target_linker) = self.linker(target) {
993             cargo.env("RUSTC_TARGET_LINKER", target_linker);
994         }
995         if let Some(ref error_format) = self.config.rustc_error_format {
996             cargo.env("RUSTC_ERROR_FORMAT", error_format);
997         }
998         if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
999             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1000         }
1001
1002         let debuginfo_level = match mode {
1003             Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1004             Mode::Std | Mode::Test => self.config.rust_debuginfo_level_std,
1005             Mode::ToolBootstrap | Mode::ToolStd |
1006             Mode::ToolTest | Mode::ToolRustc => self.config.rust_debuginfo_level_tools,
1007         };
1008         cargo.env("RUSTC_DEBUGINFO_LEVEL", debuginfo_level.to_string());
1009
1010         if !mode.is_tool() {
1011             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1012
1013             // Currently the compiler depends on crates from crates.io, and
1014             // then other crates can depend on the compiler (e.g., proc-macro
1015             // crates). Let's say, for example that rustc itself depends on the
1016             // bitflags crate. If an external crate then depends on the
1017             // bitflags crate as well, we need to make sure they don't
1018             // conflict, even if they pick the same version of bitflags. We'll
1019             // want to make sure that e.g., a plugin and rustc each get their
1020             // own copy of bitflags.
1021
1022             // Cargo ensures that this works in general through the -C metadata
1023             // flag. This flag will frob the symbols in the binary to make sure
1024             // they're different, even though the source code is the exact
1025             // same. To solve this problem for the compiler we extend Cargo's
1026             // already-passed -C metadata flag with our own. Our rustc.rs
1027             // wrapper around the actual rustc will detect -C metadata being
1028             // passed and frob it with this extra string we're passing in.
1029             cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
1030         }
1031
1032         if let Some(x) = self.crt_static(target) {
1033             cargo.env("RUSTC_CRT_STATIC", x.to_string());
1034         }
1035
1036         if let Some(x) = self.crt_static(compiler.host) {
1037             cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1038         }
1039
1040         if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
1041             cargo.env("RUSTC_DEBUGINFO_MAP", map);
1042         }
1043
1044         // Enable usage of unstable features
1045         cargo.env("RUSTC_BOOTSTRAP", "1");
1046         self.add_rust_test_threads(&mut cargo);
1047
1048         // Almost all of the crates that we compile as part of the bootstrap may
1049         // have a build script, including the standard library. To compile a
1050         // build script, however, it itself needs a standard library! This
1051         // introduces a bit of a pickle when we're compiling the standard
1052         // library itself.
1053         //
1054         // To work around this we actually end up using the snapshot compiler
1055         // (stage0) for compiling build scripts of the standard library itself.
1056         // The stage0 compiler is guaranteed to have a libstd available for use.
1057         //
1058         // For other crates, however, we know that we've already got a standard
1059         // library up and running, so we can use the normal compiler to compile
1060         // build scripts in that situation.
1061         if mode == Mode::Std {
1062             cargo
1063                 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1064                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1065         } else {
1066             cargo
1067                 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1068                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1069         }
1070
1071         if self.config.incremental {
1072             cargo.env("CARGO_INCREMENTAL", "1");
1073         } else {
1074             // Don't rely on any default setting for incr. comp. in Cargo
1075             cargo.env("CARGO_INCREMENTAL", "0");
1076         }
1077
1078         if let Some(ref on_fail) = self.config.on_fail {
1079             cargo.env("RUSTC_ON_FAIL", on_fail);
1080         }
1081
1082         if self.config.print_step_timings {
1083             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1084         }
1085
1086         if self.config.backtrace_on_ice {
1087             cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1088         }
1089
1090         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1091
1092         if self.config.deny_warnings {
1093             cargo.env("RUSTC_DENY_WARNINGS", "1");
1094         }
1095
1096         // Throughout the build Cargo can execute a number of build scripts
1097         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1098         // obtained previously to those build scripts.
1099         // Build scripts use either the `cc` crate or `configure/make` so we pass
1100         // the options through environment variables that are fetched and understood by both.
1101         //
1102         // FIXME: the guard against msvc shouldn't need to be here
1103         if target.contains("msvc") {
1104             if let Some(ref cl) = self.config.llvm_clang_cl {
1105                 cargo.env("CC", cl).env("CXX", cl);
1106             }
1107         } else {
1108             let ccache = self.config.ccache.as_ref();
1109             let ccacheify = |s: &Path| {
1110                 let ccache = match ccache {
1111                     Some(ref s) => s,
1112                     None => return s.display().to_string(),
1113                 };
1114                 // FIXME: the cc-rs crate only recognizes the literal strings
1115                 // `ccache` and `sccache` when doing caching compilations, so we
1116                 // mirror that here. It should probably be fixed upstream to
1117                 // accept a new env var or otherwise work with custom ccache
1118                 // vars.
1119                 match &ccache[..] {
1120                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1121                     _ => s.display().to_string(),
1122                 }
1123             };
1124             let cc = ccacheify(&self.cc(target));
1125             cargo.env(format!("CC_{}", target), &cc);
1126
1127             let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1128             cargo
1129                 .env(format!("CFLAGS_{}", target), cflags.clone());
1130
1131             if let Some(ar) = self.ar(target) {
1132                 let ranlib = format!("{} s", ar.display());
1133                 cargo
1134                     .env(format!("AR_{}", target), ar)
1135                     .env(format!("RANLIB_{}", target), ranlib);
1136             }
1137
1138             if let Ok(cxx) = self.cxx(target) {
1139                 let cxx = ccacheify(&cxx);
1140                 cargo
1141                     .env(format!("CXX_{}", target), &cxx)
1142                     .env(format!("CXXFLAGS_{}", target), cflags);
1143             }
1144         }
1145
1146         if (cmd == "build" || cmd == "rustc")
1147             && mode == Mode::Std
1148             && self.config.extended
1149             && compiler.is_final_stage(self)
1150         {
1151             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
1152         }
1153
1154         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1155         cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1156
1157         // Environment variables *required* throughout the build
1158         //
1159         // FIXME: should update code to not require this env var
1160         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1161
1162         // Set this for all builds to make sure doc builds also get it.
1163         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1164
1165         // This one's a bit tricky. As of the time of this writing the compiler
1166         // links to the `winapi` crate on crates.io. This crate provides raw
1167         // bindings to Windows system functions, sort of like libc does for
1168         // Unix. This crate also, however, provides "import libraries" for the
1169         // MinGW targets. There's an import library per dll in the windows
1170         // distribution which is what's linked to. These custom import libraries
1171         // are used because the winapi crate can reference Windows functions not
1172         // present in the MinGW import libraries.
1173         //
1174         // For example MinGW may ship libdbghelp.a, but it may not have
1175         // references to all the functions in the dbghelp dll. Instead the
1176         // custom import library for dbghelp in the winapi crates has all this
1177         // information.
1178         //
1179         // Unfortunately for us though the import libraries are linked by
1180         // default via `-ldylib=winapi_foo`. That is, they're linked with the
1181         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1182         // conflict with the system MinGW ones). This consequently means that
1183         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1184         // DLL) when linked against *again*, for example with procedural macros
1185         // or plugins, will trigger the propagation logic of `-ldylib`, passing
1186         // `-lwinapi_foo` to the linker again. This isn't actually available in
1187         // our distribution, however, so the link fails.
1188         //
1189         // To solve this problem we tell winapi to not use its bundled import
1190         // libraries. This means that it will link to the system MinGW import
1191         // libraries by default, and the `-ldylib=foo` directives will still get
1192         // passed to the final linker, but they'll look like `-lfoo` which can
1193         // be resolved because MinGW has the import library. The downside is we
1194         // don't get newer functions from Windows, but we don't use any of them
1195         // anyway.
1196         if !mode.is_tool() {
1197             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1198         }
1199
1200         for _ in 1..self.verbosity {
1201             cargo.arg("-v");
1202         }
1203
1204         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1205             (Mode::Std, Some(n), _) |
1206             (Mode::Test, Some(n), _) |
1207             (_, _, Some(n)) => {
1208                 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
1209             }
1210             _ => {
1211                 // Don't set anything
1212             }
1213         }
1214
1215         if self.config.rust_optimize {
1216             // FIXME: cargo bench/install do not accept `--release`
1217             if cmd != "bench" && cmd != "install" {
1218                 cargo.arg("--release");
1219             }
1220         }
1221
1222         if self.config.locked_deps {
1223             cargo.arg("--locked");
1224         }
1225         if self.config.vendor || self.is_sudo {
1226             cargo.arg("--frozen");
1227         }
1228
1229         self.ci_env.force_coloring_in_ci(&mut cargo);
1230
1231         cargo
1232     }
1233
1234     /// Ensure that a given step is built, returning its output. This will
1235     /// cache the step, so it is safe (and good!) to call this as often as
1236     /// needed to ensure that all dependencies are built.
1237     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1238         {
1239             let mut stack = self.stack.borrow_mut();
1240             for stack_step in stack.iter() {
1241                 // should skip
1242                 if stack_step
1243                     .downcast_ref::<S>()
1244                     .map_or(true, |stack_step| *stack_step != step)
1245                 {
1246                     continue;
1247                 }
1248                 let mut out = String::new();
1249                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1250                 for el in stack.iter().rev() {
1251                     out += &format!("\t{:?}\n", el);
1252                 }
1253                 panic!(out);
1254             }
1255             if let Some(out) = self.cache.get(&step) {
1256                 self.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
1257
1258                 {
1259                     let mut graph = self.graph.borrow_mut();
1260                     let parent = self.parent.get();
1261                     let us = *self
1262                         .graph_nodes
1263                         .borrow_mut()
1264                         .entry(format!("{:?}", step))
1265                         .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1266                     if let Some(parent) = parent {
1267                         graph.add_edge(parent, us, false);
1268                     }
1269                 }
1270
1271                 return out;
1272             }
1273             self.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
1274             stack.push(Box::new(step.clone()));
1275         }
1276
1277         let prev_parent = self.parent.get();
1278
1279         {
1280             let mut graph = self.graph.borrow_mut();
1281             let parent = self.parent.get();
1282             let us = *self
1283                 .graph_nodes
1284                 .borrow_mut()
1285                 .entry(format!("{:?}", step))
1286                 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1287             self.parent.set(Some(us));
1288             if let Some(parent) = parent {
1289                 graph.add_edge(parent, us, true);
1290             }
1291         }
1292
1293         let (out, dur) = {
1294             let start = Instant::now();
1295             let zero = Duration::new(0, 0);
1296             let parent = self.time_spent_on_dependencies.replace(zero);
1297             let out = step.clone().run(self);
1298             let dur = start.elapsed();
1299             let deps = self.time_spent_on_dependencies.replace(parent + dur);
1300             (out, dur - deps)
1301         };
1302
1303         self.parent.set(prev_parent);
1304
1305         if self.config.print_step_timings && dur > Duration::from_millis(100) {
1306             println!(
1307                 "[TIMING] {:?} -- {}.{:03}",
1308                 step,
1309                 dur.as_secs(),
1310                 dur.subsec_nanos() / 1_000_000
1311             );
1312         }
1313
1314         {
1315             let mut stack = self.stack.borrow_mut();
1316             let cur_step = stack.pop().expect("step stack empty");
1317             assert_eq!(cur_step.downcast_ref(), Some(&step));
1318         }
1319         self.verbose(&format!(
1320             "{}< {:?}",
1321             "  ".repeat(self.stack.borrow().len()),
1322             step
1323         ));
1324         self.cache.put(step, out.clone());
1325         out
1326     }
1327 }
1328
1329 #[cfg(test)]
1330 mod __test {
1331     use super::*;
1332     use crate::config::Config;
1333     use std::thread;
1334
1335     use pretty_assertions::assert_eq;
1336
1337     fn configure(host: &[&str], target: &[&str]) -> Config {
1338         let mut config = Config::default_opts();
1339         // don't save toolstates
1340         config.save_toolstates = None;
1341         config.run_host_only = true;
1342         config.dry_run = true;
1343         // try to avoid spurious failures in dist where we create/delete each others file
1344         let dir = config.out.join("tmp-rustbuild-tests").join(
1345             &thread::current()
1346                 .name()
1347                 .unwrap_or("unknown")
1348                 .replace(":", "-"),
1349         );
1350         t!(fs::create_dir_all(&dir));
1351         config.out = dir;
1352         config.build = INTERNER.intern_str("A");
1353         config.hosts = vec![config.build]
1354             .clone()
1355             .into_iter()
1356             .chain(host.iter().map(|s| INTERNER.intern_str(s)))
1357             .collect::<Vec<_>>();
1358         config.targets = config
1359             .hosts
1360             .clone()
1361             .into_iter()
1362             .chain(target.iter().map(|s| INTERNER.intern_str(s)))
1363             .collect::<Vec<_>>();
1364         config
1365     }
1366
1367     fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
1368         v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
1369     }
1370
1371     #[test]
1372     fn dist_baseline() {
1373         let build = Build::new(configure(&[], &[]));
1374         let mut builder = Builder::new(&build);
1375         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1376
1377         let a = INTERNER.intern_str("A");
1378
1379         assert_eq!(
1380             first(builder.cache.all::<dist::Docs>()),
1381             &[dist::Docs { host: a },]
1382         );
1383         assert_eq!(
1384             first(builder.cache.all::<dist::Mingw>()),
1385             &[dist::Mingw { host: a },]
1386         );
1387         assert_eq!(
1388             first(builder.cache.all::<dist::Rustc>()),
1389             &[dist::Rustc {
1390                 compiler: Compiler { host: a, stage: 2 }
1391             },]
1392         );
1393         assert_eq!(
1394             first(builder.cache.all::<dist::Std>()),
1395             &[dist::Std {
1396                 compiler: Compiler { host: a, stage: 1 },
1397                 target: a,
1398             },]
1399         );
1400         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1401     }
1402
1403     #[test]
1404     fn dist_with_targets() {
1405         let build = Build::new(configure(&[], &["B"]));
1406         let mut builder = Builder::new(&build);
1407         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1408
1409         let a = INTERNER.intern_str("A");
1410         let b = INTERNER.intern_str("B");
1411
1412         assert_eq!(
1413             first(builder.cache.all::<dist::Docs>()),
1414             &[
1415                 dist::Docs { host: a },
1416                 dist::Docs { host: b },
1417             ]
1418         );
1419         assert_eq!(
1420             first(builder.cache.all::<dist::Mingw>()),
1421             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1422         );
1423         assert_eq!(
1424             first(builder.cache.all::<dist::Rustc>()),
1425             &[dist::Rustc {
1426                 compiler: Compiler { host: a, stage: 2 }
1427             },]
1428         );
1429         assert_eq!(
1430             first(builder.cache.all::<dist::Std>()),
1431             &[
1432                 dist::Std {
1433                     compiler: Compiler { host: a, stage: 1 },
1434                     target: a,
1435                 },
1436                 dist::Std {
1437                     compiler: Compiler { host: a, stage: 2 },
1438                     target: b,
1439                 },
1440             ]
1441         );
1442         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1443     }
1444
1445     #[test]
1446     fn dist_with_hosts() {
1447         let build = Build::new(configure(&["B"], &[]));
1448         let mut builder = Builder::new(&build);
1449         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1450
1451         let a = INTERNER.intern_str("A");
1452         let b = INTERNER.intern_str("B");
1453
1454         assert_eq!(
1455             first(builder.cache.all::<dist::Docs>()),
1456             &[
1457                 dist::Docs { host: a },
1458                 dist::Docs { host: b },
1459             ]
1460         );
1461         assert_eq!(
1462             first(builder.cache.all::<dist::Mingw>()),
1463             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1464         );
1465         assert_eq!(
1466             first(builder.cache.all::<dist::Rustc>()),
1467             &[
1468                 dist::Rustc {
1469                     compiler: Compiler { host: a, stage: 2 }
1470                 },
1471                 dist::Rustc {
1472                     compiler: Compiler { host: b, stage: 2 }
1473                 },
1474             ]
1475         );
1476         assert_eq!(
1477             first(builder.cache.all::<dist::Std>()),
1478             &[
1479                 dist::Std {
1480                     compiler: Compiler { host: a, stage: 1 },
1481                     target: a,
1482                 },
1483                 dist::Std {
1484                     compiler: Compiler { host: a, stage: 1 },
1485                     target: b,
1486                 },
1487             ]
1488         );
1489         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1490     }
1491
1492     #[test]
1493     fn dist_only_cross_host() {
1494         let a = INTERNER.intern_str("A");
1495         let b = INTERNER.intern_str("B");
1496         let mut build = Build::new(configure(&["B"], &[]));
1497         build.config.docs = false;
1498         build.config.extended = true;
1499         build.hosts = vec![b];
1500         let mut builder = Builder::new(&build);
1501         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1502
1503         assert_eq!(
1504             first(builder.cache.all::<dist::Rustc>()),
1505             &[
1506                 dist::Rustc {
1507                     compiler: Compiler { host: b, stage: 2 }
1508                 },
1509             ]
1510         );
1511         assert_eq!(
1512             first(builder.cache.all::<compile::Rustc>()),
1513             &[
1514                 compile::Rustc {
1515                     compiler: Compiler { host: a, stage: 0 },
1516                     target: a,
1517                 },
1518                 compile::Rustc {
1519                     compiler: Compiler { host: a, stage: 1 },
1520                     target: b,
1521                 },
1522             ]
1523         );
1524     }
1525
1526     #[test]
1527     fn dist_with_targets_and_hosts() {
1528         let build = Build::new(configure(&["B"], &["C"]));
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         let c = INTERNER.intern_str("C");
1535
1536         assert_eq!(
1537             first(builder.cache.all::<dist::Docs>()),
1538             &[
1539                 dist::Docs { host: a },
1540                 dist::Docs { host: b },
1541                 dist::Docs { host: c },
1542             ]
1543         );
1544         assert_eq!(
1545             first(builder.cache.all::<dist::Mingw>()),
1546             &[
1547                 dist::Mingw { host: a },
1548                 dist::Mingw { host: b },
1549                 dist::Mingw { host: c },
1550             ]
1551         );
1552         assert_eq!(
1553             first(builder.cache.all::<dist::Rustc>()),
1554             &[
1555                 dist::Rustc {
1556                     compiler: Compiler { host: a, stage: 2 }
1557                 },
1558                 dist::Rustc {
1559                     compiler: Compiler { host: b, stage: 2 }
1560                 },
1561             ]
1562         );
1563         assert_eq!(
1564             first(builder.cache.all::<dist::Std>()),
1565             &[
1566                 dist::Std {
1567                     compiler: Compiler { host: a, stage: 1 },
1568                     target: a,
1569                 },
1570                 dist::Std {
1571                     compiler: Compiler { host: a, stage: 1 },
1572                     target: b,
1573                 },
1574                 dist::Std {
1575                     compiler: Compiler { host: a, stage: 2 },
1576                     target: c,
1577                 },
1578             ]
1579         );
1580         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1581     }
1582
1583     #[test]
1584     fn dist_with_target_flag() {
1585         let mut config = configure(&["B"], &["C"]);
1586         config.run_host_only = false; // as-if --target=C was passed
1587         let build = Build::new(config);
1588         let mut builder = Builder::new(&build);
1589         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1590
1591         let a = INTERNER.intern_str("A");
1592         let b = INTERNER.intern_str("B");
1593         let c = INTERNER.intern_str("C");
1594
1595         assert_eq!(
1596             first(builder.cache.all::<dist::Docs>()),
1597             &[
1598                 dist::Docs { host: a },
1599                 dist::Docs { host: b },
1600                 dist::Docs { host: c },
1601             ]
1602         );
1603         assert_eq!(
1604             first(builder.cache.all::<dist::Mingw>()),
1605             &[
1606                 dist::Mingw { host: a },
1607                 dist::Mingw { host: b },
1608                 dist::Mingw { host: c },
1609             ]
1610         );
1611         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1612         assert_eq!(
1613             first(builder.cache.all::<dist::Std>()),
1614             &[
1615                 dist::Std {
1616                     compiler: Compiler { host: a, stage: 1 },
1617                     target: a,
1618                 },
1619                 dist::Std {
1620                     compiler: Compiler { host: a, stage: 1 },
1621                     target: b,
1622                 },
1623                 dist::Std {
1624                     compiler: Compiler { host: a, stage: 2 },
1625                     target: c,
1626                 },
1627             ]
1628         );
1629         assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1630     }
1631
1632     #[test]
1633     fn dist_with_same_targets_and_hosts() {
1634         let build = Build::new(configure(&["B"], &["B"]));
1635         let mut builder = Builder::new(&build);
1636         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1637
1638         let a = INTERNER.intern_str("A");
1639         let b = INTERNER.intern_str("B");
1640
1641         assert_eq!(
1642             first(builder.cache.all::<dist::Docs>()),
1643             &[
1644                 dist::Docs { host: a },
1645                 dist::Docs { host: b },
1646             ]
1647         );
1648         assert_eq!(
1649             first(builder.cache.all::<dist::Mingw>()),
1650             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1651         );
1652         assert_eq!(
1653             first(builder.cache.all::<dist::Rustc>()),
1654             &[
1655                 dist::Rustc {
1656                     compiler: Compiler { host: a, stage: 2 }
1657                 },
1658                 dist::Rustc {
1659                     compiler: Compiler { host: b, stage: 2 }
1660                 },
1661             ]
1662         );
1663         assert_eq!(
1664             first(builder.cache.all::<dist::Std>()),
1665             &[
1666                 dist::Std {
1667                     compiler: Compiler { host: a, stage: 1 },
1668                     target: a,
1669                 },
1670                 dist::Std {
1671                     compiler: Compiler { host: a, stage: 1 },
1672                     target: b,
1673                 },
1674             ]
1675         );
1676         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1677         assert_eq!(
1678             first(builder.cache.all::<compile::Std>()),
1679             &[
1680                 compile::Std {
1681                     compiler: Compiler { host: a, stage: 0 },
1682                     target: a,
1683                 },
1684                 compile::Std {
1685                     compiler: Compiler { host: a, stage: 1 },
1686                     target: a,
1687                 },
1688                 compile::Std {
1689                     compiler: Compiler { host: a, stage: 2 },
1690                     target: a,
1691                 },
1692                 compile::Std {
1693                     compiler: Compiler { host: a, stage: 1 },
1694                     target: b,
1695                 },
1696                 compile::Std {
1697                     compiler: Compiler { host: a, stage: 2 },
1698                     target: b,
1699                 },
1700             ]
1701         );
1702         assert_eq!(
1703             first(builder.cache.all::<compile::Test>()),
1704             &[
1705                 compile::Test {
1706                     compiler: Compiler { host: a, stage: 0 },
1707                     target: a,
1708                 },
1709                 compile::Test {
1710                     compiler: Compiler { host: a, stage: 1 },
1711                     target: a,
1712                 },
1713                 compile::Test {
1714                     compiler: Compiler { host: a, stage: 2 },
1715                     target: a,
1716                 },
1717                 compile::Test {
1718                     compiler: Compiler { host: a, stage: 1 },
1719                     target: b,
1720                 },
1721             ]
1722         );
1723         assert_eq!(
1724             first(builder.cache.all::<compile::Assemble>()),
1725             &[
1726                 compile::Assemble {
1727                     target_compiler: Compiler { host: a, stage: 0 },
1728                 },
1729                 compile::Assemble {
1730                     target_compiler: Compiler { host: a, stage: 1 },
1731                 },
1732                 compile::Assemble {
1733                     target_compiler: Compiler { host: a, stage: 2 },
1734                 },
1735                 compile::Assemble {
1736                     target_compiler: Compiler { host: b, stage: 2 },
1737                 },
1738             ]
1739         );
1740     }
1741
1742     #[test]
1743     fn build_default() {
1744         let build = Build::new(configure(&["B"], &["C"]));
1745         let mut builder = Builder::new(&build);
1746         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1747
1748         let a = INTERNER.intern_str("A");
1749         let b = INTERNER.intern_str("B");
1750         let c = INTERNER.intern_str("C");
1751
1752         assert!(!builder.cache.all::<compile::Std>().is_empty());
1753         assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1754         assert_eq!(
1755             first(builder.cache.all::<compile::Rustc>()),
1756             &[
1757                 compile::Rustc {
1758                     compiler: Compiler { host: a, stage: 0 },
1759                     target: a,
1760                 },
1761                 compile::Rustc {
1762                     compiler: Compiler { host: a, stage: 1 },
1763                     target: a,
1764                 },
1765                 compile::Rustc {
1766                     compiler: Compiler { host: a, stage: 2 },
1767                     target: a,
1768                 },
1769                 compile::Rustc {
1770                     compiler: Compiler { host: b, stage: 2 },
1771                     target: a,
1772                 },
1773                 compile::Rustc {
1774                     compiler: Compiler { host: a, stage: 1 },
1775                     target: b,
1776                 },
1777                 compile::Rustc {
1778                     compiler: Compiler { host: a, stage: 2 },
1779                     target: b,
1780                 },
1781                 compile::Rustc {
1782                     compiler: Compiler { host: b, stage: 2 },
1783                     target: b,
1784                 },
1785             ]
1786         );
1787
1788         assert_eq!(
1789             first(builder.cache.all::<compile::Test>()),
1790             &[
1791                 compile::Test {
1792                     compiler: Compiler { host: a, stage: 0 },
1793                     target: a,
1794                 },
1795                 compile::Test {
1796                     compiler: Compiler { host: a, stage: 1 },
1797                     target: a,
1798                 },
1799                 compile::Test {
1800                     compiler: Compiler { host: a, stage: 2 },
1801                     target: a,
1802                 },
1803                 compile::Test {
1804                     compiler: Compiler { host: b, stage: 2 },
1805                     target: a,
1806                 },
1807                 compile::Test {
1808                     compiler: Compiler { host: a, stage: 1 },
1809                     target: b,
1810                 },
1811                 compile::Test {
1812                     compiler: Compiler { host: a, stage: 2 },
1813                     target: b,
1814                 },
1815                 compile::Test {
1816                     compiler: Compiler { host: b, stage: 2 },
1817                     target: b,
1818                 },
1819                 compile::Test {
1820                     compiler: Compiler { host: a, stage: 2 },
1821                     target: c,
1822                 },
1823                 compile::Test {
1824                     compiler: Compiler { host: b, stage: 2 },
1825                     target: c,
1826                 },
1827             ]
1828         );
1829     }
1830
1831     #[test]
1832     fn build_with_target_flag() {
1833         let mut config = configure(&["B"], &["C"]);
1834         config.run_host_only = false;
1835         let build = Build::new(config);
1836         let mut builder = Builder::new(&build);
1837         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1838
1839         let a = INTERNER.intern_str("A");
1840         let b = INTERNER.intern_str("B");
1841         let c = INTERNER.intern_str("C");
1842
1843         assert!(!builder.cache.all::<compile::Std>().is_empty());
1844         assert_eq!(
1845             first(builder.cache.all::<compile::Assemble>()),
1846             &[
1847                 compile::Assemble {
1848                     target_compiler: Compiler { host: a, stage: 0 },
1849                 },
1850                 compile::Assemble {
1851                     target_compiler: Compiler { host: a, stage: 1 },
1852                 },
1853                 compile::Assemble {
1854                     target_compiler: Compiler { host: a, stage: 2 },
1855                 },
1856                 compile::Assemble {
1857                     target_compiler: Compiler { host: b, stage: 2 },
1858                 },
1859             ]
1860         );
1861         assert_eq!(
1862             first(builder.cache.all::<compile::Rustc>()),
1863             &[
1864                 compile::Rustc {
1865                     compiler: Compiler { host: a, stage: 0 },
1866                     target: a,
1867                 },
1868                 compile::Rustc {
1869                     compiler: Compiler { host: a, stage: 1 },
1870                     target: a,
1871                 },
1872                 compile::Rustc {
1873                     compiler: Compiler { host: a, stage: 1 },
1874                     target: b,
1875                 },
1876             ]
1877         );
1878
1879         assert_eq!(
1880             first(builder.cache.all::<compile::Test>()),
1881             &[
1882                 compile::Test {
1883                     compiler: Compiler { host: a, stage: 0 },
1884                     target: a,
1885                 },
1886                 compile::Test {
1887                     compiler: Compiler { host: a, stage: 1 },
1888                     target: a,
1889                 },
1890                 compile::Test {
1891                     compiler: Compiler { host: a, stage: 2 },
1892                     target: a,
1893                 },
1894                 compile::Test {
1895                     compiler: Compiler { host: b, stage: 2 },
1896                     target: a,
1897                 },
1898                 compile::Test {
1899                     compiler: Compiler { host: a, stage: 1 },
1900                     target: b,
1901                 },
1902                 compile::Test {
1903                     compiler: Compiler { host: a, stage: 2 },
1904                     target: b,
1905                 },
1906                 compile::Test {
1907                     compiler: Compiler { host: b, stage: 2 },
1908                     target: b,
1909                 },
1910                 compile::Test {
1911                     compiler: Compiler { host: a, stage: 2 },
1912                     target: c,
1913                 },
1914                 compile::Test {
1915                     compiler: Compiler { host: b, stage: 2 },
1916                     target: c,
1917                 },
1918             ]
1919         );
1920     }
1921
1922     #[test]
1923     fn test_with_no_doc_stage0() {
1924         let mut config = configure(&[], &[]);
1925         config.stage = Some(0);
1926         config.cmd = Subcommand::Test {
1927             paths: vec!["src/libstd".into()],
1928             test_args: vec![],
1929             rustc_args: vec![],
1930             fail_fast: true,
1931             doc_tests: DocTests::No,
1932             bless: false,
1933             compare_mode: None,
1934             rustfix_coverage: false,
1935         };
1936
1937         let build = Build::new(config);
1938         let mut builder = Builder::new(&build);
1939
1940         let host = INTERNER.intern_str("A");
1941
1942         builder.run_step_descriptions(
1943             &[StepDescription::from::<test::Crate>()],
1944             &["src/libstd".into()],
1945         );
1946
1947         // Ensure we don't build any compiler artifacts.
1948         assert!(!builder.cache.contains::<compile::Rustc>());
1949         assert_eq!(
1950             first(builder.cache.all::<test::Crate>()),
1951             &[test::Crate {
1952                 compiler: Compiler { host, stage: 0 },
1953                 target: host,
1954                 mode: Mode::Std,
1955                 test_kind: test::TestKind::Test,
1956                 krate: INTERNER.intern_str("std"),
1957             },]
1958         );
1959     }
1960
1961     #[test]
1962     fn test_exclude() {
1963         let mut config = configure(&[], &[]);
1964         config.exclude = vec![
1965             "src/test/run-pass".into(),
1966             "src/tools/tidy".into(),
1967         ];
1968         config.cmd = Subcommand::Test {
1969             paths: Vec::new(),
1970             test_args: Vec::new(),
1971             rustc_args: Vec::new(),
1972             fail_fast: true,
1973             doc_tests: DocTests::No,
1974             bless: false,
1975             compare_mode: None,
1976             rustfix_coverage: false,
1977         };
1978
1979         let build = Build::new(config);
1980         let builder = Builder::new(&build);
1981         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Test), &[]);
1982
1983         // Ensure we have really excluded run-pass & tidy
1984         assert!(!builder.cache.contains::<test::RunPass>());
1985         assert!(!builder.cache.contains::<test::Tidy>());
1986
1987         // Ensure other tests are not affected.
1988         assert!(builder.cache.contains::<test::RunPassFullDeps>());
1989         assert!(builder.cache.contains::<test::RustdocUi>());
1990     }
1991 }