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