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