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