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