]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/tool.rs
rustdoc: Remove unnecessary clone in `DocFolder`
[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 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     cargo.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
267
268     let info = GitInfo::new(builder.config.ignore_git, &dir);
269     if let Some(sha) = info.sha() {
270         cargo.env("CFG_COMMIT_HASH", sha);
271     }
272     if let Some(sha_short) = info.sha_short() {
273         cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
274     }
275     if let Some(date) = info.commit_date() {
276         cargo.env("CFG_COMMIT_DATE", date);
277     }
278     if !features.is_empty() {
279         cargo.arg("--features").arg(&features.join(", "));
280     }
281     cargo
282 }
283
284 macro_rules! bootstrap_tool {
285     ($(
286         $name:ident, $path:expr, $tool_name:expr
287         $(,is_external_tool = $external:expr)*
288         $(,is_unstable_tool = $unstable:expr)*
289         $(,features = $features:expr)*
290         ;
291     )+) => {
292         #[derive(Copy, PartialEq, Eq, Clone)]
293         pub enum Tool {
294             $(
295                 $name,
296             )+
297         }
298
299         impl<'a> Builder<'a> {
300             pub fn tool_exe(&self, tool: Tool) -> PathBuf {
301                 match tool {
302                     $(Tool::$name =>
303                         self.ensure($name {
304                             compiler: self.compiler(0, self.config.build),
305                             target: self.config.build,
306                         }),
307                     )+
308                 }
309             }
310         }
311
312         $(
313             #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
314         pub struct $name {
315             pub compiler: Compiler,
316             pub target: TargetSelection,
317         }
318
319         impl Step for $name {
320             type Output = PathBuf;
321
322             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
323                 run.path($path)
324             }
325
326             fn make_run(run: RunConfig<'_>) {
327                 run.builder.ensure($name {
328                     // snapshot compiler
329                     compiler: run.builder.compiler(0, run.builder.config.build),
330                     target: run.target,
331                 });
332             }
333
334             fn run(self, builder: &Builder<'_>) -> PathBuf {
335                 builder.ensure(ToolBuild {
336                     compiler: self.compiler,
337                     target: self.target,
338                     tool: $tool_name,
339                     mode: if false $(|| $unstable)* {
340                         // use in-tree libraries for unstable features
341                         Mode::ToolStd
342                     } else {
343                         Mode::ToolBootstrap
344                     },
345                     path: $path,
346                     is_optional_tool: false,
347                     source_type: if false $(|| $external)* {
348                         SourceType::Submodule
349                     } else {
350                         SourceType::InTree
351                     },
352                     extra_features: {
353                         // FIXME(#60643): avoid this lint by using `_`
354                         let mut _tmp = Vec::new();
355                         $(_tmp.extend($features);)*
356                         _tmp
357                     },
358                 }).expect("expected to build -- essential tool")
359             }
360         }
361         )+
362     }
363 }
364
365 bootstrap_tool!(
366     Rustbook, "src/tools/rustbook", "rustbook";
367     UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
368     Tidy, "src/tools/tidy", "tidy";
369     Linkchecker, "src/tools/linkchecker", "linkchecker";
370     CargoTest, "src/tools/cargotest", "cargotest";
371     Compiletest, "src/tools/compiletest", "compiletest", is_unstable_tool = true;
372     BuildManifest, "src/tools/build-manifest", "build-manifest";
373     RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
374     RustInstaller, "src/tools/rust-installer", "fabricate", is_external_tool = true;
375     RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
376     ExpandYamlAnchors, "src/tools/expand-yaml-anchors", "expand-yaml-anchors";
377     LintDocs, "src/tools/lint-docs", "lint-docs";
378     JsonDocCk, "src/tools/jsondocck", "jsondocck";
379     HtmlChecker, "src/tools/html-checker", "html-checker";
380     BumpStage0, "src/tools/bump-stage0", "bump-stage0";
381 );
382
383 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
384 pub struct ErrorIndex {
385     pub compiler: Compiler,
386 }
387
388 impl ErrorIndex {
389     pub fn command(builder: &Builder<'_>) -> Command {
390         // This uses stage-1 to match the behavior of building rustdoc.
391         // Error-index-generator links with the rustdoc library, so we want to
392         // use the same librustdoc to avoid building rustdoc twice (and to
393         // avoid building the compiler an extra time). This uses
394         // saturating_sub to deal with building with stage 0. (Using stage 0
395         // isn't recommended, since it will fail if any new error index tests
396         // use new syntax, but it should work otherwise.)
397         let compiler = builder.compiler(builder.top_stage.saturating_sub(1), builder.config.build);
398         let mut cmd = Command::new(builder.ensure(ErrorIndex { compiler }));
399         add_dylib_path(
400             vec![
401                 PathBuf::from(&builder.sysroot_libdir(compiler, compiler.host)),
402                 PathBuf::from(builder.rustc_libdir(compiler)),
403             ],
404             &mut cmd,
405         );
406         cmd
407     }
408 }
409
410 impl Step for ErrorIndex {
411     type Output = PathBuf;
412
413     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
414         run.path("src/tools/error_index_generator")
415     }
416
417     fn make_run(run: RunConfig<'_>) {
418         // Compile the error-index in the same stage as rustdoc to avoid
419         // recompiling rustdoc twice if we can.
420         //
421         // NOTE: This `make_run` isn't used in normal situations, only if you
422         // manually build the tool with `x.py build
423         // src/tools/error-index-generator` which almost nobody does.
424         // Normally, `x.py test` or `x.py doc` will use the
425         // `ErrorIndex::command` function instead.
426         let compiler =
427             run.builder.compiler(run.builder.top_stage.saturating_sub(1), run.builder.config.build);
428         run.builder.ensure(ErrorIndex { compiler });
429     }
430
431     fn run(self, builder: &Builder<'_>) -> PathBuf {
432         builder
433             .ensure(ToolBuild {
434                 compiler: self.compiler,
435                 target: self.compiler.host,
436                 tool: "error_index_generator",
437                 mode: Mode::ToolRustc,
438                 path: "src/tools/error_index_generator",
439                 is_optional_tool: false,
440                 source_type: SourceType::InTree,
441                 extra_features: Vec::new(),
442             })
443             .expect("expected to build -- essential tool")
444     }
445 }
446
447 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
448 pub struct RemoteTestServer {
449     pub compiler: Compiler,
450     pub target: TargetSelection,
451 }
452
453 impl Step for RemoteTestServer {
454     type Output = PathBuf;
455
456     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
457         run.path("src/tools/remote-test-server")
458     }
459
460     fn make_run(run: RunConfig<'_>) {
461         run.builder.ensure(RemoteTestServer {
462             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
463             target: run.target,
464         });
465     }
466
467     fn run(self, builder: &Builder<'_>) -> PathBuf {
468         builder
469             .ensure(ToolBuild {
470                 compiler: self.compiler,
471                 target: self.target,
472                 tool: "remote-test-server",
473                 mode: Mode::ToolStd,
474                 path: "src/tools/remote-test-server",
475                 is_optional_tool: false,
476                 source_type: SourceType::InTree,
477                 extra_features: Vec::new(),
478             })
479             .expect("expected to build -- essential tool")
480     }
481 }
482
483 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
484 pub struct Rustdoc {
485     /// This should only ever be 0 or 2.
486     /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
487     pub compiler: Compiler,
488 }
489
490 impl Step for Rustdoc {
491     type Output = PathBuf;
492     const DEFAULT: bool = true;
493     const ONLY_HOSTS: bool = true;
494
495     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
496         run.path("src/tools/rustdoc").path("src/librustdoc")
497     }
498
499     fn make_run(run: RunConfig<'_>) {
500         run.builder.ensure(Rustdoc {
501             // Note: this is somewhat unique in that we actually want a *target*
502             // compiler here, because rustdoc *is* a compiler. We won't be using
503             // this as the compiler to build with, but rather this is "what
504             // compiler are we producing"?
505             compiler: run.builder.compiler(run.builder.top_stage, run.target),
506         });
507     }
508
509     fn run(self, builder: &Builder<'_>) -> PathBuf {
510         let target_compiler = self.compiler;
511         if target_compiler.stage == 0 {
512             if !target_compiler.is_snapshot(builder) {
513                 panic!("rustdoc in stage 0 must be snapshot rustdoc");
514             }
515             return builder.initial_rustc.with_file_name(exe("rustdoc", target_compiler.host));
516         }
517         let target = target_compiler.host;
518         // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
519         // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
520         // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
521         // rustc compiler it's paired with, so it must be built with the previous stage compiler.
522         let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
523
524         // When using `download-rustc` and a stage0 build_compiler, copying rustc doesn't actually
525         // build stage0 libstd (because the libstd in sysroot has the wrong ABI). Explicitly build
526         // it.
527         builder.ensure(compile::Std { compiler: build_compiler, target: target_compiler.host });
528         builder.ensure(compile::Rustc { compiler: build_compiler, target: target_compiler.host });
529         // NOTE: this implies that `download-rustc` is pretty useless when compiling with the stage0
530         // compiler, since you do just as much work.
531         if !builder.config.dry_run && builder.config.download_rustc && build_compiler.stage == 0 {
532             println!(
533                 "warning: `download-rustc` does nothing when building stage1 tools; consider using `--stage 2` instead"
534             );
535         }
536
537         // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
538         // compiler libraries, ...) are built. Rustdoc does not require the presence of any
539         // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
540         // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
541         // libraries here. The intuition here is that If we've built a compiler, we should be able
542         // to build rustdoc.
543         //
544         let mut features = Vec::new();
545         if builder.config.jemalloc {
546             features.push("jemalloc".to_string());
547         }
548
549         let cargo = prepare_tool_cargo(
550             builder,
551             build_compiler,
552             Mode::ToolRustc,
553             target,
554             "build",
555             "src/tools/rustdoc",
556             SourceType::InTree,
557             features.as_slice(),
558         );
559
560         builder.info(&format!(
561             "Building rustdoc for stage{} ({})",
562             target_compiler.stage, target_compiler.host
563         ));
564         builder.run(&mut cargo.into());
565
566         // Cargo adds a number of paths to the dylib search path on windows, which results in
567         // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
568         // rustdoc a different name.
569         let tool_rustdoc = builder
570             .cargo_out(build_compiler, Mode::ToolRustc, target)
571             .join(exe("rustdoc_tool_binary", target_compiler.host));
572
573         // don't create a stage0-sysroot/bin directory.
574         if target_compiler.stage > 0 {
575             let sysroot = builder.sysroot(target_compiler);
576             let bindir = sysroot.join("bin");
577             t!(fs::create_dir_all(&bindir));
578             let bin_rustdoc = bindir.join(exe("rustdoc", target_compiler.host));
579             let _ = fs::remove_file(&bin_rustdoc);
580             builder.copy(&tool_rustdoc, &bin_rustdoc);
581             bin_rustdoc
582         } else {
583             tool_rustdoc
584         }
585     }
586 }
587
588 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
589 pub struct Cargo {
590     pub compiler: Compiler,
591     pub target: TargetSelection,
592 }
593
594 impl Step for Cargo {
595     type Output = PathBuf;
596     const DEFAULT: bool = true;
597     const ONLY_HOSTS: bool = true;
598
599     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
600         let builder = run.builder;
601         run.path("src/tools/cargo").default_condition(
602             builder.config.extended
603                 && builder.config.tools.as_ref().map_or(
604                     true,
605                     // If `tools` is set, search list for this tool.
606                     |tools| tools.iter().any(|tool| tool == "cargo"),
607                 ),
608         )
609     }
610
611     fn make_run(run: RunConfig<'_>) {
612         run.builder.ensure(Cargo {
613             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
614             target: run.target,
615         });
616     }
617
618     fn run(self, builder: &Builder<'_>) -> PathBuf {
619         let cargo_bin_path = builder
620             .ensure(ToolBuild {
621                 compiler: self.compiler,
622                 target: self.target,
623                 tool: "cargo",
624                 mode: Mode::ToolRustc,
625                 path: "src/tools/cargo",
626                 is_optional_tool: false,
627                 source_type: SourceType::Submodule,
628                 extra_features: Vec::new(),
629             })
630             .expect("expected to build -- essential tool");
631
632         let build_cred = |name, path| {
633             // These credential helpers are currently experimental.
634             // Any build failures will be ignored.
635             let _ = builder.ensure(ToolBuild {
636                 compiler: self.compiler,
637                 target: self.target,
638                 tool: name,
639                 mode: Mode::ToolRustc,
640                 path,
641                 is_optional_tool: true,
642                 source_type: SourceType::Submodule,
643                 extra_features: Vec::new(),
644             });
645         };
646
647         if self.target.contains("windows") {
648             build_cred(
649                 "cargo-credential-wincred",
650                 "src/tools/cargo/crates/credential/cargo-credential-wincred",
651             );
652         }
653         if self.target.contains("apple-darwin") {
654             build_cred(
655                 "cargo-credential-macos-keychain",
656                 "src/tools/cargo/crates/credential/cargo-credential-macos-keychain",
657             );
658         }
659         build_cred(
660             "cargo-credential-1password",
661             "src/tools/cargo/crates/credential/cargo-credential-1password",
662         );
663         cargo_bin_path
664     }
665 }
666
667 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
668 pub struct LldWrapper {
669     pub compiler: Compiler,
670     pub target: TargetSelection,
671     pub flavor_feature: &'static str,
672 }
673
674 impl Step for LldWrapper {
675     type Output = PathBuf;
676
677     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
678         run.never()
679     }
680
681     fn run(self, builder: &Builder<'_>) -> PathBuf {
682         let src_exe = builder
683             .ensure(ToolBuild {
684                 compiler: self.compiler,
685                 target: self.target,
686                 tool: "lld-wrapper",
687                 mode: Mode::ToolStd,
688                 path: "src/tools/lld-wrapper",
689                 is_optional_tool: false,
690                 source_type: SourceType::InTree,
691                 extra_features: vec![self.flavor_feature.to_owned()],
692             })
693             .expect("expected to build -- essential tool");
694
695         src_exe
696     }
697 }
698
699 macro_rules! tool_extended {
700     (($sel:ident, $builder:ident),
701        $($name:ident,
702        $toolstate:ident,
703        $path:expr,
704        $tool_name:expr,
705        stable = $stable:expr,
706        $(in_tree = $in_tree:expr,)?
707        $(submodule = $submodule:literal,)?
708        $extra_deps:block;)+) => {
709         $(
710             #[derive(Debug, Clone, Hash, PartialEq, Eq)]
711         pub struct $name {
712             pub compiler: Compiler,
713             pub target: TargetSelection,
714             pub extra_features: Vec<String>,
715         }
716
717         impl Step for $name {
718             type Output = Option<PathBuf>;
719             const DEFAULT: bool = true; // Overwritten below
720             const ONLY_HOSTS: bool = true;
721
722             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
723                 let builder = run.builder;
724                 run.path($path).default_condition(
725                     builder.config.extended
726                         && builder.config.tools.as_ref().map_or(
727                             // By default, on nightly/dev enable all tools, else only
728                             // build stable tools.
729                             $stable || builder.build.unstable_features(),
730                             // If `tools` is set, search list for this tool.
731                             |tools| {
732                                 tools.iter().any(|tool| match tool.as_ref() {
733                                     "clippy" => $tool_name == "clippy-driver",
734                                     x => $tool_name == x,
735                             })
736                         }),
737                 )
738             }
739
740             fn make_run(run: RunConfig<'_>) {
741                 run.builder.ensure($name {
742                     compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
743                     target: run.target,
744                     extra_features: Vec::new(),
745                 });
746             }
747
748             #[allow(unused_mut)]
749             fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
750                 $extra_deps
751                 $( $builder.update_submodule(&Path::new("src").join("tools").join($submodule)); )?
752                 $builder.ensure(ToolBuild {
753                     compiler: $sel.compiler,
754                     target: $sel.target,
755                     tool: $tool_name,
756                     mode: Mode::ToolRustc,
757                     path: $path,
758                     extra_features: $sel.extra_features,
759                     is_optional_tool: true,
760                     source_type: if false $(|| $in_tree)* {
761                         SourceType::InTree
762                     } else {
763                         SourceType::Submodule
764                     },
765                 })
766             }
767         }
768         )+
769     }
770 }
771
772 // Note: tools need to be also added to `Builder::get_step_descriptions` in `builder.rs`
773 // to make `./x.py build <tool>` work.
774 // Note: Most submodule updates for tools are handled by bootstrap.py, since they're needed just to
775 // invoke Cargo to build bootstrap. See the comment there for more details.
776 tool_extended!((self, builder),
777     Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", stable=true, in_tree=true, {};
778     CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", stable=true, in_tree=true, {};
779     Clippy, clippy, "src/tools/clippy", "clippy-driver", stable=true, in_tree=true, {};
780     Miri, miri, "src/tools/miri", "miri", stable=false, {};
781     CargoMiri, miri, "src/tools/miri/cargo-miri", "cargo-miri", stable=false, {};
782     Rls, rls, "src/tools/rls", "rls", stable=true, {
783         builder.ensure(Clippy {
784             compiler: self.compiler,
785             target: self.target,
786             extra_features: Vec::new(),
787         });
788         self.extra_features.push("clippy".to_owned());
789     };
790     RustDemangler, rust_demangler, "src/tools/rust-demangler", "rust-demangler", stable=false, in_tree=true, {};
791     Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", stable=true, in_tree=true, {};
792     RustAnalyzer, rust_analyzer, "src/tools/rust-analyzer/crates/rust-analyzer", "rust-analyzer", stable=false, submodule="rust-analyzer", {};
793 );
794
795 impl<'a> Builder<'a> {
796     /// Gets a `Command` which is ready to run `tool` in `stage` built for
797     /// `host`.
798     pub fn tool_cmd(&self, tool: Tool) -> Command {
799         let mut cmd = Command::new(self.tool_exe(tool));
800         let compiler = self.compiler(0, self.config.build);
801         let host = &compiler.host;
802         // Prepares the `cmd` provided to be able to run the `compiler` provided.
803         //
804         // Notably this munges the dynamic library lookup path to point to the
805         // right location to run `compiler`.
806         let mut lib_paths: Vec<PathBuf> = vec![
807             self.build.rustc_snapshot_libdir(),
808             self.cargo_out(compiler, Mode::ToolBootstrap, *host).join("deps"),
809         ];
810
811         // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
812         // mode) and that C compiler may need some extra PATH modification. Do
813         // so here.
814         if compiler.host.contains("msvc") {
815             let curpaths = env::var_os("PATH").unwrap_or_default();
816             let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
817             for &(ref k, ref v) in self.cc[&compiler.host].env() {
818                 if k != "PATH" {
819                     continue;
820                 }
821                 for path in env::split_paths(v) {
822                     if !curpaths.contains(&path) {
823                         lib_paths.push(path);
824                     }
825                 }
826             }
827         }
828
829         add_dylib_path(lib_paths, &mut cmd);
830
831         // Provide a RUSTC for this command to use.
832         cmd.env("RUSTC", &self.initial_rustc);
833
834         cmd
835     }
836 }