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