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