]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Auto merge of #95612 - davidtwco:split-debuginfo-in-bootstrap, r=Mark-Simulacrum
[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::{Component, Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
13
14 use crate::cache::{Cache, Interned, INTERNER};
15 use crate::check;
16 use crate::compile;
17 use crate::config::{SplitDebuginfo, TargetSelection};
18 use crate::dist;
19 use crate::doc;
20 use crate::flags::{Color, Subcommand};
21 use crate::install;
22 use crate::native;
23 use crate::run;
24 use crate::test;
25 use crate::tool::{self, SourceType};
26 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir, output, t};
27 use crate::EXTRA_CHECK_CFGS;
28 use crate::{Build, CLang, DocTests, GitRepo, Mode};
29
30 pub use crate::Compiler;
31 // FIXME: replace with std::lazy after it gets stabilized and reaches beta
32 use once_cell::sync::Lazy;
33
34 pub struct Builder<'a> {
35     pub build: &'a Build,
36     pub top_stage: u32,
37     pub kind: Kind,
38     cache: Cache,
39     stack: RefCell<Vec<Box<dyn Any>>>,
40     time_spent_on_dependencies: Cell<Duration>,
41     pub paths: Vec<PathBuf>,
42 }
43
44 impl<'a> Deref for Builder<'a> {
45     type Target = Build;
46
47     fn deref(&self) -> &Self::Target {
48         self.build
49     }
50 }
51
52 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
53     /// `PathBuf` when directories are created or to return a `Compiler` once
54     /// it's been assembled.
55     type Output: Clone;
56
57     /// Whether this step is run by default as part of its respective phase.
58     /// `true` here can still be overwritten by `should_run` calling `default_condition`.
59     const DEFAULT: bool = false;
60
61     /// If true, then this rule should be skipped if --target was specified, but --host was not
62     const ONLY_HOSTS: bool = false;
63
64     /// Primary function to execute this rule. Can call `builder.ensure()`
65     /// with other steps to run those.
66     fn run(self, builder: &Builder<'_>) -> Self::Output;
67
68     /// When bootstrap is passed a set of paths, this controls whether this rule
69     /// will execute. However, it does not get called in a "default" context
70     /// when we are not passed any paths; in that case, `make_run` is called
71     /// directly.
72     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
73
74     /// Builds up a "root" rule, either as a default rule or from a path passed
75     /// to us.
76     ///
77     /// When path is `None`, we are executing in a context where no paths were
78     /// passed. When `./x.py build` is run, for example, this rule could get
79     /// called if it is in the correct list below with a path of `None`.
80     fn make_run(_run: RunConfig<'_>) {
81         // It is reasonable to not have an implementation of make_run for rules
82         // who do not want to get called from the root context. This means that
83         // they are likely dependencies (e.g., sysroot creation) or similar, and
84         // as such calling them from ./x.py isn't logical.
85         unimplemented!()
86     }
87 }
88
89 pub struct RunConfig<'a> {
90     pub builder: &'a Builder<'a>,
91     pub target: TargetSelection,
92     pub path: PathBuf,
93 }
94
95 impl RunConfig<'_> {
96     pub fn build_triple(&self) -> TargetSelection {
97         self.builder.build.build
98     }
99 }
100
101 struct StepDescription {
102     default: bool,
103     only_hosts: bool,
104     should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
105     make_run: fn(RunConfig<'_>),
106     name: &'static str,
107     kind: Kind,
108 }
109
110 #[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
111 pub struct TaskPath {
112     pub path: PathBuf,
113     pub kind: Option<Kind>,
114 }
115
116 impl TaskPath {
117     pub fn parse(path: impl Into<PathBuf>) -> TaskPath {
118         let mut kind = None;
119         let mut path = path.into();
120
121         let mut components = path.components();
122         if let Some(Component::Normal(os_str)) = components.next() {
123             if let Some(str) = os_str.to_str() {
124                 if let Some((found_kind, found_prefix)) = str.split_once("::") {
125                     if found_kind.is_empty() {
126                         panic!("empty kind in task path {}", path.display());
127                     }
128                     kind = Some(Kind::parse(found_kind));
129                     path = Path::new(found_prefix).join(components.as_path());
130                 }
131             }
132         }
133
134         TaskPath { path, kind }
135     }
136 }
137
138 impl Debug for TaskPath {
139     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140         if let Some(kind) = &self.kind {
141             write!(f, "{}::", kind.as_str())?;
142         }
143         write!(f, "{}", self.path.display())
144     }
145 }
146
147 /// Collection of paths used to match a task rule.
148 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
149 pub enum PathSet {
150     /// A collection of individual paths.
151     ///
152     /// These are generally matched as a path suffix. For example, a
153     /// command-line value of `libstd` will match if `src/libstd` is in the
154     /// set.
155     Set(BTreeSet<TaskPath>),
156     /// A "suite" of paths.
157     ///
158     /// These can match as a path suffix (like `Set`), or as a prefix. For
159     /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
160     /// will match `src/test/ui`. A command-line value of `ui` would also
161     /// match `src/test/ui`.
162     Suite(TaskPath),
163 }
164
165 impl PathSet {
166     fn empty() -> PathSet {
167         PathSet::Set(BTreeSet::new())
168     }
169
170     fn one<P: Into<PathBuf>>(path: P, kind: Kind) -> PathSet {
171         let mut set = BTreeSet::new();
172         set.insert(TaskPath { path: path.into(), kind: Some(kind) });
173         PathSet::Set(set)
174     }
175
176     fn has(&self, needle: &Path, module: Option<Kind>) -> bool {
177         let check = |p: &TaskPath| {
178             if let (Some(p_kind), Some(kind)) = (&p.kind, module) {
179                 p.path.ends_with(needle) && *p_kind == kind
180             } else {
181                 p.path.ends_with(needle)
182             }
183         };
184
185         match self {
186             PathSet::Set(set) => set.iter().any(check),
187             PathSet::Suite(suite) => check(suite),
188         }
189     }
190
191     fn path(&self, builder: &Builder<'_>) -> PathBuf {
192         match self {
193             PathSet::Set(set) => {
194                 set.iter().next().map(|p| &p.path).unwrap_or(&builder.build.src).clone()
195             }
196             PathSet::Suite(path) => path.path.clone(),
197         }
198     }
199 }
200
201 impl StepDescription {
202     fn from<S: Step>(kind: Kind) -> StepDescription {
203         StepDescription {
204             default: S::DEFAULT,
205             only_hosts: S::ONLY_HOSTS,
206             should_run: S::should_run,
207             make_run: S::make_run,
208             name: std::any::type_name::<S>(),
209             kind,
210         }
211     }
212
213     fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
214         if self.is_excluded(builder, pathset) {
215             return;
216         }
217
218         // Determine the targets participating in this rule.
219         let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
220
221         for target in targets {
222             let run = RunConfig { builder, path: pathset.path(builder), target: *target };
223             (self.make_run)(run);
224         }
225     }
226
227     fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool {
228         if builder.config.exclude.iter().any(|e| pathset.has(&e.path, e.kind)) {
229             eprintln!("Skipping {:?} because it is excluded", pathset);
230             return true;
231         }
232
233         if !builder.config.exclude.is_empty() {
234             builder.verbose(&format!(
235                 "{:?} not skipped for {:?} -- not in {:?}",
236                 pathset, self.name, builder.config.exclude
237             ));
238         }
239         false
240     }
241
242     fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
243         let should_runs = v
244             .iter()
245             .map(|desc| (desc.should_run)(ShouldRun::new(builder, desc.kind)))
246             .collect::<Vec<_>>();
247
248         // sanity checks on rules
249         for (desc, should_run) in v.iter().zip(&should_runs) {
250             assert!(
251                 !should_run.paths.is_empty(),
252                 "{:?} should have at least one pathset",
253                 desc.name
254             );
255         }
256
257         if paths.is_empty() || builder.config.include_default_paths {
258             for (desc, should_run) in v.iter().zip(&should_runs) {
259                 if desc.default && should_run.is_really_default() {
260                     for pathset in &should_run.paths {
261                         desc.maybe_run(builder, pathset);
262                     }
263                 }
264             }
265         }
266
267         for path in paths {
268             // strip CurDir prefix if present
269             let path = match path.strip_prefix(".") {
270                 Ok(p) => p,
271                 Err(_) => path,
272             };
273
274             let mut attempted_run = false;
275             for (desc, should_run) in v.iter().zip(&should_runs) {
276                 if let Some(suite) = should_run.is_suite_path(path) {
277                     attempted_run = true;
278                     desc.maybe_run(builder, suite);
279                 } else if let Some(pathset) = should_run.pathset_for_path(path, desc.kind) {
280                     attempted_run = true;
281                     desc.maybe_run(builder, pathset);
282                 }
283             }
284
285             if !attempted_run {
286                 panic!("error: no rules matched {}", path.display());
287             }
288         }
289     }
290 }
291
292 enum ReallyDefault<'a> {
293     Bool(bool),
294     Lazy(Lazy<bool, Box<dyn Fn() -> bool + 'a>>),
295 }
296
297 pub struct ShouldRun<'a> {
298     pub builder: &'a Builder<'a>,
299     kind: Kind,
300
301     // use a BTreeSet to maintain sort order
302     paths: BTreeSet<PathSet>,
303
304     // If this is a default rule, this is an additional constraint placed on
305     // its run. Generally something like compiler docs being enabled.
306     is_really_default: ReallyDefault<'a>,
307 }
308
309 impl<'a> ShouldRun<'a> {
310     fn new(builder: &'a Builder<'_>, kind: Kind) -> ShouldRun<'a> {
311         ShouldRun {
312             builder,
313             kind,
314             paths: BTreeSet::new(),
315             is_really_default: ReallyDefault::Bool(true), // by default no additional conditions
316         }
317     }
318
319     pub fn default_condition(mut self, cond: bool) -> Self {
320         self.is_really_default = ReallyDefault::Bool(cond);
321         self
322     }
323
324     pub fn lazy_default_condition(mut self, lazy_cond: Box<dyn Fn() -> bool + 'a>) -> Self {
325         self.is_really_default = ReallyDefault::Lazy(Lazy::new(lazy_cond));
326         self
327     }
328
329     pub fn is_really_default(&self) -> bool {
330         match &self.is_really_default {
331             ReallyDefault::Bool(val) => *val,
332             ReallyDefault::Lazy(lazy) => *lazy.deref(),
333         }
334     }
335
336     /// Indicates it should run if the command-line selects the given crate or
337     /// any of its (local) dependencies.
338     ///
339     /// Compared to `krate`, this treats the dependencies as aliases for the
340     /// same job. Generally it is preferred to use `krate`, and treat each
341     /// individual path separately. For example `./x.py test src/liballoc`
342     /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
343     /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
344     /// `all_krates` should probably be removed at some point.
345     pub fn all_krates(mut self, name: &str) -> Self {
346         let mut set = BTreeSet::new();
347         for krate in self.builder.in_tree_crates(name, None) {
348             let path = krate.local_path(self.builder);
349             set.insert(TaskPath { path, kind: Some(self.kind) });
350         }
351         self.paths.insert(PathSet::Set(set));
352         self
353     }
354
355     /// Indicates it should run if the command-line selects the given crate or
356     /// any of its (local) dependencies.
357     ///
358     /// `make_run` will be called separately for each matching command-line path.
359     pub fn krate(mut self, name: &str) -> Self {
360         for krate in self.builder.in_tree_crates(name, None) {
361             let path = krate.local_path(self.builder);
362             self.paths.insert(PathSet::one(path, self.kind));
363         }
364         self
365     }
366
367     // single alias, which does not correspond to any on-disk path
368     pub fn alias(mut self, alias: &str) -> Self {
369         assert!(
370             !self.builder.src.join(alias).exists(),
371             "use `builder.path()` for real paths: {}",
372             alias
373         );
374         self.paths.insert(PathSet::Set(
375             std::iter::once(TaskPath { path: alias.into(), kind: Some(self.kind) }).collect(),
376         ));
377         self
378     }
379
380     // single, non-aliased path
381     pub fn path(self, path: &str) -> Self {
382         self.paths(&[path])
383     }
384
385     // multiple aliases for the same job
386     pub fn paths(mut self, paths: &[&str]) -> Self {
387         self.paths.insert(PathSet::Set(
388             paths
389                 .iter()
390                 .map(|p| {
391                     // FIXME(#96188): make sure this is actually a path.
392                     // This currently breaks for paths within submodules.
393                     //assert!(
394                     //    self.builder.src.join(p).exists(),
395                     //    "`should_run.paths` should correspond to real on-disk paths - use `alias` if there is no relevant path: {}",
396                     //    p
397                     //);
398                     TaskPath { path: p.into(), kind: Some(self.kind) }
399                 })
400                 .collect(),
401         ));
402         self
403     }
404
405     pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
406         self.paths.iter().find(|pathset| match pathset {
407             PathSet::Suite(p) => path.starts_with(&p.path),
408             PathSet::Set(_) => false,
409         })
410     }
411
412     pub fn suite_path(mut self, suite: &str) -> Self {
413         self.paths.insert(PathSet::Suite(TaskPath { path: suite.into(), kind: Some(self.kind) }));
414         self
415     }
416
417     // allows being more explicit about why should_run in Step returns the value passed to it
418     pub fn never(mut self) -> ShouldRun<'a> {
419         self.paths.insert(PathSet::empty());
420         self
421     }
422
423     fn pathset_for_path(&self, path: &Path, kind: Kind) -> Option<&PathSet> {
424         self.paths.iter().find(|pathset| pathset.has(path, Some(kind)))
425     }
426 }
427
428 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
429 pub enum Kind {
430     Build,
431     Check,
432     Clippy,
433     Fix,
434     Test,
435     Bench,
436     Dist,
437     Doc,
438     Install,
439     Run,
440 }
441
442 impl Kind {
443     fn parse(string: &str) -> Kind {
444         match string {
445             "build" => Kind::Build,
446             "check" => Kind::Check,
447             "clippy" => Kind::Clippy,
448             "fix" => Kind::Fix,
449             "test" => Kind::Test,
450             "bench" => Kind::Bench,
451             "dist" => Kind::Dist,
452             "doc" => Kind::Doc,
453             "install" => Kind::Install,
454             "run" => Kind::Run,
455             other => panic!("unknown kind: {}", other),
456         }
457     }
458
459     fn as_str(&self) -> &'static str {
460         match self {
461             Kind::Build => "build",
462             Kind::Check => "check",
463             Kind::Clippy => "clippy",
464             Kind::Fix => "fix",
465             Kind::Test => "test",
466             Kind::Bench => "bench",
467             Kind::Dist => "dist",
468             Kind::Doc => "doc",
469             Kind::Install => "install",
470             Kind::Run => "run",
471         }
472     }
473 }
474
475 impl<'a> Builder<'a> {
476     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
477         macro_rules! describe {
478             ($($rule:ty),+ $(,)?) => {{
479                 vec![$(StepDescription::from::<$rule>(kind)),+]
480             }};
481         }
482         match kind {
483             Kind::Build => describe!(
484                 compile::Std,
485                 compile::Assemble,
486                 compile::CodegenBackend,
487                 compile::StartupObjects,
488                 tool::BuildManifest,
489                 tool::Rustbook,
490                 tool::ErrorIndex,
491                 tool::UnstableBookGen,
492                 tool::Tidy,
493                 tool::Linkchecker,
494                 tool::CargoTest,
495                 tool::Compiletest,
496                 tool::RemoteTestServer,
497                 tool::RemoteTestClient,
498                 tool::RustInstaller,
499                 tool::Cargo,
500                 tool::Rls,
501                 tool::RustAnalyzer,
502                 tool::RustDemangler,
503                 tool::Rustdoc,
504                 tool::Clippy,
505                 tool::CargoClippy,
506                 native::Llvm,
507                 native::Sanitizers,
508                 tool::Rustfmt,
509                 tool::Miri,
510                 tool::CargoMiri,
511                 native::Lld,
512                 native::CrtBeginEnd
513             ),
514             Kind::Check | Kind::Clippy { .. } | Kind::Fix => describe!(
515                 check::Std,
516                 check::Rustc,
517                 check::Rustdoc,
518                 check::CodegenBackend,
519                 check::Clippy,
520                 check::Miri,
521                 check::Rls,
522                 check::Rustfmt,
523                 check::Bootstrap
524             ),
525             Kind::Test => describe!(
526                 crate::toolstate::ToolStateCheck,
527                 test::ExpandYamlAnchors,
528                 test::Tidy,
529                 test::Ui,
530                 test::RunPassValgrind,
531                 test::MirOpt,
532                 test::Codegen,
533                 test::CodegenUnits,
534                 test::Assembly,
535                 test::Incremental,
536                 test::Debuginfo,
537                 test::UiFullDeps,
538                 test::Rustdoc,
539                 test::Pretty,
540                 test::Crate,
541                 test::CrateLibrustc,
542                 test::CrateRustdoc,
543                 test::CrateRustdocJsonTypes,
544                 test::Linkcheck,
545                 test::TierCheck,
546                 test::Cargotest,
547                 test::Cargo,
548                 test::Rls,
549                 test::ErrorIndex,
550                 test::Distcheck,
551                 test::RunMakeFullDeps,
552                 test::Nomicon,
553                 test::Reference,
554                 test::RustdocBook,
555                 test::RustByExample,
556                 test::TheBook,
557                 test::UnstableBook,
558                 test::RustcBook,
559                 test::LintDocs,
560                 test::RustcGuide,
561                 test::EmbeddedBook,
562                 test::EditionGuide,
563                 test::Rustfmt,
564                 test::Miri,
565                 test::Clippy,
566                 test::RustDemangler,
567                 test::CompiletestTest,
568                 test::RustdocJSStd,
569                 test::RustdocJSNotStd,
570                 test::RustdocGUI,
571                 test::RustdocTheme,
572                 test::RustdocUi,
573                 test::RustdocJson,
574                 test::HtmlCheck,
575                 // Run bootstrap close to the end as it's unlikely to fail
576                 test::Bootstrap,
577                 // Run run-make last, since these won't pass without make on Windows
578                 test::RunMake,
579             ),
580             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
581             Kind::Doc => describe!(
582                 doc::UnstableBook,
583                 doc::UnstableBookGen,
584                 doc::TheBook,
585                 doc::Standalone,
586                 doc::Std,
587                 doc::Rustc,
588                 doc::Rustdoc,
589                 doc::Rustfmt,
590                 doc::ErrorIndex,
591                 doc::Nomicon,
592                 doc::Reference,
593                 doc::RustdocBook,
594                 doc::RustByExample,
595                 doc::RustcBook,
596                 doc::CargoBook,
597                 doc::Clippy,
598                 doc::EmbeddedBook,
599                 doc::EditionGuide,
600             ),
601             Kind::Dist => describe!(
602                 dist::Docs,
603                 dist::RustcDocs,
604                 dist::Mingw,
605                 dist::Rustc,
606                 dist::DebuggerScripts,
607                 dist::Std,
608                 dist::RustcDev,
609                 dist::Analysis,
610                 dist::Src,
611                 dist::Cargo,
612                 dist::Rls,
613                 dist::RustAnalyzer,
614                 dist::Rustfmt,
615                 dist::RustDemangler,
616                 dist::Clippy,
617                 dist::Miri,
618                 dist::LlvmTools,
619                 dist::RustDev,
620                 dist::Extended,
621                 // It seems that PlainSourceTarball somehow changes how some of the tools
622                 // perceive their dependencies (see #93033) which would invalidate fingerprints
623                 // and force us to rebuild tools after vendoring dependencies.
624                 // To work around this, create the Tarball after building all the tools.
625                 dist::PlainSourceTarball,
626                 dist::BuildManifest,
627                 dist::ReproducibleArtifacts,
628             ),
629             Kind::Install => describe!(
630                 install::Docs,
631                 install::Std,
632                 install::Cargo,
633                 install::Rls,
634                 install::RustAnalyzer,
635                 install::Rustfmt,
636                 install::RustDemangler,
637                 install::Clippy,
638                 install::Miri,
639                 install::Analysis,
640                 install::Src,
641                 install::Rustc
642             ),
643             Kind::Run => describe!(run::ExpandYamlAnchors, run::BuildManifest, run::BumpStage0),
644         }
645     }
646
647     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
648         let kind = match subcommand {
649             "build" | "b" => Kind::Build,
650             "doc" | "d" => Kind::Doc,
651             "test" | "t" => Kind::Test,
652             "bench" => Kind::Bench,
653             "dist" => Kind::Dist,
654             "install" => Kind::Install,
655             _ => return None,
656         };
657
658         let builder = Self::new_internal(build, kind, vec![]);
659         let builder = &builder;
660         // The "build" kind here is just a placeholder, it will be replaced with something else in
661         // the following statement.
662         let mut should_run = ShouldRun::new(builder, Kind::Build);
663         for desc in Builder::get_step_descriptions(builder.kind) {
664             should_run.kind = desc.kind;
665             should_run = (desc.should_run)(should_run);
666         }
667         let mut help = String::from("Available paths:\n");
668         let mut add_path = |path: &Path| {
669             help.push_str(&format!("    ./x.py {} {}\n", subcommand, path.display()));
670         };
671         for pathset in should_run.paths {
672             match pathset {
673                 PathSet::Set(set) => {
674                     for path in set {
675                         add_path(&path.path);
676                     }
677                 }
678                 PathSet::Suite(path) => {
679                     add_path(&path.path.join("..."));
680                 }
681             }
682         }
683         Some(help)
684     }
685
686     fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
687         Builder {
688             build,
689             top_stage: build.config.stage,
690             kind,
691             cache: Cache::new(),
692             stack: RefCell::new(Vec::new()),
693             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
694             paths,
695         }
696     }
697
698     pub fn new(build: &Build) -> Builder<'_> {
699         let (kind, paths) = match build.config.cmd {
700             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
701             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
702             Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
703             Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
704             Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
705             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
706             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
707             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
708             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
709             Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
710             Subcommand::Format { .. } | Subcommand::Clean { .. } | Subcommand::Setup { .. } => {
711                 panic!()
712             }
713         };
714
715         Self::new_internal(build, kind, paths.to_owned())
716     }
717
718     pub fn execute_cli(&self) {
719         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
720     }
721
722     pub fn default_doc(&self, paths: &[PathBuf]) {
723         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
724     }
725
726     /// NOTE: keep this in sync with `rustdoc::clean::utils::doc_rust_lang_org_channel`, or tests will fail on beta/stable.
727     pub fn doc_rust_lang_org_channel(&self) -> String {
728         let channel = match &*self.config.channel {
729             "stable" => &self.version,
730             "beta" => "beta",
731             "nightly" | "dev" => "nightly",
732             // custom build of rustdoc maybe? link to the latest stable docs just in case
733             _ => "stable",
734         };
735         "https://doc.rust-lang.org/".to_owned() + channel
736     }
737
738     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
739         StepDescription::run(v, self, paths);
740     }
741
742     /// Obtain a compiler at a given stage and for a given host. Explicitly does
743     /// not take `Compiler` since all `Compiler` instances are meant to be
744     /// obtained through this function, since it ensures that they are valid
745     /// (i.e., built and assembled).
746     pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
747         self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
748     }
749
750     /// Similar to `compiler`, except handles the full-bootstrap option to
751     /// silently use the stage1 compiler instead of a stage2 compiler if one is
752     /// requested.
753     ///
754     /// Note that this does *not* have the side effect of creating
755     /// `compiler(stage, host)`, unlike `compiler` above which does have such
756     /// a side effect. The returned compiler here can only be used to compile
757     /// new artifacts, it can't be used to rely on the presence of a particular
758     /// sysroot.
759     ///
760     /// See `force_use_stage1` for documentation on what each argument is.
761     pub fn compiler_for(
762         &self,
763         stage: u32,
764         host: TargetSelection,
765         target: TargetSelection,
766     ) -> Compiler {
767         if self.build.force_use_stage1(Compiler { stage, host }, target) {
768             self.compiler(1, self.config.build)
769         } else {
770             self.compiler(stage, host)
771         }
772     }
773
774     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
775         self.ensure(compile::Sysroot { compiler })
776     }
777
778     /// Returns the libdir where the standard library and other artifacts are
779     /// found for a compiler's sysroot.
780     pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
781         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
782         struct Libdir {
783             compiler: Compiler,
784             target: TargetSelection,
785         }
786         impl Step for Libdir {
787             type Output = Interned<PathBuf>;
788
789             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
790                 run.never()
791             }
792
793             fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
794                 let lib = builder.sysroot_libdir_relative(self.compiler);
795                 let sysroot = builder
796                     .sysroot(self.compiler)
797                     .join(lib)
798                     .join("rustlib")
799                     .join(self.target.triple)
800                     .join("lib");
801                 // Avoid deleting the rustlib/ directory we just copied
802                 // (in `impl Step for Sysroot`).
803                 if !builder.config.download_rustc {
804                     let _ = fs::remove_dir_all(&sysroot);
805                     t!(fs::create_dir_all(&sysroot));
806                 }
807                 INTERNER.intern_path(sysroot)
808             }
809         }
810         self.ensure(Libdir { compiler, target })
811     }
812
813     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
814         self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
815     }
816
817     /// Returns the compiler's libdir where it stores the dynamic libraries that
818     /// it itself links against.
819     ///
820     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
821     /// Windows.
822     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
823         if compiler.is_snapshot(self) {
824             self.rustc_snapshot_libdir()
825         } else {
826             match self.config.libdir_relative() {
827                 Some(relative_libdir) if compiler.stage >= 1 => {
828                     self.sysroot(compiler).join(relative_libdir)
829                 }
830                 _ => self.sysroot(compiler).join(libdir(compiler.host)),
831             }
832         }
833     }
834
835     /// Returns the compiler's relative libdir where it stores the dynamic libraries that
836     /// it itself links against.
837     ///
838     /// For example this returns `lib` on Unix and `bin` on
839     /// Windows.
840     pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
841         if compiler.is_snapshot(self) {
842             libdir(self.config.build).as_ref()
843         } else {
844             match self.config.libdir_relative() {
845                 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
846                 _ => libdir(compiler.host).as_ref(),
847             }
848         }
849     }
850
851     /// Returns the compiler's relative libdir where the standard library and other artifacts are
852     /// found for a compiler's sysroot.
853     ///
854     /// For example this returns `lib` on Unix and Windows.
855     pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
856         match self.config.libdir_relative() {
857             Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
858             _ if compiler.stage == 0 => &self.build.initial_libdir,
859             _ => Path::new("lib"),
860         }
861     }
862
863     pub fn rustc_lib_paths(&self, compiler: Compiler) -> Vec<PathBuf> {
864         let mut dylib_dirs = vec![self.rustc_libdir(compiler)];
865
866         // Ensure that the downloaded LLVM libraries can be found.
867         if self.config.llvm_from_ci {
868             let ci_llvm_lib = self.out.join(&*compiler.host.triple).join("ci-llvm").join("lib");
869             dylib_dirs.push(ci_llvm_lib);
870         }
871
872         dylib_dirs
873     }
874
875     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
876     /// library lookup path.
877     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
878         // Windows doesn't need dylib path munging because the dlls for the
879         // compiler live next to the compiler and the system will find them
880         // automatically.
881         if cfg!(windows) {
882             return;
883         }
884
885         add_dylib_path(self.rustc_lib_paths(compiler), cmd);
886     }
887
888     /// Gets a path to the compiler specified.
889     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
890         if compiler.is_snapshot(self) {
891             self.initial_rustc.clone()
892         } else {
893             self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
894         }
895     }
896
897     /// Gets the paths to all of the compiler's codegen backends.
898     fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
899         fs::read_dir(self.sysroot_codegen_backends(compiler))
900             .into_iter()
901             .flatten()
902             .filter_map(Result::ok)
903             .map(|entry| entry.path())
904     }
905
906     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
907         self.ensure(tool::Rustdoc { compiler })
908     }
909
910     pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
911         let mut cmd = Command::new(&self.bootstrap_out.join("rustdoc"));
912         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
913             .env("RUSTC_SYSROOT", self.sysroot(compiler))
914             // Note that this is *not* the sysroot_libdir because rustdoc must be linked
915             // equivalently to rustc.
916             .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
917             .env("CFG_RELEASE_CHANNEL", &self.config.channel)
918             .env("RUSTDOC_REAL", self.rustdoc(compiler))
919             .env("RUSTC_BOOTSTRAP", "1");
920
921         cmd.arg("-Wrustdoc::invalid_codeblock_attributes");
922
923         if self.config.deny_warnings {
924             cmd.arg("-Dwarnings");
925         }
926         cmd.arg("-Znormalize-docs");
927
928         // Remove make-related flags that can cause jobserver problems.
929         cmd.env_remove("MAKEFLAGS");
930         cmd.env_remove("MFLAGS");
931
932         if let Some(linker) = self.linker(compiler.host) {
933             cmd.env("RUSTDOC_LINKER", linker);
934         }
935         if self.is_fuse_ld_lld(compiler.host) {
936             cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
937         }
938         cmd
939     }
940
941     /// Return the path to `llvm-config` for the target, if it exists.
942     ///
943     /// Note that this returns `None` if LLVM is disabled, or if we're in a
944     /// check build or dry-run, where there's no need to build all of LLVM.
945     fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
946         if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
947             let llvm_config = self.ensure(native::Llvm { target });
948             if llvm_config.is_file() {
949                 return Some(llvm_config);
950             }
951         }
952         None
953     }
954
955     /// Prepares an invocation of `cargo` to be run.
956     ///
957     /// This will create a `Command` that represents a pending execution of
958     /// Cargo. This cargo will be configured to use `compiler` as the actual
959     /// rustc compiler, its output will be scoped by `mode`'s output directory,
960     /// it will pass the `--target` flag for the specified `target`, and will be
961     /// executing the Cargo command `cmd`.
962     pub fn cargo(
963         &self,
964         compiler: Compiler,
965         mode: Mode,
966         source_type: SourceType,
967         target: TargetSelection,
968         cmd: &str,
969     ) -> Cargo {
970         let mut cargo = Command::new(&self.initial_cargo);
971         let out_dir = self.stage_out(compiler, mode);
972
973         // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
974         // so we need to explicitly clear out if they've been updated.
975         for backend in self.codegen_backends(compiler) {
976             self.clear_if_dirty(&out_dir, &backend);
977         }
978
979         if cmd == "doc" || cmd == "rustdoc" {
980             let my_out = match mode {
981                 // This is the intended out directory for compiler documentation.
982                 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
983                 Mode::Std => out_dir.join(target.triple).join("doc"),
984                 _ => panic!("doc mode {:?} not expected", mode),
985             };
986             let rustdoc = self.rustdoc(compiler);
987             self.clear_if_dirty(&my_out, &rustdoc);
988         }
989
990         cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
991
992         let profile_var = |name: &str| {
993             let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
994             format!("CARGO_PROFILE_{}_{}", profile, name)
995         };
996
997         // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
998         // needs to not accidentally link to libLLVM in stage0/lib.
999         cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
1000         if let Some(e) = env::var_os(util::dylib_path_var()) {
1001             cargo.env("REAL_LIBRARY_PATH", e);
1002         }
1003
1004         // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
1005         // from out of tree it shouldn't matter, since x.py is only used for
1006         // building in-tree.
1007         let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
1008         match self.build.config.color {
1009             Color::Always => {
1010                 cargo.arg("--color=always");
1011                 for log in &color_logs {
1012                     cargo.env(log, "always");
1013                 }
1014             }
1015             Color::Never => {
1016                 cargo.arg("--color=never");
1017                 for log in &color_logs {
1018                     cargo.env(log, "never");
1019                 }
1020             }
1021             Color::Auto => {} // nothing to do
1022         }
1023
1024         if cmd != "install" {
1025             cargo.arg("--target").arg(target.rustc_target_arg());
1026         } else {
1027             assert_eq!(target, compiler.host);
1028         }
1029
1030         // Set a flag for `check`/`clippy`/`fix`, so that certain build
1031         // scripts can do less work (i.e. not building/requiring LLVM).
1032         if cmd == "check" || cmd == "clippy" || cmd == "fix" {
1033             // If we've not yet built LLVM, or it's stale, then bust
1034             // the rustc_llvm cache. That will always work, even though it
1035             // may mean that on the next non-check build we'll need to rebuild
1036             // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
1037             // of work comparatively, and we'd likely need to rebuild it anyway,
1038             // so that's okay.
1039             if crate::native::prebuilt_llvm_config(self, target).is_err() {
1040                 cargo.env("RUST_CHECK", "1");
1041             }
1042         }
1043
1044         let stage = if compiler.stage == 0 && self.local_rebuild {
1045             // Assume the local-rebuild rustc already has stage1 features.
1046             1
1047         } else {
1048             compiler.stage
1049         };
1050
1051         let mut rustflags = Rustflags::new(target);
1052         if stage != 0 {
1053             if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
1054                 cargo.args(s.split_whitespace());
1055             }
1056             rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
1057         } else {
1058             if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
1059                 cargo.args(s.split_whitespace());
1060             }
1061             rustflags.env("RUSTFLAGS_BOOTSTRAP");
1062             if cmd == "clippy" {
1063                 // clippy overwrites sysroot if we pass it to cargo.
1064                 // Pass it directly to clippy instead.
1065                 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
1066                 // so it has no way of knowing the sysroot.
1067                 rustflags.arg("--sysroot");
1068                 rustflags.arg(
1069                     self.sysroot(compiler)
1070                         .as_os_str()
1071                         .to_str()
1072                         .expect("sysroot must be valid UTF-8"),
1073                 );
1074                 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
1075                 cargo.arg("-Zunstable-options");
1076                 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
1077                 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
1078                 let output = host_version.and_then(|output| {
1079                     if output.status.success() {
1080                         Ok(output)
1081                     } else {
1082                         Err(())
1083                     }
1084                 }).unwrap_or_else(|_| {
1085                     eprintln!(
1086                         "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
1087                     );
1088                     eprintln!("help: try `rustup component add clippy`");
1089                     std::process::exit(1);
1090                 });
1091                 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
1092                     rustflags.arg("--cfg=bootstrap");
1093                 }
1094             } else {
1095                 rustflags.arg("--cfg=bootstrap");
1096             }
1097         }
1098
1099         let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
1100             Some(setting) => {
1101                 // If an explicit setting is given, use that
1102                 setting
1103             }
1104             None => {
1105                 if mode == Mode::Std {
1106                     // The standard library defaults to the legacy scheme
1107                     false
1108                 } else {
1109                     // The compiler and tools default to the new scheme
1110                     true
1111                 }
1112             }
1113         };
1114
1115         if use_new_symbol_mangling {
1116             rustflags.arg("-Csymbol-mangling-version=v0");
1117         } else {
1118             rustflags.arg("-Csymbol-mangling-version=legacy");
1119             rustflags.arg("-Zunstable-options");
1120         }
1121
1122         // #[cfg(not(bootstrap)]
1123         if stage != 0 {
1124             // Enable cfg checking of cargo features
1125             // FIXME: De-comment this when cargo beta get support for it
1126             // cargo.arg("-Zcheck-cfg-features");
1127
1128             // Enable cfg checking of rustc well-known names
1129             rustflags
1130                 .arg("-Zunstable-options")
1131                 // Enable checking of well known names
1132                 .arg("--check-cfg=names()")
1133                 // Enable checking of well known values
1134                 .arg("--check-cfg=values()");
1135
1136             // Add extra cfg not defined in rustc
1137             for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
1138                 if *restricted_mode == None || *restricted_mode == Some(mode) {
1139                     // Creating a string of the values by concatenating each value:
1140                     // ',"tvos","watchos"' or '' (nothing) when there are no values
1141                     let values = match values {
1142                         Some(values) => values
1143                             .iter()
1144                             .map(|val| [",", "\"", val, "\""])
1145                             .flatten()
1146                             .collect::<String>(),
1147                         None => String::new(),
1148                     };
1149                     rustflags.arg(&format!("--check-cfg=values({name}{values})"));
1150                 }
1151             }
1152         }
1153
1154         // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
1155         // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
1156         // #71458.
1157         let mut rustdocflags = rustflags.clone();
1158         rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
1159         if stage == 0 {
1160             rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
1161         } else {
1162             rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
1163         }
1164
1165         if let Ok(s) = env::var("CARGOFLAGS") {
1166             cargo.args(s.split_whitespace());
1167         }
1168
1169         match mode {
1170             Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
1171             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
1172                 // Build proc macros both for the host and the target
1173                 if target != compiler.host && cmd != "check" {
1174                     cargo.arg("-Zdual-proc-macros");
1175                     rustflags.arg("-Zdual-proc-macros");
1176                 }
1177             }
1178         }
1179
1180         // This tells Cargo (and in turn, rustc) to output more complete
1181         // dependency information.  Most importantly for rustbuild, this
1182         // includes sysroot artifacts, like libstd, which means that we don't
1183         // need to track those in rustbuild (an error prone process!). This
1184         // feature is currently unstable as there may be some bugs and such, but
1185         // it represents a big improvement in rustbuild's reliability on
1186         // rebuilds, so we're using it here.
1187         //
1188         // For some additional context, see #63470 (the PR originally adding
1189         // this), as well as #63012 which is the tracking issue for this
1190         // feature on the rustc side.
1191         cargo.arg("-Zbinary-dep-depinfo");
1192
1193         cargo.arg("-j").arg(self.jobs().to_string());
1194         // Remove make-related flags to ensure Cargo can correctly set things up
1195         cargo.env_remove("MAKEFLAGS");
1196         cargo.env_remove("MFLAGS");
1197
1198         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
1199         // Force cargo to output binaries with disambiguating hashes in the name
1200         let mut metadata = if compiler.stage == 0 {
1201             // Treat stage0 like a special channel, whether it's a normal prior-
1202             // release rustc or a local rebuild with the same version, so we
1203             // never mix these libraries by accident.
1204             "bootstrap".to_string()
1205         } else {
1206             self.config.channel.to_string()
1207         };
1208         // We want to make sure that none of the dependencies between
1209         // std/test/rustc unify with one another. This is done for weird linkage
1210         // reasons but the gist of the problem is that if librustc, libtest, and
1211         // libstd all depend on libc from crates.io (which they actually do) we
1212         // want to make sure they all get distinct versions. Things get really
1213         // weird if we try to unify all these dependencies right now, namely
1214         // around how many times the library is linked in dynamic libraries and
1215         // such. If rustc were a static executable or if we didn't ship dylibs
1216         // this wouldn't be a problem, but we do, so it is. This is in general
1217         // just here to make sure things build right. If you can remove this and
1218         // things still build right, please do!
1219         match mode {
1220             Mode::Std => metadata.push_str("std"),
1221             // When we're building rustc tools, they're built with a search path
1222             // that contains things built during the rustc build. For example,
1223             // bitflags is built during the rustc build, and is a dependency of
1224             // rustdoc as well. We're building rustdoc in a different target
1225             // directory, though, which means that Cargo will rebuild the
1226             // dependency. When we go on to build rustdoc, we'll look for
1227             // bitflags, and find two different copies: one built during the
1228             // rustc step and one that we just built. This isn't always a
1229             // problem, somehow -- not really clear why -- but we know that this
1230             // fixes things.
1231             Mode::ToolRustc => metadata.push_str("tool-rustc"),
1232             // Same for codegen backends.
1233             Mode::Codegen => metadata.push_str("codegen"),
1234             _ => {}
1235         }
1236         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
1237
1238         if cmd == "clippy" {
1239             rustflags.arg("-Zforce-unstable-if-unmarked");
1240         }
1241
1242         rustflags.arg("-Zmacro-backtrace");
1243
1244         let want_rustdoc = self.doc_tests != DocTests::No;
1245
1246         // We synthetically interpret a stage0 compiler used to build tools as a
1247         // "raw" compiler in that it's the exact snapshot we download. Normally
1248         // the stage0 build means it uses libraries build by the stage0
1249         // compiler, but for tools we just use the precompiled libraries that
1250         // we've downloaded
1251         let use_snapshot = mode == Mode::ToolBootstrap;
1252         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1253
1254         let maybe_sysroot = self.sysroot(compiler);
1255         let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1256         let libdir = self.rustc_libdir(compiler);
1257
1258         // Clear the output directory if the real rustc we're using has changed;
1259         // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1260         //
1261         // Avoid doing this during dry run as that usually means the relevant
1262         // compiler is not yet linked/copied properly.
1263         //
1264         // Only clear out the directory if we're compiling std; otherwise, we
1265         // should let Cargo take care of things for us (via depdep info)
1266         if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
1267             self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1268         }
1269
1270         // Customize the compiler we're running. Specify the compiler to cargo
1271         // as our shim and then pass it some various options used to configure
1272         // how the actual compiler itself is called.
1273         //
1274         // These variables are primarily all read by
1275         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1276         cargo
1277             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1278             .env("RUSTC_REAL", self.rustc(compiler))
1279             .env("RUSTC_STAGE", stage.to_string())
1280             .env("RUSTC_SYSROOT", &sysroot)
1281             .env("RUSTC_LIBDIR", &libdir)
1282             .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
1283             .env(
1284                 "RUSTDOC_REAL",
1285                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1286                     self.rustdoc(compiler)
1287                 } else {
1288                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1289                 },
1290             )
1291             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1292             .env("RUSTC_BREAK_ON_ICE", "1");
1293         // Clippy support is a hack and uses the default `cargo-clippy` in path.
1294         // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1295         if cmd != "clippy" {
1296             cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
1297         }
1298
1299         // Dealing with rpath here is a little special, so let's go into some
1300         // detail. First off, `-rpath` is a linker option on Unix platforms
1301         // which adds to the runtime dynamic loader path when looking for
1302         // dynamic libraries. We use this by default on Unix platforms to ensure
1303         // that our nightlies behave the same on Windows, that is they work out
1304         // of the box. This can be disabled, of course, but basically that's why
1305         // we're gated on RUSTC_RPATH here.
1306         //
1307         // Ok, so the astute might be wondering "why isn't `-C rpath` used
1308         // here?" and that is indeed a good question to ask. This codegen
1309         // option is the compiler's current interface to generating an rpath.
1310         // Unfortunately it doesn't quite suffice for us. The flag currently
1311         // takes no value as an argument, so the compiler calculates what it
1312         // should pass to the linker as `-rpath`. This unfortunately is based on
1313         // the **compile time** directory structure which when building with
1314         // Cargo will be very different than the runtime directory structure.
1315         //
1316         // All that's a really long winded way of saying that if we use
1317         // `-Crpath` then the executables generated have the wrong rpath of
1318         // something like `$ORIGIN/deps` when in fact the way we distribute
1319         // rustc requires the rpath to be `$ORIGIN/../lib`.
1320         //
1321         // So, all in all, to set up the correct rpath we pass the linker
1322         // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1323         // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1324         // to change a flag in a binary?
1325         if self.config.rust_rpath && util::use_host_linker(target) {
1326             let rpath = if target.contains("apple") {
1327                 // Note that we need to take one extra step on macOS to also pass
1328                 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1329                 // do that we pass a weird flag to the compiler to get it to do
1330                 // so. Note that this is definitely a hack, and we should likely
1331                 // flesh out rpath support more fully in the future.
1332                 rustflags.arg("-Zosx-rpath-install-name");
1333                 Some("-Wl,-rpath,@loader_path/../lib")
1334             } else if !target.contains("windows") {
1335                 rustflags.arg("-Clink-args=-Wl,-z,origin");
1336                 Some("-Wl,-rpath,$ORIGIN/../lib")
1337             } else {
1338                 None
1339             };
1340             if let Some(rpath) = rpath {
1341                 rustflags.arg(&format!("-Clink-args={}", rpath));
1342             }
1343         }
1344
1345         if let Some(host_linker) = self.linker(compiler.host) {
1346             cargo.env("RUSTC_HOST_LINKER", host_linker);
1347         }
1348         if self.is_fuse_ld_lld(compiler.host) {
1349             cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1350             cargo.env("RUSTDOC_FUSE_LD_LLD", "1");
1351         }
1352
1353         if let Some(target_linker) = self.linker(target) {
1354             let target = crate::envify(&target.triple);
1355             cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1356         }
1357         if self.is_fuse_ld_lld(target) {
1358             rustflags.arg("-Clink-args=-fuse-ld=lld");
1359         }
1360         self.lld_flags(target).for_each(|flag| {
1361             rustdocflags.arg(&flag);
1362         });
1363
1364         if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1365             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1366         }
1367
1368         let debuginfo_level = match mode {
1369             Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1370             Mode::Std => self.config.rust_debuginfo_level_std,
1371             Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1372                 self.config.rust_debuginfo_level_tools
1373             }
1374         };
1375         cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1376         cargo.env(
1377             profile_var("DEBUG_ASSERTIONS"),
1378             if mode == Mode::Std {
1379                 self.config.rust_debug_assertions_std.to_string()
1380             } else {
1381                 self.config.rust_debug_assertions.to_string()
1382             },
1383         );
1384         cargo.env(
1385             profile_var("OVERFLOW_CHECKS"),
1386             if mode == Mode::Std {
1387                 self.config.rust_overflow_checks_std.to_string()
1388             } else {
1389                 self.config.rust_overflow_checks.to_string()
1390             },
1391         );
1392
1393         // FIXME(davidtwco): #[cfg(not(bootstrap))] - #95612 needs to be in the bootstrap compiler
1394         // for this conditional to be removed.
1395         if !target.contains("windows") || compiler.stage >= 1 {
1396             if target.contains("linux") || target.contains("windows") {
1397                 rustflags.arg("-Zunstable-options");
1398             }
1399             match self.config.rust_split_debuginfo {
1400                 SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
1401                 SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
1402                 SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
1403             };
1404         }
1405
1406         if self.config.cmd.bless() {
1407             // Bless `expect!` tests.
1408             cargo.env("UPDATE_EXPECT", "1");
1409         }
1410
1411         if !mode.is_tool() {
1412             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1413         }
1414
1415         if let Some(x) = self.crt_static(target) {
1416             if x {
1417                 rustflags.arg("-Ctarget-feature=+crt-static");
1418             } else {
1419                 rustflags.arg("-Ctarget-feature=-crt-static");
1420             }
1421         }
1422
1423         if let Some(x) = self.crt_static(compiler.host) {
1424             cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1425         }
1426
1427         if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1428             let map = format!("{}={}", self.build.src.display(), map_to);
1429             cargo.env("RUSTC_DEBUGINFO_MAP", map);
1430
1431             // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1432             // in order to opportunistically reverse it later.
1433             cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1434         }
1435
1436         // Enable usage of unstable features
1437         cargo.env("RUSTC_BOOTSTRAP", "1");
1438         self.add_rust_test_threads(&mut cargo);
1439
1440         // Almost all of the crates that we compile as part of the bootstrap may
1441         // have a build script, including the standard library. To compile a
1442         // build script, however, it itself needs a standard library! This
1443         // introduces a bit of a pickle when we're compiling the standard
1444         // library itself.
1445         //
1446         // To work around this we actually end up using the snapshot compiler
1447         // (stage0) for compiling build scripts of the standard library itself.
1448         // The stage0 compiler is guaranteed to have a libstd available for use.
1449         //
1450         // For other crates, however, we know that we've already got a standard
1451         // library up and running, so we can use the normal compiler to compile
1452         // build scripts in that situation.
1453         if mode == Mode::Std {
1454             cargo
1455                 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1456                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1457         } else {
1458             cargo
1459                 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1460                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1461         }
1462
1463         // Tools that use compiler libraries may inherit the `-lLLVM` link
1464         // requirement, but the `-L` library path is not propagated across
1465         // separate Cargo projects. We can add LLVM's library path to the
1466         // platform-specific environment variable as a workaround.
1467         if mode == Mode::ToolRustc || mode == Mode::Codegen {
1468             if let Some(llvm_config) = self.llvm_config(target) {
1469                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1470                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1471             }
1472         }
1473
1474         // Compile everything except libraries and proc macros with the more
1475         // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1476         // so we can't use it by default in general, but we can use it for tools
1477         // and our own internal libraries.
1478         if !mode.must_support_dlopen() && !target.triple.starts_with("powerpc-") {
1479             rustflags.arg("-Ztls-model=initial-exec");
1480         }
1481
1482         if self.config.incremental {
1483             cargo.env("CARGO_INCREMENTAL", "1");
1484         } else {
1485             // Don't rely on any default setting for incr. comp. in Cargo
1486             cargo.env("CARGO_INCREMENTAL", "0");
1487         }
1488
1489         if let Some(ref on_fail) = self.config.on_fail {
1490             cargo.env("RUSTC_ON_FAIL", on_fail);
1491         }
1492
1493         if self.config.print_step_timings {
1494             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1495         }
1496
1497         if self.config.print_step_rusage {
1498             cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1499         }
1500
1501         if self.config.backtrace_on_ice {
1502             cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1503         }
1504
1505         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1506
1507         if source_type == SourceType::InTree {
1508             let mut lint_flags = Vec::new();
1509             // When extending this list, add the new lints to the RUSTFLAGS of the
1510             // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1511             // some code doesn't go through this `rustc` wrapper.
1512             lint_flags.push("-Wrust_2018_idioms");
1513             lint_flags.push("-Wunused_lifetimes");
1514             lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1515
1516             if self.config.deny_warnings {
1517                 lint_flags.push("-Dwarnings");
1518                 rustdocflags.arg("-Dwarnings");
1519             }
1520
1521             // This does not use RUSTFLAGS due to caching issues with Cargo.
1522             // Clippy is treated as an "in tree" tool, but shares the same
1523             // cache as other "submodule" tools. With these options set in
1524             // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1525             // By injecting this into the rustc wrapper, this circumvents
1526             // Cargo's fingerprint detection. This is fine because lint flags
1527             // are always ignored in dependencies. Eventually this should be
1528             // fixed via better support from Cargo.
1529             cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1530
1531             rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1532         }
1533
1534         if mode == Mode::Rustc {
1535             rustflags.arg("-Zunstable-options");
1536             rustflags.arg("-Wrustc::internal");
1537         }
1538
1539         // Throughout the build Cargo can execute a number of build scripts
1540         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1541         // obtained previously to those build scripts.
1542         // Build scripts use either the `cc` crate or `configure/make` so we pass
1543         // the options through environment variables that are fetched and understood by both.
1544         //
1545         // FIXME: the guard against msvc shouldn't need to be here
1546         if target.contains("msvc") {
1547             if let Some(ref cl) = self.config.llvm_clang_cl {
1548                 cargo.env("CC", cl).env("CXX", cl);
1549             }
1550         } else {
1551             let ccache = self.config.ccache.as_ref();
1552             let ccacheify = |s: &Path| {
1553                 let ccache = match ccache {
1554                     Some(ref s) => s,
1555                     None => return s.display().to_string(),
1556                 };
1557                 // FIXME: the cc-rs crate only recognizes the literal strings
1558                 // `ccache` and `sccache` when doing caching compilations, so we
1559                 // mirror that here. It should probably be fixed upstream to
1560                 // accept a new env var or otherwise work with custom ccache
1561                 // vars.
1562                 match &ccache[..] {
1563                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1564                     _ => s.display().to_string(),
1565                 }
1566             };
1567             let cc = ccacheify(&self.cc(target));
1568             cargo.env(format!("CC_{}", target.triple), &cc);
1569
1570             let cflags = self.cflags(target, GitRepo::Rustc, CLang::C).join(" ");
1571             cargo.env(format!("CFLAGS_{}", target.triple), &cflags);
1572
1573             if let Some(ar) = self.ar(target) {
1574                 let ranlib = format!("{} s", ar.display());
1575                 cargo
1576                     .env(format!("AR_{}", target.triple), ar)
1577                     .env(format!("RANLIB_{}", target.triple), ranlib);
1578             }
1579
1580             if let Ok(cxx) = self.cxx(target) {
1581                 let cxx = ccacheify(&cxx);
1582                 let cxxflags = self.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" ");
1583                 cargo
1584                     .env(format!("CXX_{}", target.triple), &cxx)
1585                     .env(format!("CXXFLAGS_{}", target.triple), cxxflags);
1586             }
1587         }
1588
1589         if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1590             rustflags.arg("-Zsave-analysis");
1591             cargo.env(
1592                 "RUST_SAVE_ANALYSIS_CONFIG",
1593                 "{\"output_file\": null,\"full_docs\": false,\
1594                        \"pub_only\": true,\"reachable_only\": false,\
1595                        \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1596             );
1597         }
1598
1599         // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1600         // when compiling the standard library, since this might be linked into the final outputs
1601         // produced by rustc. Since this mitigation is only available on Windows, only enable it
1602         // for the standard library in case the compiler is run on a non-Windows platform.
1603         // This is not needed for stage 0 artifacts because these will only be used for building
1604         // the stage 1 compiler.
1605         if cfg!(windows)
1606             && mode == Mode::Std
1607             && self.config.control_flow_guard
1608             && compiler.stage >= 1
1609         {
1610             rustflags.arg("-Ccontrol-flow-guard");
1611         }
1612
1613         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1614         // This replaces spaces with newlines because RUSTDOCFLAGS does not
1615         // support arguments with regular spaces. Hopefully someday Cargo will
1616         // have space support.
1617         let rust_version = self.rust_version().replace(' ', "\n");
1618         rustdocflags.arg("--crate-version").arg(&rust_version);
1619
1620         // Environment variables *required* throughout the build
1621         //
1622         // FIXME: should update code to not require this env var
1623         cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1624
1625         // Set this for all builds to make sure doc builds also get it.
1626         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1627
1628         // This one's a bit tricky. As of the time of this writing the compiler
1629         // links to the `winapi` crate on crates.io. This crate provides raw
1630         // bindings to Windows system functions, sort of like libc does for
1631         // Unix. This crate also, however, provides "import libraries" for the
1632         // MinGW targets. There's an import library per dll in the windows
1633         // distribution which is what's linked to. These custom import libraries
1634         // are used because the winapi crate can reference Windows functions not
1635         // present in the MinGW import libraries.
1636         //
1637         // For example MinGW may ship libdbghelp.a, but it may not have
1638         // references to all the functions in the dbghelp dll. Instead the
1639         // custom import library for dbghelp in the winapi crates has all this
1640         // information.
1641         //
1642         // Unfortunately for us though the import libraries are linked by
1643         // default via `-ldylib=winapi_foo`. That is, they're linked with the
1644         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1645         // conflict with the system MinGW ones). This consequently means that
1646         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1647         // DLL) when linked against *again*, for example with procedural macros
1648         // or plugins, will trigger the propagation logic of `-ldylib`, passing
1649         // `-lwinapi_foo` to the linker again. This isn't actually available in
1650         // our distribution, however, so the link fails.
1651         //
1652         // To solve this problem we tell winapi to not use its bundled import
1653         // libraries. This means that it will link to the system MinGW import
1654         // libraries by default, and the `-ldylib=foo` directives will still get
1655         // passed to the final linker, but they'll look like `-lfoo` which can
1656         // be resolved because MinGW has the import library. The downside is we
1657         // don't get newer functions from Windows, but we don't use any of them
1658         // anyway.
1659         if !mode.is_tool() {
1660             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1661         }
1662
1663         for _ in 0..self.verbosity {
1664             cargo.arg("-v");
1665         }
1666
1667         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1668             (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1669                 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1670             }
1671             _ => {
1672                 // Don't set anything
1673             }
1674         }
1675
1676         if self.config.rust_optimize {
1677             // FIXME: cargo bench/install do not accept `--release`
1678             if cmd != "bench" && cmd != "install" {
1679                 cargo.arg("--release");
1680             }
1681         }
1682
1683         if self.config.locked_deps {
1684             cargo.arg("--locked");
1685         }
1686         if self.config.vendor || self.is_sudo {
1687             cargo.arg("--frozen");
1688         }
1689
1690         // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1691         cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1692
1693         self.ci_env.force_coloring_in_ci(&mut cargo);
1694
1695         // When we build Rust dylibs they're all intended for intermediate
1696         // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1697         // linking all deps statically into the dylib.
1698         if matches!(mode, Mode::Std | Mode::Rustc) {
1699             rustflags.arg("-Cprefer-dynamic");
1700         }
1701
1702         // When building incrementally we default to a lower ThinLTO import limit
1703         // (unless explicitly specified otherwise). This will produce a somewhat
1704         // slower code but give way better compile times.
1705         {
1706             let limit = match self.config.rust_thin_lto_import_instr_limit {
1707                 Some(limit) => Some(limit),
1708                 None if self.config.incremental => Some(10),
1709                 _ => None,
1710             };
1711
1712             if let Some(limit) = limit {
1713                 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1714             }
1715         }
1716
1717         Cargo { command: cargo, rustflags, rustdocflags }
1718     }
1719
1720     /// Ensure that a given step is built, returning its output. This will
1721     /// cache the step, so it is safe (and good!) to call this as often as
1722     /// needed to ensure that all dependencies are built.
1723     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1724         {
1725             let mut stack = self.stack.borrow_mut();
1726             for stack_step in stack.iter() {
1727                 // should skip
1728                 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1729                     continue;
1730                 }
1731                 let mut out = String::new();
1732                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1733                 for el in stack.iter().rev() {
1734                     out += &format!("\t{:?}\n", el);
1735                 }
1736                 panic!("{}", out);
1737             }
1738             if let Some(out) = self.cache.get(&step) {
1739                 self.verbose_than(1, &format!("{}c {:?}", "  ".repeat(stack.len()), step));
1740
1741                 return out;
1742             }
1743             self.verbose_than(1, &format!("{}> {:?}", "  ".repeat(stack.len()), step));
1744             stack.push(Box::new(step.clone()));
1745         }
1746
1747         let (out, dur) = {
1748             let start = Instant::now();
1749             let zero = Duration::new(0, 0);
1750             let parent = self.time_spent_on_dependencies.replace(zero);
1751             let out = step.clone().run(self);
1752             let dur = start.elapsed();
1753             let deps = self.time_spent_on_dependencies.replace(parent + dur);
1754             (out, dur - deps)
1755         };
1756
1757         if self.config.print_step_timings && !self.config.dry_run {
1758             println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis());
1759         }
1760
1761         {
1762             let mut stack = self.stack.borrow_mut();
1763             let cur_step = stack.pop().expect("step stack empty");
1764             assert_eq!(cur_step.downcast_ref(), Some(&step));
1765         }
1766         self.verbose_than(1, &format!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
1767         self.cache.put(step, out.clone());
1768         out
1769     }
1770
1771     /// Ensure that a given step is built *only if it's supposed to be built by default*, returning
1772     /// its output. This will cache the step, so it's safe (and good!) to call this as often as
1773     /// needed to ensure that all dependencies are build.
1774     pub(crate) fn ensure_if_default<T, S: Step<Output = Option<T>>>(
1775         &'a self,
1776         step: S,
1777         kind: Kind,
1778     ) -> S::Output {
1779         let desc = StepDescription::from::<S>(kind);
1780         let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1781
1782         // Avoid running steps contained in --exclude
1783         for pathset in &should_run.paths {
1784             if desc.is_excluded(self, pathset) {
1785                 return None;
1786             }
1787         }
1788
1789         // Only execute if it's supposed to run as default
1790         if desc.default && should_run.is_really_default() { self.ensure(step) } else { None }
1791     }
1792
1793     /// Checks if any of the "should_run" paths is in the `Builder` paths.
1794     pub(crate) fn was_invoked_explicitly<S: Step>(&'a self, kind: Kind) -> bool {
1795         let desc = StepDescription::from::<S>(kind);
1796         let should_run = (desc.should_run)(ShouldRun::new(self, desc.kind));
1797
1798         for path in &self.paths {
1799             if should_run.paths.iter().any(|s| s.has(path, Some(desc.kind)))
1800                 && !desc.is_excluded(
1801                     self,
1802                     &PathSet::Suite(TaskPath { path: path.clone(), kind: Some(desc.kind) }),
1803                 )
1804             {
1805                 return true;
1806             }
1807         }
1808
1809         false
1810     }
1811 }
1812
1813 #[cfg(test)]
1814 mod tests;
1815
1816 #[derive(Debug, Clone)]
1817 struct Rustflags(String, TargetSelection);
1818
1819 impl Rustflags {
1820     fn new(target: TargetSelection) -> Rustflags {
1821         let mut ret = Rustflags(String::new(), target);
1822         ret.propagate_cargo_env("RUSTFLAGS");
1823         ret
1824     }
1825
1826     /// By default, cargo will pick up on various variables in the environment. However, bootstrap
1827     /// reuses those variables to pass additional flags to rustdoc, so by default they get overridden.
1828     /// Explicitly add back any previous value in the environment.
1829     ///
1830     /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
1831     fn propagate_cargo_env(&mut self, prefix: &str) {
1832         // Inherit `RUSTFLAGS` by default ...
1833         self.env(prefix);
1834
1835         // ... and also handle target-specific env RUSTFLAGS if they're configured.
1836         let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
1837         self.env(&target_specific);
1838     }
1839
1840     fn env(&mut self, env: &str) {
1841         if let Ok(s) = env::var(env) {
1842             for part in s.split(' ') {
1843                 self.arg(part);
1844             }
1845         }
1846     }
1847
1848     fn arg(&mut self, arg: &str) -> &mut Self {
1849         assert_eq!(arg.split(' ').count(), 1);
1850         if !self.0.is_empty() {
1851             self.0.push(' ');
1852         }
1853         self.0.push_str(arg);
1854         self
1855     }
1856 }
1857
1858 #[derive(Debug)]
1859 pub struct Cargo {
1860     command: Command,
1861     rustflags: Rustflags,
1862     rustdocflags: Rustflags,
1863 }
1864
1865 impl Cargo {
1866     pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
1867         self.rustdocflags.arg(arg);
1868         self
1869     }
1870     pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1871         self.rustflags.arg(arg);
1872         self
1873     }
1874
1875     pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1876         self.command.arg(arg.as_ref());
1877         self
1878     }
1879
1880     pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1881     where
1882         I: IntoIterator<Item = S>,
1883         S: AsRef<OsStr>,
1884     {
1885         for arg in args {
1886             self.arg(arg.as_ref());
1887         }
1888         self
1889     }
1890
1891     pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1892         // These are managed through rustflag/rustdocflag interfaces.
1893         assert_ne!(key.as_ref(), "RUSTFLAGS");
1894         assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
1895         self.command.env(key.as_ref(), value.as_ref());
1896         self
1897     }
1898
1899     pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
1900         builder.add_rustc_lib_path(compiler, &mut self.command);
1901     }
1902
1903     pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
1904         self.command.current_dir(dir);
1905         self
1906     }
1907 }
1908
1909 impl From<Cargo> for Command {
1910     fn from(mut cargo: Cargo) -> Command {
1911         let rustflags = &cargo.rustflags.0;
1912         if !rustflags.is_empty() {
1913             cargo.command.env("RUSTFLAGS", rustflags);
1914         }
1915
1916         let rustdocflags = &cargo.rustdocflags.0;
1917         if !rustdocflags.is_empty() {
1918             cargo.command.env("RUSTDOCFLAGS", rustdocflags);
1919         }
1920
1921         cargo.command
1922     }
1923 }