]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
408e61ef548691dd4523f4babc7d52b5d0f320ea
[rust.git] / src / bootstrap / builder.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::any::Any;
12 use std::cell::{Cell, RefCell};
13 use std::collections::BTreeSet;
14 use std::env;
15 use std::fmt::Debug;
16 use std::fs;
17 use std::hash::Hash;
18 use std::ops::Deref;
19 use std::path::{Path, PathBuf};
20 use std::process::Command;
21 use std::time::{Instant, Duration};
22 use std::collections::HashMap;
23
24 use compile;
25 use install;
26 use dist;
27 use util::{exe, libdir, add_lib_path};
28 use {Build, Mode, DocTestsOption};
29 use cache::{INTERNER, Interned, Cache};
30 use check;
31 use test;
32 use flags::Subcommand;
33 use doc;
34 use tool;
35 use native;
36
37 pub use Compiler;
38
39 use petgraph::Graph;
40 use petgraph::graph::NodeIndex;
41
42 pub struct Builder<'a> {
43     pub build: &'a Build,
44     pub top_stage: u32,
45     pub kind: Kind,
46     cache: Cache,
47     stack: RefCell<Vec<Box<Any>>>,
48     time_spent_on_dependencies: Cell<Duration>,
49     pub paths: Vec<PathBuf>,
50     graph_nodes: RefCell<HashMap<String, NodeIndex>>,
51     graph: RefCell<Graph<String, bool>>,
52     parent: Cell<Option<NodeIndex>>,
53 }
54
55 impl<'a> Deref for Builder<'a> {
56     type Target = Build;
57
58     fn deref(&self) -> &Self::Target {
59         self.build
60     }
61 }
62
63 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
64     /// `PathBuf` when directories are created or to return a `Compiler` once
65     /// it's been assembled.
66     type Output: Clone;
67
68     const DEFAULT: bool = false;
69
70     /// Run this rule for all hosts without cross compiling.
71     const ONLY_HOSTS: bool = false;
72
73     /// Primary function to execute this rule. Can call `builder.ensure(...)`
74     /// with other steps to run those.
75     fn run(self, builder: &Builder) -> Self::Output;
76
77     /// When bootstrap is passed a set of paths, this controls whether this rule
78     /// will execute. However, it does not get called in a "default" context
79     /// when we are not passed any paths; in that case, make_run is called
80     /// directly.
81     fn should_run(run: ShouldRun) -> ShouldRun;
82
83     /// Build up a "root" rule, either as a default rule or from a path passed
84     /// to us.
85     ///
86     /// When path is `None`, we are executing in a context where no paths were
87     /// passed. When `./x.py build` is run, for example, this rule could get
88     /// called if it is in the correct list below with a path of `None`.
89     fn make_run(_run: RunConfig) {
90         // It is reasonable to not have an implementation of make_run for rules
91         // who do not want to get called from the root context. This means that
92         // they are likely dependencies (e.g., sysroot creation) or similar, and
93         // as such calling them from ./x.py isn't logical.
94         unimplemented!()
95     }
96 }
97
98 pub struct RunConfig<'a> {
99     pub builder: &'a Builder<'a>,
100     pub host: Interned<String>,
101     pub target: Interned<String>,
102     pub path: PathBuf,
103 }
104
105 struct StepDescription {
106     default: bool,
107     only_hosts: bool,
108     should_run: fn(ShouldRun) -> ShouldRun,
109     make_run: fn(RunConfig),
110     name: &'static str,
111 }
112
113 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
114 struct PathSet {
115     set: BTreeSet<PathBuf>,
116 }
117
118 impl PathSet {
119     fn empty() -> PathSet {
120         PathSet { set: BTreeSet::new() }
121     }
122
123     fn one<P: Into<PathBuf>>(path: P) -> PathSet {
124         let mut set = BTreeSet::new();
125         set.insert(path.into());
126         PathSet { set }
127     }
128
129     fn has(&self, needle: &Path) -> bool {
130         self.set.iter().any(|p| p.ends_with(needle))
131     }
132
133     fn path(&self, builder: &Builder) -> PathBuf {
134         self.set.iter().next().unwrap_or(&builder.build.src).to_path_buf()
135     }
136 }
137
138 impl StepDescription {
139     fn from<S: Step>() -> StepDescription {
140         StepDescription {
141             default: S::DEFAULT,
142             only_hosts: S::ONLY_HOSTS,
143             should_run: S::should_run,
144             make_run: S::make_run,
145             name: unsafe { ::std::intrinsics::type_name::<S>() },
146         }
147     }
148
149     fn maybe_run(&self, builder: &Builder, pathset: &PathSet) {
150         if builder.config.exclude.iter().any(|e| pathset.has(e)) {
151             eprintln!("Skipping {:?} because it is excluded", pathset);
152             return;
153         } else if !builder.config.exclude.is_empty() {
154             eprintln!("{:?} not skipped for {:?} -- not in {:?}", pathset,
155                 self.name, builder.config.exclude);
156         }
157         let hosts = &builder.hosts;
158
159         // Determine the targets participating in this rule.
160         let targets = if self.only_hosts {
161             if !builder.config.run_host_only {
162                 return; // don't run anything
163             } else {
164                 &builder.hosts
165             }
166         } else {
167             &builder.targets
168         };
169
170         for host in hosts {
171             for target in targets {
172                 let run = RunConfig {
173                     builder,
174                     path: pathset.path(builder),
175                     host: *host,
176                     target: *target,
177                 };
178                 (self.make_run)(run);
179             }
180         }
181     }
182
183     fn run(v: &[StepDescription], builder: &Builder, paths: &[PathBuf]) {
184         let should_runs = v.iter().map(|desc| {
185             (desc.should_run)(ShouldRun::new(builder))
186         }).collect::<Vec<_>>();
187
188         // sanity checks on rules
189         for (desc, should_run) in v.iter().zip(&should_runs) {
190             assert!(!should_run.paths.is_empty(),
191                 "{:?} should have at least one pathset", desc.name);
192         }
193
194         if paths.is_empty() {
195             for (desc, should_run) in v.iter().zip(should_runs) {
196                 if desc.default && should_run.is_really_default {
197                     for pathset in &should_run.paths {
198                         desc.maybe_run(builder, pathset);
199                     }
200                 }
201             }
202         } else {
203             for path in paths {
204                 let mut attempted_run = false;
205                 for (desc, should_run) in v.iter().zip(&should_runs) {
206                     if let Some(pathset) = should_run.pathset_for_path(path) {
207                         attempted_run = true;
208                         desc.maybe_run(builder, pathset);
209                     }
210                 }
211
212                 if !attempted_run {
213                     panic!("Error: no rules matched {}.", path.display());
214                 }
215             }
216         }
217     }
218 }
219
220 #[derive(Clone)]
221 pub struct ShouldRun<'a> {
222     pub builder: &'a Builder<'a>,
223     // use a BTreeSet to maintain sort order
224     paths: BTreeSet<PathSet>,
225
226     // If this is a default rule, this is an additional constraint placed on
227     // its run. Generally something like compiler docs being enabled.
228     is_really_default: bool,
229 }
230
231 impl<'a> ShouldRun<'a> {
232     fn new(builder: &'a Builder) -> ShouldRun<'a> {
233         ShouldRun {
234             builder,
235             paths: BTreeSet::new(),
236             is_really_default: true, // by default no additional conditions
237         }
238     }
239
240     pub fn default_condition(mut self, cond: bool) -> Self {
241         self.is_really_default = cond;
242         self
243     }
244
245     // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
246     // ever be used, but as we transition to having all rules properly handle passing krate(...) by
247     // actually doing something different for every crate passed.
248     pub fn all_krates(mut self, name: &str) -> Self {
249         let mut set = BTreeSet::new();
250         for krate in self.builder.in_tree_crates(name) {
251             set.insert(PathBuf::from(&krate.path));
252         }
253         self.paths.insert(PathSet { set });
254         self
255     }
256
257     pub fn krate(mut self, name: &str) -> Self {
258         for krate in self.builder.in_tree_crates(name) {
259             self.paths.insert(PathSet::one(&krate.path));
260         }
261         self
262     }
263
264     // single, non-aliased path
265     pub fn path(self, path: &str) -> Self {
266         self.paths(&[path])
267     }
268
269     // multiple aliases for the same job
270     pub fn paths(mut self, paths: &[&str]) -> Self {
271         self.paths.insert(PathSet {
272             set: paths.iter().map(PathBuf::from).collect(),
273         });
274         self
275     }
276
277     // allows being more explicit about why should_run in Step returns the value passed to it
278     pub fn never(mut self) -> ShouldRun<'a> {
279         self.paths.insert(PathSet::empty());
280         self
281     }
282
283     fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
284         self.paths.iter().find(|pathset| pathset.has(path))
285     }
286 }
287
288 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
289 pub enum Kind {
290     Build,
291     Check,
292     Test,
293     Bench,
294     Dist,
295     Doc,
296     Install,
297 }
298
299 impl<'a> Builder<'a> {
300     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
301         macro_rules! describe {
302             ($($rule:ty),+ $(,)*) => {{
303                 vec![$(StepDescription::from::<$rule>()),+]
304             }};
305         }
306         match kind {
307             Kind::Build => describe!(compile::Std, compile::Test, compile::Rustc,
308                 compile::StartupObjects, tool::BuildManifest, tool::Rustbook, tool::ErrorIndex,
309                 tool::UnstableBookGen, tool::Tidy, tool::Linkchecker, tool::CargoTest,
310                 tool::Compiletest, tool::RemoteTestServer, tool::RemoteTestClient,
311                 tool::RustInstaller, tool::Cargo, tool::Rls, tool::Rustdoc, tool::Clippy,
312                 native::Llvm, tool::Rustfmt, tool::Miri, native::Lld),
313             Kind::Check => describe!(check::Std, check::Test, check::Rustc, check::CodegenBackend,
314                 check::Rustdoc),
315             Kind::Test => describe!(test::Tidy, test::Bootstrap, test::Ui, test::RunPass,
316                 test::CompileFail, test::ParseFail, test::RunFail, test::RunPassValgrind,
317                 test::MirOpt, test::Codegen, test::CodegenUnits, test::Incremental, test::Debuginfo,
318                 test::UiFullDeps, test::RunPassFullDeps, test::RunFailFullDeps,
319                 test::CompileFailFullDeps, test::IncrementalFullDeps, test::Rustdoc, test::Pretty,
320                 test::RunPassPretty, test::RunFailPretty, test::RunPassValgrindPretty,
321                 test::RunPassFullDepsPretty, test::RunFailFullDepsPretty,
322                 test::Crate, test::CrateLibrustc, test::CrateRustdoc, test::Linkcheck,
323                 test::Cargotest, test::Cargo, test::Rls, test::ErrorIndex, test::Distcheck,
324                 test::RunMakeFullDeps,
325                 test::Nomicon, test::Reference, test::RustdocBook, test::RustByExample,
326                 test::TheBook, test::UnstableBook, test::RustcBook,
327                 test::Rustfmt, test::Miri, test::Clippy, test::RustdocJS, test::RustdocTheme,
328                 // Run run-make last, since these won't pass without make on Windows
329                 test::RunMake, test::RustdocUi),
330             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
331             Kind::Doc => describe!(doc::UnstableBook, doc::UnstableBookGen, doc::TheBook,
332                 doc::Standalone, doc::Std, doc::Test, doc::WhitelistedRustc, doc::Rustc,
333                 doc::ErrorIndex, doc::Nomicon, doc::Reference, doc::Rustdoc, doc::RustByExample,
334                 doc::RustcBook, doc::CargoBook),
335             Kind::Dist => describe!(dist::Docs, dist::RustcDocs, dist::Mingw, dist::Rustc,
336                 dist::DebuggerScripts, dist::Std, dist::Analysis, dist::Src,
337                 dist::PlainSourceTarball, dist::Cargo, dist::Rls, dist::Rustfmt, dist::Extended,
338                 dist::HashSign),
339             Kind::Install => describe!(install::Docs, install::Std, install::Cargo, install::Rls,
340                 install::Rustfmt, install::Analysis, install::Src, install::Rustc),
341         }
342     }
343
344     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
345         let kind = match subcommand {
346             "build" => Kind::Build,
347             "doc" => Kind::Doc,
348             "test" => Kind::Test,
349             "bench" => Kind::Bench,
350             "dist" => Kind::Dist,
351             "install" => Kind::Install,
352             _ => return None,
353         };
354
355         let builder = Builder {
356             build,
357             top_stage: build.config.stage.unwrap_or(2),
358             kind,
359             cache: Cache::new(),
360             stack: RefCell::new(Vec::new()),
361             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
362             paths: vec![],
363             graph_nodes: RefCell::new(HashMap::new()),
364             graph: RefCell::new(Graph::new()),
365             parent: Cell::new(None),
366         };
367
368         let builder = &builder;
369         let mut should_run = ShouldRun::new(builder);
370         for desc in Builder::get_step_descriptions(builder.kind) {
371             should_run = (desc.should_run)(should_run);
372         }
373         let mut help = String::from("Available paths:\n");
374         for pathset in should_run.paths {
375             for path in pathset.set {
376                 help.push_str(format!("    ./x.py {} {}\n", subcommand, path.display()).as_str());
377             }
378         }
379         Some(help)
380     }
381
382     pub fn new(build: &Build) -> Builder {
383         let (kind, paths) = match build.config.cmd {
384             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
385             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
386             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
387             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
388             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
389             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
390             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
391             Subcommand::Clean { .. } => panic!(),
392         };
393
394         let builder = Builder {
395             build,
396             top_stage: build.config.stage.unwrap_or(2),
397             kind,
398             cache: Cache::new(),
399             stack: RefCell::new(Vec::new()),
400             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
401             paths: paths.to_owned(),
402             graph_nodes: RefCell::new(HashMap::new()),
403             graph: RefCell::new(Graph::new()),
404             parent: Cell::new(None),
405         };
406
407         if kind == Kind::Dist {
408             assert!(!builder.config.test_miri, "Do not distribute with miri enabled.\n\
409                 The distributed libraries would include all MIR (increasing binary size).
410                 The distributed MIR would include validation statements.");
411         }
412
413         builder
414     }
415
416     pub fn execute_cli(&self) -> Graph<String, bool> {
417         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
418         self.graph.borrow().clone()
419     }
420
421     pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
422         let paths = paths.unwrap_or(&[]);
423         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
424     }
425
426     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
427         StepDescription::run(v, self, paths);
428     }
429
430     /// Obtain a compiler at a given stage and for a given host. Explicitly does
431     /// not take `Compiler` since all `Compiler` instances are meant to be
432     /// obtained through this function, since it ensures that they are valid
433     /// (i.e., built and assembled).
434     pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
435         self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
436     }
437
438     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
439         self.ensure(compile::Sysroot { compiler })
440     }
441
442     /// Returns the libdir where the standard library and other artifacts are
443     /// found for a compiler's sysroot.
444     pub fn sysroot_libdir(
445         &self, compiler: Compiler, target: Interned<String>
446     ) -> Interned<PathBuf> {
447         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
448         struct Libdir {
449             compiler: Compiler,
450             target: Interned<String>,
451         }
452         impl Step for Libdir {
453             type Output = Interned<PathBuf>;
454
455             fn should_run(run: ShouldRun) -> ShouldRun {
456                 run.never()
457             }
458
459             fn run(self, builder: &Builder) -> Interned<PathBuf> {
460                 let compiler = self.compiler;
461                 let config = &builder.build.config;
462                 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
463                     builder.build.config.libdir_relative().unwrap()
464                 } else {
465                     Path::new("lib")
466                 };
467                 let sysroot = builder.sysroot(self.compiler).join(lib)
468                     .join("rustlib").join(self.target).join("lib");
469                 let _ = fs::remove_dir_all(&sysroot);
470                 t!(fs::create_dir_all(&sysroot));
471                 INTERNER.intern_path(sysroot)
472             }
473         }
474         self.ensure(Libdir { compiler, target })
475     }
476
477     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
478         self.sysroot_libdir(compiler, compiler.host)
479             .with_file_name(self.config.rust_codegen_backends_dir.clone())
480     }
481
482     /// Returns the compiler's libdir where it stores the dynamic libraries that
483     /// it itself links against.
484     ///
485     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
486     /// Windows.
487     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
488         if compiler.is_snapshot(self) {
489             self.rustc_snapshot_libdir()
490         } else {
491             self.sysroot(compiler).join(libdir(&compiler.host))
492         }
493     }
494
495     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
496     /// library lookup path.
497     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
498         // Windows doesn't need dylib path munging because the dlls for the
499         // compiler live next to the compiler and the system will find them
500         // automatically.
501         if cfg!(windows) {
502             return
503         }
504
505         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
506     }
507
508     /// Get a path to the compiler specified.
509     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
510         if compiler.is_snapshot(self) {
511             self.initial_rustc.clone()
512         } else {
513             self.sysroot(compiler).join("bin").join(exe("rustc", &compiler.host))
514         }
515     }
516
517     pub fn rustdoc(&self, host: Interned<String>) -> PathBuf {
518         self.ensure(tool::Rustdoc { host })
519     }
520
521     pub fn rustdoc_cmd(&self, host: Interned<String>) -> Command {
522         let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
523         let compiler = self.compiler(self.top_stage, host);
524         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
525            .env("RUSTC_SYSROOT", self.sysroot(compiler))
526            .env("RUSTDOC_LIBDIR", self.sysroot_libdir(compiler, self.config.build))
527            .env("CFG_RELEASE_CHANNEL", &self.config.channel)
528            .env("RUSTDOC_REAL", self.rustdoc(host))
529            .env("RUSTDOC_CRATE_VERSION", self.rust_version())
530            .env("RUSTC_BOOTSTRAP", "1");
531         if let Some(linker) = self.linker(host) {
532             cmd.env("RUSTC_TARGET_LINKER", linker);
533         }
534         cmd
535     }
536
537     /// Prepares an invocation of `cargo` to be run.
538     ///
539     /// This will create a `Command` that represents a pending execution of
540     /// Cargo. This cargo will be configured to use `compiler` as the actual
541     /// rustc compiler, its output will be scoped by `mode`'s output directory,
542     /// it will pass the `--target` flag for the specified `target`, and will be
543     /// executing the Cargo command `cmd`.
544     pub fn cargo(&self,
545              compiler: Compiler,
546              mode: Mode,
547              target: Interned<String>,
548              cmd: &str) -> Command {
549         let mut cargo = Command::new(&self.initial_cargo);
550         let out_dir = self.stage_out(compiler, mode);
551         cargo.env("CARGO_TARGET_DIR", out_dir)
552              .arg(cmd)
553              .arg("--target")
554              .arg(target);
555
556         // Set a flag for `check` so that certain build scripts can do less work
557         // (e.g. not building/requiring LLVM).
558         if cmd == "check" {
559             cargo.env("RUST_CHECK", "1");
560         }
561
562         // If we were invoked from `make` then that's already got a jobserver
563         // set up for us so no need to tell Cargo about jobs all over again.
564         if env::var_os("MAKEFLAGS").is_none() && env::var_os("MFLAGS").is_none() {
565              cargo.arg("-j").arg(self.jobs().to_string());
566         }
567
568         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
569         // Force cargo to output binaries with disambiguating hashes in the name
570         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &self.config.channel);
571
572         let stage;
573         if compiler.stage == 0 && self.local_rebuild {
574             // Assume the local-rebuild rustc already has stage1 features.
575             stage = 1;
576         } else {
577             stage = compiler.stage;
578         }
579
580         let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
581         if stage != 0 {
582             let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
583             if !extra_args.is_empty() {
584                 extra_args.push_str(" ");
585             }
586             extra_args.push_str(&s);
587         }
588
589         if !extra_args.is_empty() {
590             cargo.env("RUSTFLAGS",
591                 format!("{} {}", env::var("RUSTFLAGS").unwrap_or_default(), extra_args));
592         }
593
594         let want_rustdoc = self.doc_tests != DocTestsOption::No;
595
596         // Customize the compiler we're running. Specify the compiler to cargo
597         // as our shim and then pass it some various options used to configure
598         // how the actual compiler itself is called.
599         //
600         // These variables are primarily all read by
601         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
602         cargo.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
603              .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
604              .env("RUSTC_REAL", self.rustc(compiler))
605              .env("RUSTC_STAGE", stage.to_string())
606              .env("RUSTC_DEBUG_ASSERTIONS",
607                   self.config.rust_debug_assertions.to_string())
608              .env("RUSTC_SYSROOT", self.sysroot(compiler))
609              .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
610              .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
611              .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
612              .env("RUSTDOC_REAL", if cmd == "doc" || (cmd == "test" && want_rustdoc) {
613                  self.rustdoc(compiler.host)
614              } else {
615                  PathBuf::from("/path/to/nowhere/rustdoc/not/required")
616              })
617              .env("TEST_MIRI", self.config.test_miri.to_string())
618              .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
619
620         if let Some(host_linker) = self.linker(compiler.host) {
621             cargo.env("RUSTC_HOST_LINKER", host_linker);
622         }
623         if let Some(target_linker) = self.linker(target) {
624             cargo.env("RUSTC_TARGET_LINKER", target_linker);
625         }
626         if let Some(ref error_format) = self.config.rustc_error_format {
627             cargo.env("RUSTC_ERROR_FORMAT", error_format);
628         }
629         if cmd != "build" && cmd != "check" && want_rustdoc {
630             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(self.compiler(2, self.config.build)));
631         }
632
633         if mode == Mode::Tool {
634             // Tools like cargo and rls don't get debuginfo by default right now, but this can be
635             // enabled in the config.  Adding debuginfo makes them several times larger.
636             if self.config.rust_debuginfo_tools {
637                 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
638                 cargo.env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string());
639             }
640         } else {
641             cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
642             cargo.env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string());
643             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
644
645             // Currently the compiler depends on crates from crates.io, and
646             // then other crates can depend on the compiler (e.g. proc-macro
647             // crates). Let's say, for example that rustc itself depends on the
648             // bitflags crate. If an external crate then depends on the
649             // bitflags crate as well, we need to make sure they don't
650             // conflict, even if they pick the same version of bitflags. We'll
651             // want to make sure that e.g. a plugin and rustc each get their
652             // own copy of bitflags.
653
654             // Cargo ensures that this works in general through the -C metadata
655             // flag. This flag will frob the symbols in the binary to make sure
656             // they're different, even though the source code is the exact
657             // same. To solve this problem for the compiler we extend Cargo's
658             // already-passed -C metadata flag with our own. Our rustc.rs
659             // wrapper around the actual rustc will detect -C metadata being
660             // passed and frob it with this extra string we're passing in.
661             cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
662         }
663
664         if let Some(x) = self.crt_static(target) {
665             cargo.env("RUSTC_CRT_STATIC", x.to_string());
666         }
667
668         // Enable usage of unstable features
669         cargo.env("RUSTC_BOOTSTRAP", "1");
670         self.add_rust_test_threads(&mut cargo);
671
672         // Almost all of the crates that we compile as part of the bootstrap may
673         // have a build script, including the standard library. To compile a
674         // build script, however, it itself needs a standard library! This
675         // introduces a bit of a pickle when we're compiling the standard
676         // library itself.
677         //
678         // To work around this we actually end up using the snapshot compiler
679         // (stage0) for compiling build scripts of the standard library itself.
680         // The stage0 compiler is guaranteed to have a libstd available for use.
681         //
682         // For other crates, however, we know that we've already got a standard
683         // library up and running, so we can use the normal compiler to compile
684         // build scripts in that situation.
685         //
686         // If LLVM support is disabled we need to use the snapshot compiler to compile
687         // build scripts, as the new compiler doesn't support executables.
688         if mode == Mode::Libstd || !self.config.llvm_enabled {
689             cargo.env("RUSTC_SNAPSHOT", &self.initial_rustc)
690                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
691         } else {
692             cargo.env("RUSTC_SNAPSHOT", self.rustc(compiler))
693                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
694         }
695
696         // Ignore incremental modes except for stage0, since we're
697         // not guaranteeing correctness across builds if the compiler
698         // is changing under your feet.`
699         if self.config.incremental && compiler.stage == 0 {
700             cargo.env("CARGO_INCREMENTAL", "1");
701         }
702
703         if let Some(ref on_fail) = self.config.on_fail {
704             cargo.env("RUSTC_ON_FAIL", on_fail);
705         }
706
707         if self.config.print_step_timings {
708             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
709         }
710
711         cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity));
712
713         // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful.
714         if self.config.deny_warnings && !(mode == Mode::Libstd && stage == 0) {
715             cargo.env("RUSTC_DENY_WARNINGS", "1");
716         }
717
718         // Throughout the build Cargo can execute a number of build scripts
719         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
720         // obtained previously to those build scripts.
721         // Build scripts use either the `cc` crate or `configure/make` so we pass
722         // the options through environment variables that are fetched and understood by both.
723         //
724         // FIXME: the guard against msvc shouldn't need to be here
725         if !target.contains("msvc") {
726             let ccache = self.config.ccache.as_ref();
727             let ccacheify = |s: &Path| {
728                 let ccache = match ccache {
729                     Some(ref s) => s,
730                     None => return s.display().to_string(),
731                 };
732                 // FIXME: the cc-rs crate only recognizes the literal strings
733                 // `ccache` and `sccache` when doing caching compilations, so we
734                 // mirror that here. It should probably be fixed upstream to
735                 // accept a new env var or otherwise work with custom ccache
736                 // vars.
737                 match &ccache[..] {
738                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
739                     _ => s.display().to_string(),
740                 }
741             };
742             let cc = ccacheify(&self.cc(target));
743             cargo.env(format!("CC_{}", target), &cc)
744                  .env("CC", &cc);
745
746             let cflags = self.cflags(target).join(" ");
747             cargo.env(format!("CFLAGS_{}", target), cflags.clone())
748                  .env("CFLAGS", cflags.clone());
749
750             if let Some(ar) = self.ar(target) {
751                 let ranlib = format!("{} s", ar.display());
752                 cargo.env(format!("AR_{}", target), ar)
753                      .env("AR", ar)
754                      .env(format!("RANLIB_{}", target), ranlib.clone())
755                      .env("RANLIB", ranlib);
756             }
757
758             if let Ok(cxx) = self.cxx(target) {
759                 let cxx = ccacheify(&cxx);
760                 cargo.env(format!("CXX_{}", target), &cxx)
761                      .env("CXX", &cxx)
762                      .env(format!("CXXFLAGS_{}", target), cflags.clone())
763                      .env("CXXFLAGS", cflags);
764             }
765         }
766
767         if cmd == "build" && mode == Mode::Libstd
768             && self.config.extended && compiler.is_final_stage(self)
769         {
770             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
771         }
772
773         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
774         cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
775
776         // Environment variables *required* throughout the build
777         //
778         // FIXME: should update code to not require this env var
779         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
780
781         // Set this for all builds to make sure doc builds also get it.
782         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
783
784         // This one's a bit tricky. As of the time of this writing the compiler
785         // links to the `winapi` crate on crates.io. This crate provides raw
786         // bindings to Windows system functions, sort of like libc does for
787         // Unix. This crate also, however, provides "import libraries" for the
788         // MinGW targets. There's an import library per dll in the windows
789         // distribution which is what's linked to. These custom import libraries
790         // are used because the winapi crate can reference Windows functions not
791         // present in the MinGW import libraries.
792         //
793         // For example MinGW may ship libdbghelp.a, but it may not have
794         // references to all the functions in the dbghelp dll. Instead the
795         // custom import library for dbghelp in the winapi crates has all this
796         // information.
797         //
798         // Unfortunately for us though the import libraries are linked by
799         // default via `-ldylib=winapi_foo`. That is, they're linked with the
800         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
801         // conflict with the system MinGW ones). This consequently means that
802         // the binaries we ship of things like rustc_trans (aka the rustc_trans
803         // DLL) when linked against *again*, for example with procedural macros
804         // or plugins, will trigger the propagation logic of `-ldylib`, passing
805         // `-lwinapi_foo` to the linker again. This isn't actually available in
806         // our distribution, however, so the link fails.
807         //
808         // To solve this problem we tell winapi to not use its bundled import
809         // libraries. This means that it will link to the system MinGW import
810         // libraries by default, and the `-ldylib=foo` directives will still get
811         // passed to the final linker, but they'll look like `-lfoo` which can
812         // be resolved because MinGW has the import library. The downside is we
813         // don't get newer functions from Windows, but we don't use any of them
814         // anyway.
815         if mode != Mode::Tool {
816             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
817         }
818
819         for _ in 1..self.verbosity {
820             cargo.arg("-v");
821         }
822
823         // This must be kept before the thinlto check, as we set codegen units
824         // to 1 forcibly there.
825         if let Some(n) = self.config.rust_codegen_units {
826             cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
827         }
828
829         if self.config.rust_optimize {
830             // FIXME: cargo bench does not accept `--release`
831             if cmd != "bench" {
832                 cargo.arg("--release");
833             }
834         }
835
836         if self.config.locked_deps {
837             cargo.arg("--locked");
838         }
839         if self.config.vendor || self.is_sudo {
840             cargo.arg("--frozen");
841         }
842
843         self.ci_env.force_coloring_in_ci(&mut cargo);
844
845         cargo
846     }
847
848     /// Ensure that a given step is built, returning its output. This will
849     /// cache the step, so it is safe (and good!) to call this as often as
850     /// needed to ensure that all dependencies are built.
851     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
852         {
853             let mut stack = self.stack.borrow_mut();
854             for stack_step in stack.iter() {
855                 // should skip
856                 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
857                     continue;
858                 }
859                 let mut out = String::new();
860                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
861                 for el in stack.iter().rev() {
862                     out += &format!("\t{:?}\n", el);
863                 }
864                 panic!(out);
865             }
866             if let Some(out) = self.cache.get(&step) {
867                 self.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
868
869                 {
870                     let mut graph = self.graph.borrow_mut();
871                     let parent = self.parent.get();
872                     let us = *self.graph_nodes.borrow_mut()
873                         .entry(format!("{:?}", step))
874                         .or_insert_with(|| graph.add_node(format!("{:?}", step)));
875                     if let Some(parent) = parent {
876                         graph.add_edge(parent, us, false);
877                     }
878                 }
879
880                 return out;
881             }
882             self.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
883             stack.push(Box::new(step.clone()));
884         }
885
886         let prev_parent = self.parent.get();
887
888         {
889             let mut graph = self.graph.borrow_mut();
890             let parent = self.parent.get();
891             let us = *self.graph_nodes.borrow_mut()
892                 .entry(format!("{:?}", step))
893                 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
894             self.parent.set(Some(us));
895             if let Some(parent) = parent {
896                 graph.add_edge(parent, us, true);
897             }
898         }
899
900         let (out, dur) = {
901             let start = Instant::now();
902             let zero = Duration::new(0, 0);
903             let parent = self.time_spent_on_dependencies.replace(zero);
904             let out = step.clone().run(self);
905             let dur = start.elapsed();
906             let deps = self.time_spent_on_dependencies.replace(parent + dur);
907             (out, dur - deps)
908         };
909
910         self.parent.set(prev_parent);
911
912         if self.config.print_step_timings && dur > Duration::from_millis(100) {
913             println!("[TIMING] {:?} -- {}.{:03}",
914                      step,
915                      dur.as_secs(),
916                      dur.subsec_nanos() / 1_000_000);
917         }
918
919         {
920             let mut stack = self.stack.borrow_mut();
921             let cur_step = stack.pop().expect("step stack empty");
922             assert_eq!(cur_step.downcast_ref(), Some(&step));
923         }
924         self.verbose(&format!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
925         self.cache.put(step, out.clone());
926         out
927     }
928 }
929
930 #[cfg(test)]
931 mod __test {
932     use config::Config;
933     use std::thread;
934     use super::*;
935
936     fn configure(host: &[&str], target: &[&str]) -> Config {
937         let mut config = Config::default_opts();
938         // don't save toolstates
939         config.save_toolstates = None;
940         config.run_host_only = true;
941         config.dry_run = true;
942         // try to avoid spurious failures in dist where we create/delete each others file
943         let dir = config.out.join("tmp-rustbuild-tests")
944             .join(&thread::current().name().unwrap_or("unknown").replace(":", "-"));
945         t!(fs::create_dir_all(&dir));
946         config.out = dir;
947         config.build = INTERNER.intern_str("A");
948         config.hosts = vec![config.build].clone().into_iter()
949             .chain(host.iter().map(|s| INTERNER.intern_str(s))).collect::<Vec<_>>();
950         config.targets = config.hosts.clone().into_iter()
951             .chain(target.iter().map(|s| INTERNER.intern_str(s))).collect::<Vec<_>>();
952         config
953     }
954
955     fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
956         v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
957     }
958
959     #[test]
960     fn dist_baseline() {
961         let build = Build::new(configure(&[], &[]));
962         let mut builder = Builder::new(&build);
963         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
964
965         let a = INTERNER.intern_str("A");
966
967         assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
968             dist::Docs { stage: 2, host: a },
969         ]);
970         assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
971             dist::Mingw { host: a },
972         ]);
973         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
974             dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
975         ]);
976         assert_eq!(first(builder.cache.all::<dist::Std>()), &[
977             dist::Std {
978                 compiler: Compiler { host: a, stage: 2 },
979                 target: a,
980             },
981         ]);
982         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
983     }
984
985     #[test]
986     fn dist_with_targets() {
987         let build = Build::new(configure(&[], &["B"]));
988         let mut builder = Builder::new(&build);
989         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
990
991         let a = INTERNER.intern_str("A");
992         let b = INTERNER.intern_str("B");
993
994         assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
995             dist::Docs { stage: 2, host: a },
996             dist::Docs { stage: 2, host: b },
997         ]);
998         assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
999             dist::Mingw { host: a },
1000             dist::Mingw { host: b },
1001         ]);
1002         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
1003             dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
1004         ]);
1005         assert_eq!(first(builder.cache.all::<dist::Std>()), &[
1006             dist::Std {
1007                 compiler: Compiler { host: a, stage: 2 },
1008                 target: a,
1009             },
1010             dist::Std {
1011                 compiler: Compiler { host: a, stage: 2 },
1012                 target: b,
1013             },
1014         ]);
1015         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1016     }
1017
1018     #[test]
1019     fn dist_with_hosts() {
1020         let build = Build::new(configure(&["B"], &[]));
1021         let mut builder = Builder::new(&build);
1022         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1023
1024         let a = INTERNER.intern_str("A");
1025         let b = INTERNER.intern_str("B");
1026
1027         assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
1028             dist::Docs { stage: 2, host: a },
1029             dist::Docs { stage: 2, host: b },
1030         ]);
1031         assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
1032             dist::Mingw { host: a },
1033             dist::Mingw { host: b },
1034         ]);
1035         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
1036             dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
1037             dist::Rustc { compiler: Compiler { host: b, stage: 2 } },
1038         ]);
1039         assert_eq!(first(builder.cache.all::<dist::Std>()), &[
1040             dist::Std {
1041                 compiler: Compiler { host: a, stage: 2 },
1042                 target: a,
1043             },
1044             dist::Std {
1045                 compiler: Compiler { host: a, stage: 2 },
1046                 target: b,
1047             },
1048         ]);
1049         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1050     }
1051
1052     #[test]
1053     fn dist_with_targets_and_hosts() {
1054         let build = Build::new(configure(&["B"], &["C"]));
1055         let mut builder = Builder::new(&build);
1056         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1057
1058         let a = INTERNER.intern_str("A");
1059         let b = INTERNER.intern_str("B");
1060         let c = INTERNER.intern_str("C");
1061
1062         assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
1063             dist::Docs { stage: 2, host: a },
1064             dist::Docs { stage: 2, host: b },
1065             dist::Docs { stage: 2, host: c },
1066         ]);
1067         assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
1068             dist::Mingw { host: a },
1069             dist::Mingw { host: b },
1070             dist::Mingw { host: c },
1071         ]);
1072         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
1073             dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
1074             dist::Rustc { compiler: Compiler { host: b, stage: 2 } },
1075         ]);
1076         assert_eq!(first(builder.cache.all::<dist::Std>()), &[
1077             dist::Std {
1078                 compiler: Compiler { host: a, stage: 2 },
1079                 target: a,
1080             },
1081             dist::Std {
1082                 compiler: Compiler { host: a, stage: 2 },
1083                 target: b,
1084             },
1085             dist::Std {
1086                 compiler: Compiler { host: a, stage: 2 },
1087                 target: c,
1088             },
1089         ]);
1090         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1091     }
1092
1093     #[test]
1094     fn dist_with_target_flag() {
1095         let mut config = configure(&["B"], &["C"]);
1096         config.run_host_only = false; // as-if --target=C was passed
1097         let build = Build::new(config);
1098         let mut builder = Builder::new(&build);
1099         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1100
1101         let a = INTERNER.intern_str("A");
1102         let b = INTERNER.intern_str("B");
1103         let c = INTERNER.intern_str("C");
1104
1105         assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
1106             dist::Docs { stage: 2, host: a },
1107             dist::Docs { stage: 2, host: b },
1108             dist::Docs { stage: 2, host: c },
1109         ]);
1110         assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
1111             dist::Mingw { host: a },
1112             dist::Mingw { host: b },
1113             dist::Mingw { host: c },
1114         ]);
1115         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1116         assert_eq!(first(builder.cache.all::<dist::Std>()), &[
1117             dist::Std {
1118                 compiler: Compiler { host: a, stage: 2 },
1119                 target: a,
1120             },
1121             dist::Std {
1122                 compiler: Compiler { host: a, stage: 2 },
1123                 target: b,
1124             },
1125             dist::Std {
1126                 compiler: Compiler { host: a, stage: 2 },
1127                 target: c,
1128             },
1129         ]);
1130         assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1131     }
1132
1133     #[test]
1134     fn dist_with_same_targets_and_hosts() {
1135         let build = Build::new(configure(&["B"], &["B"]));
1136         let mut builder = Builder::new(&build);
1137         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1138
1139         let a = INTERNER.intern_str("A");
1140         let b = INTERNER.intern_str("B");
1141
1142         assert_eq!(first(builder.cache.all::<dist::Docs>()), &[
1143             dist::Docs { stage: 2, host: a },
1144             dist::Docs { stage: 2, host: b },
1145         ]);
1146         assert_eq!(first(builder.cache.all::<dist::Mingw>()), &[
1147             dist::Mingw { host: a },
1148             dist::Mingw { host: b },
1149         ]);
1150         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[
1151             dist::Rustc { compiler: Compiler { host: a, stage: 2 } },
1152             dist::Rustc { compiler: Compiler { host: b, stage: 2 } },
1153         ]);
1154         assert_eq!(first(builder.cache.all::<dist::Std>()), &[
1155             dist::Std {
1156                 compiler: Compiler { host: a, stage: 2 },
1157                 target: a,
1158             },
1159             dist::Std {
1160                 compiler: Compiler { host: a, stage: 2 },
1161                 target: b,
1162             },
1163         ]);
1164         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1165         assert_eq!(first(builder.cache.all::<compile::Std>()), &[
1166             compile::Std {
1167                 compiler: Compiler { host: a, stage: 0 },
1168                 target: a,
1169             },
1170             compile::Std {
1171                 compiler: Compiler { host: a, stage: 1 },
1172                 target: a,
1173             },
1174             compile::Std {
1175                 compiler: Compiler { host: a, stage: 2 },
1176                 target: a,
1177             },
1178             compile::Std {
1179                 compiler: Compiler { host: a, stage: 1 },
1180                 target: b,
1181             },
1182             compile::Std {
1183                 compiler: Compiler { host: a, stage: 2 },
1184                 target: b,
1185             },
1186         ]);
1187         assert_eq!(first(builder.cache.all::<compile::Test>()), &[
1188             compile::Test {
1189                 compiler: Compiler { host: a, stage: 0 },
1190                 target: a,
1191             },
1192             compile::Test {
1193                 compiler: Compiler { host: a, stage: 1 },
1194                 target: a,
1195             },
1196             compile::Test {
1197                 compiler: Compiler { host: a, stage: 2 },
1198                 target: a,
1199             },
1200             compile::Test {
1201                 compiler: Compiler { host: a, stage: 1 },
1202                 target: b,
1203             },
1204             compile::Test {
1205                 compiler: Compiler { host: a, stage: 2 },
1206                 target: b,
1207             },
1208         ]);
1209         assert_eq!(first(builder.cache.all::<compile::Assemble>()), &[
1210             compile::Assemble {
1211                 target_compiler: Compiler { host: a, stage: 0 },
1212             },
1213             compile::Assemble {
1214                 target_compiler: Compiler { host: a, stage: 1 },
1215             },
1216             compile::Assemble {
1217                 target_compiler: Compiler { host: a, stage: 2 },
1218             },
1219             compile::Assemble {
1220                 target_compiler: Compiler { host: b, stage: 2 },
1221             },
1222         ]);
1223     }
1224
1225     #[test]
1226     fn build_default() {
1227         let build = Build::new(configure(&["B"], &["C"]));
1228         let mut builder = Builder::new(&build);
1229         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1230
1231         let a = INTERNER.intern_str("A");
1232         let b = INTERNER.intern_str("B");
1233         let c = INTERNER.intern_str("C");
1234
1235         assert!(!builder.cache.all::<compile::Std>().is_empty());
1236         assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1237         assert_eq!(first(builder.cache.all::<compile::Rustc>()), &[
1238             compile::Rustc {
1239                 compiler: Compiler { host: a, stage: 0 },
1240                 target: a,
1241             },
1242             compile::Rustc {
1243                 compiler: Compiler { host: a, stage: 1 },
1244                 target: a,
1245             },
1246             compile::Rustc {
1247                 compiler: Compiler { host: a, stage: 2 },
1248                 target: a,
1249             },
1250             compile::Rustc {
1251                 compiler: Compiler { host: b, stage: 2 },
1252                 target: a,
1253             },
1254             compile::Rustc {
1255                 compiler: Compiler { host: a, stage: 0 },
1256                 target: b,
1257             },
1258             compile::Rustc {
1259                 compiler: Compiler { host: a, stage: 1 },
1260                 target: b,
1261             },
1262             compile::Rustc {
1263                 compiler: Compiler { host: a, stage: 2 },
1264                 target: b,
1265             },
1266             compile::Rustc {
1267                 compiler: Compiler { host: b, stage: 2 },
1268                 target: b,
1269             },
1270         ]);
1271
1272         assert_eq!(first(builder.cache.all::<compile::Test>()), &[
1273             compile::Test {
1274                 compiler: Compiler { host: a, stage: 0 },
1275                 target: a,
1276             },
1277             compile::Test {
1278                 compiler: Compiler { host: a, stage: 1 },
1279                 target: a,
1280             },
1281             compile::Test {
1282                 compiler: Compiler { host: a, stage: 2 },
1283                 target: a,
1284             },
1285             compile::Test {
1286                 compiler: Compiler { host: b, stage: 2 },
1287                 target: a,
1288             },
1289             compile::Test {
1290                 compiler: Compiler { host: a, stage: 0 },
1291                 target: b,
1292             },
1293             compile::Test {
1294                 compiler: Compiler { host: a, stage: 1 },
1295                 target: b,
1296             },
1297             compile::Test {
1298                 compiler: Compiler { host: a, stage: 2 },
1299                 target: b,
1300             },
1301             compile::Test {
1302                 compiler: Compiler { host: b, stage: 2 },
1303                 target: b,
1304             },
1305             compile::Test {
1306                 compiler: Compiler { host: a, stage: 2 },
1307                 target: c,
1308             },
1309             compile::Test {
1310                 compiler: Compiler { host: b, stage: 2 },
1311                 target: c,
1312             },
1313         ]);
1314     }
1315
1316     #[test]
1317     fn build_with_target_flag() {
1318         let mut config = configure(&["B"], &["C"]);
1319         config.run_host_only = false;
1320         let build = Build::new(config);
1321         let mut builder = Builder::new(&build);
1322         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1323
1324         let a = INTERNER.intern_str("A");
1325         let b = INTERNER.intern_str("B");
1326         let c = INTERNER.intern_str("C");
1327
1328         assert!(!builder.cache.all::<compile::Std>().is_empty());
1329         assert_eq!(first(builder.cache.all::<compile::Assemble>()), &[
1330             compile::Assemble {
1331                 target_compiler: Compiler { host: a, stage: 0 },
1332             },
1333             compile::Assemble {
1334                 target_compiler: Compiler { host: a, stage: 1 },
1335             },
1336             compile::Assemble {
1337                 target_compiler: Compiler { host: b, stage: 1 },
1338             },
1339             compile::Assemble {
1340                 target_compiler: Compiler { host: a, stage: 2 },
1341             },
1342             compile::Assemble {
1343                 target_compiler: Compiler { host: b, stage: 2 },
1344             },
1345         ]);
1346         assert_eq!(first(builder.cache.all::<compile::Rustc>()), &[
1347             compile::Rustc {
1348                 compiler: Compiler { host: a, stage: 0 },
1349                 target: a,
1350             },
1351             compile::Rustc {
1352                 compiler: Compiler { host: a, stage: 1 },
1353                 target: a,
1354             },
1355             compile::Rustc {
1356                 compiler: Compiler { host: a, stage: 0 },
1357                 target: b,
1358             },
1359             compile::Rustc {
1360                 compiler: Compiler { host: a, stage: 1 },
1361                 target: b,
1362             },
1363         ]);
1364
1365         assert_eq!(first(builder.cache.all::<compile::Test>()), &[
1366             compile::Test {
1367                 compiler: Compiler { host: a, stage: 0 },
1368                 target: a,
1369             },
1370             compile::Test {
1371                 compiler: Compiler { host: a, stage: 1 },
1372                 target: a,
1373             },
1374             compile::Test {
1375                 compiler: Compiler { host: a, stage: 2 },
1376                 target: a,
1377             },
1378             compile::Test {
1379                 compiler: Compiler { host: b, stage: 2 },
1380                 target: a,
1381             },
1382             compile::Test {
1383                 compiler: Compiler { host: a, stage: 0 },
1384                 target: b,
1385             },
1386             compile::Test {
1387                 compiler: Compiler { host: a, stage: 1 },
1388                 target: b,
1389             },
1390             compile::Test {
1391                 compiler: Compiler { host: a, stage: 2 },
1392                 target: b,
1393             },
1394             compile::Test {
1395                 compiler: Compiler { host: b, stage: 2 },
1396                 target: b,
1397             },
1398             compile::Test {
1399                 compiler: Compiler { host: a, stage: 2 },
1400                 target: c,
1401             },
1402             compile::Test {
1403                 compiler: Compiler { host: b, stage: 2 },
1404                 target: c,
1405             },
1406         ]);
1407     }
1408 }