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