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