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