]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/tool.rs
64e4be6863a62f824d2bf87ca2ddd2fdf93770c0
[rust.git] / src / bootstrap / tool.rs
1 use std::collections::HashSet;
2 use std::env;
3 use std::fs;
4 use std::path::PathBuf;
5 use std::process::{exit, Command};
6
7 use build_helper::t;
8
9 use crate::builder::{Builder, Cargo as CargoCommand, RunConfig, ShouldRun, Step};
10 use crate::channel::GitInfo;
11 use crate::compile;
12 use crate::config::TargetSelection;
13 use crate::toolstate::ToolState;
14 use crate::util::{add_dylib_path, exe};
15 use crate::Compiler;
16 use crate::Mode;
17
18 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
19 pub enum SourceType {
20     InTree,
21     Submodule,
22 }
23
24 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
25 struct ToolBuild {
26     compiler: Compiler,
27     target: TargetSelection,
28     tool: &'static str,
29     path: &'static str,
30     mode: Mode,
31     is_optional_tool: bool,
32     source_type: SourceType,
33     extra_features: Vec<String>,
34 }
35
36 impl Step for ToolBuild {
37     type Output = Option<PathBuf>;
38
39     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
40         run.never()
41     }
42
43     /// Builds a tool in `src/tools`
44     ///
45     /// This will build the specified tool with the specified `host` compiler in
46     /// `stage` into the normal cargo output directory.
47     fn run(self, builder: &Builder<'_>) -> Option<PathBuf> {
48         let compiler = self.compiler;
49         let target = self.target;
50         let mut tool = self.tool;
51         let path = self.path;
52         let is_optional_tool = self.is_optional_tool;
53
54         match self.mode {
55             Mode::ToolRustc => {
56                 builder.ensure(compile::Std { compiler, target: compiler.host });
57                 builder.ensure(compile::Rustc { compiler, target });
58             }
59             Mode::ToolStd => builder.ensure(compile::Std { compiler, target }),
60             Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
61             _ => panic!("unexpected Mode for tool build"),
62         }
63
64         let cargo = prepare_tool_cargo(
65             builder,
66             compiler,
67             self.mode,
68             target,
69             "build",
70             path,
71             self.source_type,
72             &self.extra_features,
73         );
74
75         builder.info(&format!("Building stage{} tool {} ({})", compiler.stage, tool, target));
76         let mut duplicates = Vec::new();
77         let is_expected = compile::stream_cargo(builder, cargo, vec![], &mut |msg| {
78             // Only care about big things like the RLS/Cargo for now
79             match tool {
80                 "rls" | "cargo" | "clippy-driver" | "miri" | "rustfmt" => {}
81
82                 _ => return,
83             }
84             let (id, features, filenames) = match msg {
85                 compile::CargoMessage::CompilerArtifact {
86                     package_id,
87                     features,
88                     filenames,
89                     target: _,
90                 } => (package_id, features, filenames),
91                 _ => return,
92             };
93             let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();
94
95             for path in filenames {
96                 let val = (tool, PathBuf::from(&*path), features.clone());
97                 // we're only interested in deduplicating rlibs for now
98                 if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
99                     continue;
100                 }
101
102                 // Don't worry about compiles that turn out to be host
103                 // dependencies or build scripts. To skip these we look for
104                 // anything that goes in `.../release/deps` but *doesn't* go in
105                 // `$target/release/deps`. This ensure that outputs in
106                 // `$target/release` are still considered candidates for
107                 // deduplication.
108                 if let Some(parent) = val.1.parent() {
109                     if parent.ends_with("release/deps") {
110                         let maybe_target = parent
111                             .parent()
112                             .and_then(|p| p.parent())
113                             .and_then(|p| p.file_name())
114                             .and_then(|p| p.to_str())
115                             .unwrap();
116                         if maybe_target != &*target.triple {
117                             continue;
118                         }
119                     }
120                 }
121
122                 // Record that we've built an artifact for `id`, and if one was
123                 // already listed then we need to see if we reused the same
124                 // artifact or produced a duplicate.
125                 let mut artifacts = builder.tool_artifacts.borrow_mut();
126                 let prev_artifacts = artifacts.entry(target).or_default();
127                 let prev = match prev_artifacts.get(&*id) {
128                     Some(prev) => prev,
129                     None => {
130                         prev_artifacts.insert(id.to_string(), val);
131                         continue;
132                     }
133                 };
134                 if prev.1 == val.1 {
135                     return; // same path, same artifact
136                 }
137
138                 // If the paths are different and one of them *isn't* inside of
139                 // `release/deps`, then it means it's probably in
140                 // `$target/release`, or it's some final artifact like
141                 // `libcargo.rlib`. In these situations Cargo probably just
142                 // copied it up from `$target/release/deps/libcargo-xxxx.rlib`,
143                 // so if the features are equal we can just skip it.
144                 let prev_no_hash = prev.1.parent().unwrap().ends_with("release/deps");
145                 let val_no_hash = val.1.parent().unwrap().ends_with("release/deps");
146                 if prev.2 == val.2 || !prev_no_hash || !val_no_hash {
147                     return;
148                 }
149
150                 // ... and otherwise this looks like we duplicated some sort of
151                 // compilation, so record it to generate an error later.
152                 duplicates.push((id.to_string(), val, prev.clone()));
153             }
154         });
155
156         if is_expected && !duplicates.is_empty() {
157             println!(
158                 "duplicate artifacts found when compiling a tool, this \
159                       typically means that something was recompiled because \
160                       a transitive dependency has different features activated \
161                       than in a previous build:\n"
162             );
163             println!(
164                 "the following dependencies are duplicated although they \
165                       have the same features enabled:"
166             );
167             let (same, different): (Vec<_>, Vec<_>) =
168                 duplicates.into_iter().partition(|(_, cur, prev)| cur.2 == prev.2);
169             for (id, cur, prev) in same {
170                 println!("  {}", id);
171                 // same features
172                 println!("    `{}` ({:?})\n    `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
173             }
174             println!("the following dependencies have different features:");
175             for (id, cur, prev) in different {
176                 println!("  {}", id);
177                 let cur_features: HashSet<_> = cur.2.into_iter().collect();
178                 let prev_features: HashSet<_> = prev.2.into_iter().collect();
179                 println!(
180                     "    `{}` additionally enabled features {:?} at {:?}",
181                     cur.0,
182                     &cur_features - &prev_features,
183                     cur.1
184                 );
185                 println!(
186                     "    `{}` additionally enabled features {:?} at {:?}",
187                     prev.0,
188                     &prev_features - &cur_features,
189                     prev.1
190                 );
191             }
192             println!();
193             println!(
194                 "to fix this you will probably want to edit the local \
195                       src/tools/rustc-workspace-hack/Cargo.toml crate, as \
196                       that will update the dependency graph to ensure that \
197                       these crates all share the same feature set"
198             );
199             panic!("tools should not compile multiple copies of the same crate");
200         }
201
202         builder.save_toolstate(
203             tool,
204             if is_expected { ToolState::TestFail } else { ToolState::BuildFail },
205         );
206
207         if !is_expected {
208             if !is_optional_tool {
209                 exit(1);
210             } else {
211                 None
212             }
213         } else {
214             // HACK(#82501): on Windows, the tools directory gets added to PATH when running tests, and
215             // compiletest confuses HTML tidy with the in-tree tidy. Name the in-tree tidy something
216             // different so the problem doesn't come up.
217             if tool == "tidy" {
218                 tool = "rust-tidy";
219             }
220             let cargo_out = builder.cargo_out(compiler, self.mode, target).join(exe(tool, target));
221             let bin = builder.tools_dir(compiler).join(exe(tool, target));
222             builder.copy(&cargo_out, &bin);
223             Some(bin)
224         }
225     }
226 }
227
228 pub fn prepare_tool_cargo(
229     builder: &Builder<'_>,
230     compiler: Compiler,
231     mode: Mode,
232     target: TargetSelection,
233     command: &'static str,
234     path: &'static str,
235     source_type: SourceType,
236     extra_features: &[String],
237 ) -> CargoCommand {
238     let mut cargo = builder.cargo(compiler, mode, source_type, target, command);
239     let dir = builder.src.join(path);
240     cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
241
242     let mut features = extra_features.to_vec();
243     if builder.build.config.cargo_native_static {
244         if path.ends_with("cargo")
245             || path.ends_with("rls")
246             || path.ends_with("clippy")
247             || path.ends_with("miri")
248             || path.ends_with("rustfmt")
249         {
250             cargo.env("LIBZ_SYS_STATIC", "1");
251             features.push("rustc-workspace-hack/all-static".to_string());
252         }
253     }
254
255     // if tools are using lzma we want to force the build script to build its
256     // own copy
257     cargo.env("LZMA_API_STATIC", "1");
258
259     // CFG_RELEASE is needed by rustfmt (and possibly other tools) which
260     // import rustc-ap-rustc_attr which requires this to be set for the
261     // `#[cfg(version(...))]` attribute.
262     cargo.env("CFG_RELEASE", builder.rust_release());
263     cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
264     cargo.env("CFG_VERSION", builder.rust_version());
265     cargo.env("CFG_RELEASE_NUM", &builder.version);
266
267     let info = GitInfo::new(builder.config.ignore_git, &dir);
268     if let Some(sha) = info.sha() {
269         cargo.env("CFG_COMMIT_HASH", sha);
270     }
271     if let Some(sha_short) = info.sha_short() {
272         cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
273     }
274     if let Some(date) = info.commit_date() {
275         cargo.env("CFG_COMMIT_DATE", date);
276     }
277     if !features.is_empty() {
278         cargo.arg("--features").arg(&features.join(", "));
279     }
280     cargo
281 }
282
283 macro_rules! bootstrap_tool {
284     ($(
285         $name:ident, $path:expr, $tool_name:expr
286         $(,is_external_tool = $external:expr)*
287         $(,is_unstable_tool = $unstable:expr)*
288         $(,features = $features:expr)*
289         ;
290     )+) => {
291         #[derive(Copy, PartialEq, Eq, Clone)]
292         pub enum Tool {
293             $(
294                 $name,
295             )+
296         }
297
298         impl<'a> Builder<'a> {
299             pub fn tool_exe(&self, tool: Tool) -> PathBuf {
300                 match tool {
301                     $(Tool::$name =>
302                         self.ensure($name {
303                             compiler: self.compiler(0, self.config.build),
304                             target: self.config.build,
305                         }),
306                     )+
307                 }
308             }
309         }
310
311         $(
312             #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
313         pub struct $name {
314             pub compiler: Compiler,
315             pub target: TargetSelection,
316         }
317
318         impl Step for $name {
319             type Output = PathBuf;
320
321             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
322                 run.path($path)
323             }
324
325             fn make_run(run: RunConfig<'_>) {
326                 run.builder.ensure($name {
327                     // snapshot compiler
328                     compiler: run.builder.compiler(0, run.builder.config.build),
329                     target: run.target,
330                 });
331             }
332
333             fn run(self, builder: &Builder<'_>) -> PathBuf {
334                 builder.ensure(ToolBuild {
335                     compiler: self.compiler,
336                     target: self.target,
337                     tool: $tool_name,
338                     mode: if false $(|| $unstable)* {
339                         // use in-tree libraries for unstable features
340                         Mode::ToolStd
341                     } else {
342                         Mode::ToolBootstrap
343                     },
344                     path: $path,
345                     is_optional_tool: false,
346                     source_type: if false $(|| $external)* {
347                         SourceType::Submodule
348                     } else {
349                         SourceType::InTree
350                     },
351                     extra_features: {
352                         // FIXME(#60643): avoid this lint by using `_`
353                         let mut _tmp = Vec::new();
354                         $(_tmp.extend($features);)*
355                         _tmp
356                     },
357                 }).expect("expected to build -- essential tool")
358             }
359         }
360         )+
361     }
362 }
363
364 bootstrap_tool!(
365     Rustbook, "src/tools/rustbook", "rustbook";
366     UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
367     Tidy, "src/tools/tidy", "tidy";
368     Linkchecker, "src/tools/linkchecker", "linkchecker";
369     CargoTest, "src/tools/cargotest", "cargotest";
370     Compiletest, "src/tools/compiletest", "compiletest", is_unstable_tool = true;
371     BuildManifest, "src/tools/build-manifest", "build-manifest";
372     RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
373     RustInstaller, "src/tools/rust-installer", "fabricate", is_external_tool = true;
374     RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
375     ExpandYamlAnchors, "src/tools/expand-yaml-anchors", "expand-yaml-anchors";
376     LintDocs, "src/tools/lint-docs", "lint-docs";
377     JsonDocCk, "src/tools/jsondocck", "jsondocck";
378 );
379
380 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
381 pub struct ErrorIndex {
382     pub compiler: Compiler,
383 }
384
385 impl ErrorIndex {
386     pub fn command(builder: &Builder<'_>) -> Command {
387         // This uses stage-1 to match the behavior of building rustdoc.
388         // Error-index-generator links with the rustdoc library, so we want to
389         // use the same librustdoc to avoid building rustdoc twice (and to
390         // avoid building the compiler an extra time). This uses
391         // saturating_sub to deal with building with stage 0. (Using stage 0
392         // isn't recommended, since it will fail if any new error index tests
393         // use new syntax, but it should work otherwise.)
394         let compiler = builder.compiler(builder.top_stage.saturating_sub(1), builder.config.build);
395         let mut cmd = Command::new(builder.ensure(ErrorIndex { compiler }));
396         add_dylib_path(
397             vec![
398                 PathBuf::from(&builder.sysroot_libdir(compiler, compiler.host)),
399                 PathBuf::from(builder.rustc_libdir(compiler)),
400             ],
401             &mut cmd,
402         );
403         cmd
404     }
405 }
406
407 impl Step for ErrorIndex {
408     type Output = PathBuf;
409
410     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
411         run.path("src/tools/error_index_generator")
412     }
413
414     fn make_run(run: RunConfig<'_>) {
415         // Compile the error-index in the same stage as rustdoc to avoid
416         // recompiling rustdoc twice if we can.
417         //
418         // NOTE: This `make_run` isn't used in normal situations, only if you
419         // manually build the tool with `x.py build
420         // src/tools/error-index-generator` which almost nobody does.
421         // Normally, `x.py test` or `x.py doc` will use the
422         // `ErrorIndex::command` function instead.
423         let compiler =
424             run.builder.compiler(run.builder.top_stage.saturating_sub(1), run.builder.config.build);
425         run.builder.ensure(ErrorIndex { compiler });
426     }
427
428     fn run(self, builder: &Builder<'_>) -> PathBuf {
429         builder
430             .ensure(ToolBuild {
431                 compiler: self.compiler,
432                 target: self.compiler.host,
433                 tool: "error_index_generator",
434                 mode: Mode::ToolRustc,
435                 path: "src/tools/error_index_generator",
436                 is_optional_tool: false,
437                 source_type: SourceType::InTree,
438                 extra_features: Vec::new(),
439             })
440             .expect("expected to build -- essential tool")
441     }
442 }
443
444 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
445 pub struct RemoteTestServer {
446     pub compiler: Compiler,
447     pub target: TargetSelection,
448 }
449
450 impl Step for RemoteTestServer {
451     type Output = PathBuf;
452
453     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
454         run.path("src/tools/remote-test-server")
455     }
456
457     fn make_run(run: RunConfig<'_>) {
458         run.builder.ensure(RemoteTestServer {
459             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
460             target: run.target,
461         });
462     }
463
464     fn run(self, builder: &Builder<'_>) -> PathBuf {
465         builder
466             .ensure(ToolBuild {
467                 compiler: self.compiler,
468                 target: self.target,
469                 tool: "remote-test-server",
470                 mode: Mode::ToolStd,
471                 path: "src/tools/remote-test-server",
472                 is_optional_tool: false,
473                 source_type: SourceType::InTree,
474                 extra_features: Vec::new(),
475             })
476             .expect("expected to build -- essential tool")
477     }
478 }
479
480 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
481 pub struct Rustdoc {
482     /// This should only ever be 0 or 2.
483     /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
484     pub compiler: Compiler,
485 }
486
487 impl Step for Rustdoc {
488     type Output = PathBuf;
489     const DEFAULT: bool = true;
490     const ONLY_HOSTS: bool = true;
491
492     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
493         run.path("src/tools/rustdoc").path("src/librustdoc")
494     }
495
496     fn make_run(run: RunConfig<'_>) {
497         run.builder.ensure(Rustdoc {
498             // Note: this is somewhat unique in that we actually want a *target*
499             // compiler here, because rustdoc *is* a compiler. We won't be using
500             // this as the compiler to build with, but rather this is "what
501             // compiler are we producing"?
502             compiler: run.builder.compiler(run.builder.top_stage, run.target),
503         });
504     }
505
506     fn run(self, builder: &Builder<'_>) -> PathBuf {
507         let target_compiler = self.compiler;
508         if target_compiler.stage == 0 {
509             if !target_compiler.is_snapshot(builder) {
510                 panic!("rustdoc in stage 0 must be snapshot rustdoc");
511             }
512             return builder.initial_rustc.with_file_name(exe("rustdoc", target_compiler.host));
513         }
514         let target = target_compiler.host;
515         // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
516         // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
517         // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
518         // rustc compiler it's paired with, so it must be built with the previous stage compiler.
519         let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
520
521         // When using `download-rustc` and a stage0 build_compiler, copying rustc doesn't actually
522         // build stage0 libstd (because the libstd in sysroot has the wrong ABI). Explicitly build
523         // it.
524         builder.ensure(compile::Std { compiler: build_compiler, target: target_compiler.host });
525         builder.ensure(compile::Rustc { compiler: build_compiler, target: target_compiler.host });
526         // NOTE: this implies that `download-rustc` is pretty useless when compiling with the stage0
527         // compiler, since you do just as much work.
528         if !builder.config.dry_run && builder.config.download_rustc && build_compiler.stage == 0 {
529             println!(
530                 "warning: `download-rustc` does nothing when building stage1 tools; consider using `--stage 2` instead"
531             );
532         }
533
534         // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
535         // compiler libraries, ...) are built. Rustdoc does not require the presence of any
536         // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
537         // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
538         // libraries here. The intuition here is that If we've built a compiler, we should be able
539         // to build rustdoc.
540         //
541         let mut features = Vec::new();
542         if builder.config.jemalloc {
543             features.push("jemalloc".to_string());
544         }
545
546         let cargo = prepare_tool_cargo(
547             builder,
548             build_compiler,
549             Mode::ToolRustc,
550             target,
551             "build",
552             "src/tools/rustdoc",
553             SourceType::InTree,
554             features.as_slice(),
555         );
556
557         builder.info(&format!(
558             "Building rustdoc for stage{} ({})",
559             target_compiler.stage, target_compiler.host
560         ));
561         builder.run(&mut cargo.into());
562
563         // Cargo adds a number of paths to the dylib search path on windows, which results in
564         // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
565         // rustdoc a different name.
566         let tool_rustdoc = builder
567             .cargo_out(build_compiler, Mode::ToolRustc, target)
568             .join(exe("rustdoc_tool_binary", target_compiler.host));
569
570         // don't create a stage0-sysroot/bin directory.
571         if target_compiler.stage > 0 {
572             let sysroot = builder.sysroot(target_compiler);
573             let bindir = sysroot.join("bin");
574             t!(fs::create_dir_all(&bindir));
575             let bin_rustdoc = bindir.join(exe("rustdoc", target_compiler.host));
576             let _ = fs::remove_file(&bin_rustdoc);
577             builder.copy(&tool_rustdoc, &bin_rustdoc);
578             bin_rustdoc
579         } else {
580             tool_rustdoc
581         }
582     }
583 }
584
585 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
586 pub struct Cargo {
587     pub compiler: Compiler,
588     pub target: TargetSelection,
589 }
590
591 impl Step for Cargo {
592     type Output = PathBuf;
593     const DEFAULT: bool = true;
594     const ONLY_HOSTS: bool = true;
595
596     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
597         let builder = run.builder;
598         run.path("src/tools/cargo").default_condition(
599             builder.config.extended
600                 && builder.config.tools.as_ref().map_or(
601                     true,
602                     // If `tools` is set, search list for this tool.
603                     |tools| tools.iter().any(|tool| tool == "cargo"),
604                 ),
605         )
606     }
607
608     fn make_run(run: RunConfig<'_>) {
609         run.builder.ensure(Cargo {
610             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
611             target: run.target,
612         });
613     }
614
615     fn run(self, builder: &Builder<'_>) -> PathBuf {
616         let cargo_bin_path = builder
617             .ensure(ToolBuild {
618                 compiler: self.compiler,
619                 target: self.target,
620                 tool: "cargo",
621                 mode: Mode::ToolRustc,
622                 path: "src/tools/cargo",
623                 is_optional_tool: false,
624                 source_type: SourceType::Submodule,
625                 extra_features: Vec::new(),
626             })
627             .expect("expected to build -- essential tool");
628
629         let build_cred = |name, path| {
630             // These credential helpers are currently experimental.
631             // Any build failures will be ignored.
632             let _ = builder.ensure(ToolBuild {
633                 compiler: self.compiler,
634                 target: self.target,
635                 tool: name,
636                 mode: Mode::ToolRustc,
637                 path,
638                 is_optional_tool: true,
639                 source_type: SourceType::Submodule,
640                 extra_features: Vec::new(),
641             });
642         };
643
644         if self.target.contains("windows") {
645             build_cred(
646                 "cargo-credential-wincred",
647                 "src/tools/cargo/crates/credential/cargo-credential-wincred",
648             );
649         }
650         if self.target.contains("apple-darwin") {
651             build_cred(
652                 "cargo-credential-macos-keychain",
653                 "src/tools/cargo/crates/credential/cargo-credential-macos-keychain",
654             );
655         }
656         build_cred(
657             "cargo-credential-1password",
658             "src/tools/cargo/crates/credential/cargo-credential-1password",
659         );
660         cargo_bin_path
661     }
662 }
663
664 macro_rules! tool_extended {
665     (($sel:ident, $builder:ident),
666        $($name:ident,
667        $toolstate:ident,
668        $path:expr,
669        $tool_name:expr,
670        stable = $stable:expr,
671        $(in_tree = $in_tree:expr,)*
672        $extra_deps:block;)+) => {
673         $(
674             #[derive(Debug, Clone, Hash, PartialEq, Eq)]
675         pub struct $name {
676             pub compiler: Compiler,
677             pub target: TargetSelection,
678             pub extra_features: Vec<String>,
679         }
680
681         impl Step for $name {
682             type Output = Option<PathBuf>;
683             const DEFAULT: bool = true; // Overwritten below
684             const ONLY_HOSTS: bool = true;
685
686             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
687                 let builder = run.builder;
688                 run.path($path).default_condition(
689                     builder.config.extended
690                         && builder.config.tools.as_ref().map_or(
691                             // By default, on nightly/dev enable all tools, else only
692                             // build stable tools.
693                             $stable || builder.build.unstable_features(),
694                             // If `tools` is set, search list for this tool.
695                             |tools| {
696                                 tools.iter().any(|tool| match tool.as_ref() {
697                                     "clippy" => $tool_name == "clippy-driver",
698                                     x => $tool_name == x,
699                             })
700                         }),
701                 )
702             }
703
704             fn make_run(run: RunConfig<'_>) {
705                 run.builder.ensure($name {
706                     compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
707                     target: run.target,
708                     extra_features: Vec::new(),
709                 });
710             }
711
712             #[allow(unused_mut)]
713             fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
714                 $extra_deps
715                 $builder.ensure(ToolBuild {
716                     compiler: $sel.compiler,
717                     target: $sel.target,
718                     tool: $tool_name,
719                     mode: Mode::ToolRustc,
720                     path: $path,
721                     extra_features: $sel.extra_features,
722                     is_optional_tool: true,
723                     source_type: if false $(|| $in_tree)* {
724                         SourceType::InTree
725                     } else {
726                         SourceType::Submodule
727                     },
728                 })
729             }
730         }
731         )+
732     }
733 }
734
735 // Note: tools need to be also added to `Builder::get_step_descriptions` in `builder.rs`
736 // to make `./x.py build <tool>` work.
737 tool_extended!((self, builder),
738     Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", stable=true, in_tree=true, {};
739     CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", stable=true, in_tree=true, {};
740     Clippy, clippy, "src/tools/clippy", "clippy-driver", stable=true, in_tree=true, {};
741     Miri, miri, "src/tools/miri", "miri", stable=false, {};
742     CargoMiri, miri, "src/tools/miri/cargo-miri", "cargo-miri", stable=false, {};
743     Rls, rls, "src/tools/rls", "rls", stable=true, {
744         builder.ensure(Clippy {
745             compiler: self.compiler,
746             target: self.target,
747             extra_features: Vec::new(),
748         });
749         self.extra_features.push("clippy".to_owned());
750     };
751     RustDemangler, rust_demangler, "src/tools/rust-demangler", "rust-demangler", stable=false, in_tree=true, {};
752     Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", stable=true, in_tree=true, {};
753     RustAnalyzer, rust_analyzer, "src/tools/rust-analyzer/crates/rust-analyzer", "rust-analyzer", stable=false, {};
754 );
755
756 impl<'a> Builder<'a> {
757     /// Gets a `Command` which is ready to run `tool` in `stage` built for
758     /// `host`.
759     pub fn tool_cmd(&self, tool: Tool) -> Command {
760         let mut cmd = Command::new(self.tool_exe(tool));
761         let compiler = self.compiler(0, self.config.build);
762         let host = &compiler.host;
763         // Prepares the `cmd` provided to be able to run the `compiler` provided.
764         //
765         // Notably this munges the dynamic library lookup path to point to the
766         // right location to run `compiler`.
767         let mut lib_paths: Vec<PathBuf> = vec![
768             self.build.rustc_snapshot_libdir(),
769             self.cargo_out(compiler, Mode::ToolBootstrap, *host).join("deps"),
770         ];
771
772         // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
773         // mode) and that C compiler may need some extra PATH modification. Do
774         // so here.
775         if compiler.host.contains("msvc") {
776             let curpaths = env::var_os("PATH").unwrap_or_default();
777             let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
778             for &(ref k, ref v) in self.cc[&compiler.host].env() {
779                 if k != "PATH" {
780                     continue;
781                 }
782                 for path in env::split_paths(v) {
783                     if !curpaths.contains(&path) {
784                         lib_paths.push(path);
785                     }
786                 }
787             }
788         }
789
790         add_dylib_path(lib_paths, &mut cmd);
791
792         // Provide a RUSTC for this command to use.
793         cmd.env("RUSTC", &self.initial_rustc);
794
795         cmd
796     }
797 }