]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/tool.rs
Rollup merge of #97739 - a2aaron:let_underscore, r=estebank
[rust.git] / src / bootstrap / tool.rs
1 use std::collections::HashSet;
2 use std::env;
3 use std::fs;
4 use std::path::PathBuf;
5 use std::process::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             let (same, different): (Vec<_>, Vec<_>) =
162                 duplicates.into_iter().partition(|(_, cur, prev)| cur.2 == prev.2);
163             if !same.is_empty() {
164                 eprintln!(
165                     "the following dependencies are duplicated although they \
166                       have the same features enabled:"
167                 );
168                 for (id, cur, prev) in same {
169                     eprintln!("  {}", id);
170                     // same features
171                     eprintln!("    `{}` ({:?})\n    `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
172                 }
173             }
174             if !different.is_empty() {
175                 eprintln!("the following dependencies have different features:");
176                 for (id, cur, prev) in different {
177                     eprintln!("  {}", id);
178                     let cur_features: HashSet<_> = cur.2.into_iter().collect();
179                     let prev_features: HashSet<_> = prev.2.into_iter().collect();
180                     eprintln!(
181                         "    `{}` additionally enabled features {:?} at {:?}",
182                         cur.0,
183                         &cur_features - &prev_features,
184                         cur.1
185                     );
186                     eprintln!(
187                         "    `{}` additionally enabled features {:?} at {:?}",
188                         prev.0,
189                         &prev_features - &cur_features,
190                         prev.1
191                     );
192                 }
193             }
194             eprintln!();
195             eprintln!(
196                 "to fix this you will probably want to edit the local \
197                       src/tools/rustc-workspace-hack/Cargo.toml crate, as \
198                       that will update the dependency graph to ensure that \
199                       these crates all share the same feature set"
200             );
201             panic!("tools should not compile multiple copies of the same crate");
202         }
203
204         builder.save_toolstate(
205             tool,
206             if is_expected { ToolState::TestFail } else { ToolState::BuildFail },
207         );
208
209         if !is_expected {
210             if !is_optional_tool {
211                 crate::detail_exit(1);
212             } else {
213                 None
214             }
215         } else {
216             // HACK(#82501): on Windows, the tools directory gets added to PATH when running tests, and
217             // compiletest confuses HTML tidy with the in-tree tidy. Name the in-tree tidy something
218             // different so the problem doesn't come up.
219             if tool == "tidy" {
220                 tool = "rust-tidy";
221             }
222             let cargo_out = builder.cargo_out(compiler, self.mode, target).join(exe(tool, target));
223             let bin = builder.tools_dir(compiler).join(exe(tool, target));
224             builder.copy(&cargo_out, &bin);
225             Some(bin)
226         }
227     }
228 }
229
230 pub fn prepare_tool_cargo(
231     builder: &Builder<'_>,
232     compiler: Compiler,
233     mode: Mode,
234     target: TargetSelection,
235     command: &'static str,
236     path: &'static str,
237     source_type: SourceType,
238     extra_features: &[String],
239 ) -> CargoCommand {
240     let mut cargo = builder.cargo(compiler, mode, source_type, target, command);
241     let dir = builder.src.join(path);
242     cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
243
244     let mut features = extra_features.to_vec();
245     if builder.build.config.cargo_native_static {
246         if path.ends_with("cargo")
247             || path.ends_with("rls")
248             || path.ends_with("clippy")
249             || path.ends_with("miri")
250             || path.ends_with("rustfmt")
251         {
252             cargo.env("LIBZ_SYS_STATIC", "1");
253             features.push("rustc-workspace-hack/all-static".to_string());
254         }
255     }
256
257     // clippy tests need to know about the stage sysroot. Set them consistently while building to
258     // avoid rebuilding when running tests.
259     cargo.env("SYSROOT", builder.sysroot(compiler));
260
261     // if tools are using lzma we want to force the build script to build its
262     // own copy
263     cargo.env("LZMA_API_STATIC", "1");
264
265     // CFG_RELEASE is needed by rustfmt (and possibly other tools) which
266     // import rustc-ap-rustc_attr which requires this to be set for the
267     // `#[cfg(version(...))]` attribute.
268     cargo.env("CFG_RELEASE", builder.rust_release());
269     cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
270     cargo.env("CFG_VERSION", builder.rust_version());
271     cargo.env("CFG_RELEASE_NUM", &builder.version);
272     cargo.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
273
274     let info = GitInfo::new(builder.config.ignore_git, &dir);
275     if let Some(sha) = info.sha() {
276         cargo.env("CFG_COMMIT_HASH", sha);
277     }
278     if let Some(sha_short) = info.sha_short() {
279         cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
280     }
281     if let Some(date) = info.commit_date() {
282         cargo.env("CFG_COMMIT_DATE", date);
283     }
284     if !features.is_empty() {
285         cargo.arg("--features").arg(&features.join(", "));
286     }
287     cargo
288 }
289
290 macro_rules! bootstrap_tool {
291     ($(
292         $name:ident, $path:expr, $tool_name:expr
293         $(,is_external_tool = $external:expr)*
294         $(,is_unstable_tool = $unstable:expr)*
295         ;
296     )+) => {
297         #[derive(Copy, PartialEq, Eq, Clone)]
298         pub enum Tool {
299             $(
300                 $name,
301             )+
302         }
303
304         impl<'a> Builder<'a> {
305             pub fn tool_exe(&self, tool: Tool) -> PathBuf {
306                 match tool {
307                     $(Tool::$name =>
308                         self.ensure($name {
309                             compiler: self.compiler(0, self.config.build),
310                             target: self.config.build,
311                         }),
312                     )+
313                 }
314             }
315         }
316
317         $(
318             #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
319         pub struct $name {
320             pub compiler: Compiler,
321             pub target: TargetSelection,
322         }
323
324         impl Step for $name {
325             type Output = PathBuf;
326
327             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
328                 run.path($path)
329             }
330
331             fn make_run(run: RunConfig<'_>) {
332                 run.builder.ensure($name {
333                     // snapshot compiler
334                     compiler: run.builder.compiler(0, run.builder.config.build),
335                     target: run.target,
336                 });
337             }
338
339             fn run(self, builder: &Builder<'_>) -> PathBuf {
340                 builder.ensure(ToolBuild {
341                     compiler: self.compiler,
342                     target: self.target,
343                     tool: $tool_name,
344                     mode: if false $(|| $unstable)* {
345                         // use in-tree libraries for unstable features
346                         Mode::ToolStd
347                     } else {
348                         Mode::ToolBootstrap
349                     },
350                     path: $path,
351                     is_optional_tool: false,
352                     source_type: if false $(|| $external)* {
353                         SourceType::Submodule
354                     } else {
355                         SourceType::InTree
356                     },
357                     extra_features: vec![],
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", "rust-installer", 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     ReplaceVersionPlaceholder, "src/tools/replace-version-placeholder", "replace-version-placeholder";
382 );
383
384 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
385 pub struct ErrorIndex {
386     pub compiler: Compiler,
387 }
388
389 impl ErrorIndex {
390     pub fn command(builder: &Builder<'_>) -> Command {
391         // Error-index-generator links with the rustdoc library, so we need to add `rustc_lib_paths`
392         // for rustc_private and libLLVM.so, and `sysroot_lib` for libstd, etc.
393         let host = builder.config.build;
394         let compiler = builder.compiler_for(builder.top_stage, host, host);
395         let mut cmd = Command::new(builder.ensure(ErrorIndex { compiler }));
396         let mut dylib_paths = builder.rustc_lib_paths(compiler);
397         dylib_paths.push(PathBuf::from(&builder.sysroot_libdir(compiler, compiler.host)));
398         add_dylib_path(dylib_paths, &mut cmd);
399         cmd
400     }
401 }
402
403 impl Step for ErrorIndex {
404     type Output = PathBuf;
405
406     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
407         run.path("src/tools/error_index_generator")
408     }
409
410     fn make_run(run: RunConfig<'_>) {
411         // Compile the error-index in the same stage as rustdoc to avoid
412         // recompiling rustdoc twice if we can.
413         //
414         // NOTE: This `make_run` isn't used in normal situations, only if you
415         // manually build the tool with `x.py build
416         // src/tools/error-index-generator` which almost nobody does.
417         // Normally, `x.py test` or `x.py doc` will use the
418         // `ErrorIndex::command` function instead.
419         let compiler =
420             run.builder.compiler(run.builder.top_stage.saturating_sub(1), run.builder.config.build);
421         run.builder.ensure(ErrorIndex { compiler });
422     }
423
424     fn run(self, builder: &Builder<'_>) -> PathBuf {
425         builder
426             .ensure(ToolBuild {
427                 compiler: self.compiler,
428                 target: self.compiler.host,
429                 tool: "error_index_generator",
430                 mode: Mode::ToolRustc,
431                 path: "src/tools/error_index_generator",
432                 is_optional_tool: false,
433                 source_type: SourceType::InTree,
434                 extra_features: Vec::new(),
435             })
436             .expect("expected to build -- essential tool")
437     }
438 }
439
440 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
441 pub struct RemoteTestServer {
442     pub compiler: Compiler,
443     pub target: TargetSelection,
444 }
445
446 impl Step for RemoteTestServer {
447     type Output = PathBuf;
448
449     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
450         run.path("src/tools/remote-test-server")
451     }
452
453     fn make_run(run: RunConfig<'_>) {
454         run.builder.ensure(RemoteTestServer {
455             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
456             target: run.target,
457         });
458     }
459
460     fn run(self, builder: &Builder<'_>) -> PathBuf {
461         builder
462             .ensure(ToolBuild {
463                 compiler: self.compiler,
464                 target: self.target,
465                 tool: "remote-test-server",
466                 mode: Mode::ToolStd,
467                 path: "src/tools/remote-test-server",
468                 is_optional_tool: false,
469                 source_type: SourceType::InTree,
470                 extra_features: Vec::new(),
471             })
472             .expect("expected to build -- essential tool")
473     }
474 }
475
476 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
477 pub struct Rustdoc {
478     /// This should only ever be 0 or 2.
479     /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
480     pub compiler: Compiler,
481 }
482
483 impl Step for Rustdoc {
484     type Output = PathBuf;
485     const DEFAULT: bool = true;
486     const ONLY_HOSTS: bool = true;
487
488     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
489         run.path("src/tools/rustdoc").path("src/librustdoc")
490     }
491
492     fn make_run(run: RunConfig<'_>) {
493         run.builder.ensure(Rustdoc {
494             // Note: this is somewhat unique in that we actually want a *target*
495             // compiler here, because rustdoc *is* a compiler. We won't be using
496             // this as the compiler to build with, but rather this is "what
497             // compiler are we producing"?
498             compiler: run.builder.compiler(run.builder.top_stage, run.target),
499         });
500     }
501
502     fn run(self, builder: &Builder<'_>) -> PathBuf {
503         let target_compiler = self.compiler;
504         if target_compiler.stage == 0 {
505             if !target_compiler.is_snapshot(builder) {
506                 panic!("rustdoc in stage 0 must be snapshot rustdoc");
507             }
508             return builder.initial_rustc.with_file_name(exe("rustdoc", target_compiler.host));
509         }
510         let target = target_compiler.host;
511         // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
512         // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
513         // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
514         // rustc compiler it's paired with, so it must be built with the previous stage compiler.
515         let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
516
517         // When using `download-rustc` and a stage0 build_compiler, copying rustc doesn't actually
518         // build stage0 libstd (because the libstd in sysroot has the wrong ABI). Explicitly build
519         // it.
520         builder.ensure(compile::Std::new(build_compiler, target_compiler.host));
521         builder.ensure(compile::Rustc::new(build_compiler, target_compiler.host));
522         // NOTE: this implies that `download-rustc` is pretty useless when compiling with the stage0
523         // compiler, since you do just as much work.
524         if !builder.config.dry_run && builder.download_rustc() && build_compiler.stage == 0 {
525             println!(
526                 "warning: `download-rustc` does nothing when building stage1 tools; consider using `--stage 2` instead"
527             );
528         }
529
530         // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
531         // compiler libraries, ...) are built. Rustdoc does not require the presence of any
532         // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
533         // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
534         // libraries here. The intuition here is that If we've built a compiler, we should be able
535         // to build rustdoc.
536         //
537         let mut features = Vec::new();
538         if builder.config.jemalloc {
539             features.push("jemalloc".to_string());
540         }
541
542         let cargo = prepare_tool_cargo(
543             builder,
544             build_compiler,
545             Mode::ToolRustc,
546             target,
547             "build",
548             "src/tools/rustdoc",
549             SourceType::InTree,
550             features.as_slice(),
551         );
552
553         builder.info(&format!(
554             "Building rustdoc for stage{} ({})",
555             target_compiler.stage, target_compiler.host
556         ));
557         builder.run(&mut cargo.into());
558
559         // Cargo adds a number of paths to the dylib search path on windows, which results in
560         // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
561         // rustdoc a different name.
562         let tool_rustdoc = builder
563             .cargo_out(build_compiler, Mode::ToolRustc, target)
564             .join(exe("rustdoc_tool_binary", target_compiler.host));
565
566         // don't create a stage0-sysroot/bin directory.
567         if target_compiler.stage > 0 {
568             let sysroot = builder.sysroot(target_compiler);
569             let bindir = sysroot.join("bin");
570             t!(fs::create_dir_all(&bindir));
571             let bin_rustdoc = bindir.join(exe("rustdoc", target_compiler.host));
572             let _ = fs::remove_file(&bin_rustdoc);
573             builder.copy(&tool_rustdoc, &bin_rustdoc);
574             bin_rustdoc
575         } else {
576             tool_rustdoc
577         }
578     }
579 }
580
581 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
582 pub struct Cargo {
583     pub compiler: Compiler,
584     pub target: TargetSelection,
585 }
586
587 impl Step for Cargo {
588     type Output = PathBuf;
589     const DEFAULT: bool = true;
590     const ONLY_HOSTS: bool = true;
591
592     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
593         let builder = run.builder;
594         run.path("src/tools/cargo").default_condition(
595             builder.config.extended
596                 && builder.config.tools.as_ref().map_or(
597                     true,
598                     // If `tools` is set, search list for this tool.
599                     |tools| tools.iter().any(|tool| tool == "cargo"),
600                 ),
601         )
602     }
603
604     fn make_run(run: RunConfig<'_>) {
605         run.builder.ensure(Cargo {
606             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
607             target: run.target,
608         });
609     }
610
611     fn run(self, builder: &Builder<'_>) -> PathBuf {
612         let cargo_bin_path = builder
613             .ensure(ToolBuild {
614                 compiler: self.compiler,
615                 target: self.target,
616                 tool: "cargo",
617                 mode: Mode::ToolRustc,
618                 path: "src/tools/cargo",
619                 is_optional_tool: false,
620                 source_type: SourceType::Submodule,
621                 extra_features: Vec::new(),
622             })
623             .expect("expected to build -- essential tool");
624
625         let build_cred = |name, path| {
626             // These credential helpers are currently experimental.
627             // Any build failures will be ignored.
628             let _ = builder.ensure(ToolBuild {
629                 compiler: self.compiler,
630                 target: self.target,
631                 tool: name,
632                 mode: Mode::ToolRustc,
633                 path,
634                 is_optional_tool: true,
635                 source_type: SourceType::Submodule,
636                 extra_features: Vec::new(),
637             });
638         };
639
640         if self.target.contains("windows") {
641             build_cred(
642                 "cargo-credential-wincred",
643                 "src/tools/cargo/crates/credential/cargo-credential-wincred",
644             );
645         }
646         if self.target.contains("apple-darwin") {
647             build_cred(
648                 "cargo-credential-macos-keychain",
649                 "src/tools/cargo/crates/credential/cargo-credential-macos-keychain",
650             );
651         }
652         build_cred(
653             "cargo-credential-1password",
654             "src/tools/cargo/crates/credential/cargo-credential-1password",
655         );
656         cargo_bin_path
657     }
658 }
659
660 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
661 pub struct LldWrapper {
662     pub compiler: Compiler,
663     pub target: TargetSelection,
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::new(),
684             })
685             .expect("expected to build -- essential tool");
686
687         src_exe
688     }
689 }
690
691 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
692 pub struct RustAnalyzer {
693     pub compiler: Compiler,
694     pub target: TargetSelection,
695 }
696
697 impl Step for RustAnalyzer {
698     type Output = Option<PathBuf>;
699     const DEFAULT: bool = true;
700     const ONLY_HOSTS: bool = false;
701
702     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
703         let builder = run.builder;
704         run.path("src/tools/rust-analyzer").default_condition(
705             builder.config.extended
706                 && builder
707                     .config
708                     .tools
709                     .as_ref()
710                     .map_or(true, |tools| tools.iter().any(|tool| tool == "rust-analyzer")),
711         )
712     }
713
714     fn make_run(run: RunConfig<'_>) {
715         run.builder.ensure(RustAnalyzer {
716             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
717             target: run.target,
718         });
719     }
720
721     fn run(self, builder: &Builder<'_>) -> Option<PathBuf> {
722         builder.ensure(ToolBuild {
723             compiler: self.compiler,
724             target: self.target,
725             tool: "rust-analyzer",
726             mode: Mode::ToolStd,
727             path: "src/tools/rust-analyzer",
728             extra_features: vec!["rust-analyzer/in-rust-tree".to_owned()],
729             is_optional_tool: false,
730             source_type: SourceType::InTree,
731         })
732     }
733 }
734
735 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
736 pub struct RustAnalyzerProcMacroSrv {
737     pub compiler: Compiler,
738     pub target: TargetSelection,
739 }
740
741 impl Step for RustAnalyzerProcMacroSrv {
742     type Output = Option<PathBuf>;
743     const DEFAULT: bool = true;
744     const ONLY_HOSTS: bool = false;
745
746     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
747         let builder = run.builder;
748         run.path("src/tools/rust-analyzer").default_condition(
749             builder.config.extended
750                 && builder
751                     .config
752                     .tools
753                     .as_ref()
754                     .map_or(true, |tools| tools.iter().any(|tool| tool == "rust-analyzer")),
755         )
756     }
757
758     fn make_run(run: RunConfig<'_>) {
759         run.builder.ensure(RustAnalyzerProcMacroSrv {
760             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
761             target: run.target,
762         });
763     }
764
765     fn run(self, builder: &Builder<'_>) -> Option<PathBuf> {
766         builder.ensure(ToolBuild {
767             compiler: self.compiler,
768             target: self.target,
769             tool: "rust-analyzer-proc-macro-srv",
770             mode: Mode::ToolStd,
771             path: "src/tools/rust-analyzer/crates/proc-macro-srv-cli",
772             extra_features: vec!["proc-macro-srv/sysroot-abi".to_owned()],
773             is_optional_tool: false,
774             source_type: SourceType::InTree,
775         })
776     }
777 }
778
779 macro_rules! tool_extended {
780     (($sel:ident, $builder:ident),
781        $($name:ident,
782        $path:expr,
783        $tool_name:expr,
784        stable = $stable:expr,
785        $(in_tree = $in_tree:expr,)?
786        $(tool_std = $tool_std:literal,)?
787        $extra_deps:block;)+) => {
788         $(
789             #[derive(Debug, Clone, Hash, PartialEq, Eq)]
790         pub struct $name {
791             pub compiler: Compiler,
792             pub target: TargetSelection,
793             pub extra_features: Vec<String>,
794         }
795
796         impl Step for $name {
797             type Output = Option<PathBuf>;
798             const DEFAULT: bool = true; // Overwritten below
799             const ONLY_HOSTS: bool = true;
800
801             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
802                 let builder = run.builder;
803                 run.path($path).default_condition(
804                     builder.config.extended
805                         && builder.config.tools.as_ref().map_or(
806                             // By default, on nightly/dev enable all tools, else only
807                             // build stable tools.
808                             $stable || builder.build.unstable_features(),
809                             // If `tools` is set, search list for this tool.
810                             |tools| {
811                                 tools.iter().any(|tool| match tool.as_ref() {
812                                     "clippy" => $tool_name == "clippy-driver",
813                                     x => $tool_name == x,
814                             })
815                         }),
816                 )
817             }
818
819             fn make_run(run: RunConfig<'_>) {
820                 run.builder.ensure($name {
821                     compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
822                     target: run.target,
823                     extra_features: Vec::new(),
824                 });
825             }
826
827             #[allow(unused_mut)]
828             fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
829                 $extra_deps
830                 $builder.ensure(ToolBuild {
831                     compiler: $sel.compiler,
832                     target: $sel.target,
833                     tool: $tool_name,
834                     mode: if false $(|| $tool_std)? { Mode::ToolStd } else { Mode::ToolRustc },
835                     path: $path,
836                     extra_features: $sel.extra_features,
837                     is_optional_tool: true,
838                     source_type: if false $(|| $in_tree)* {
839                         SourceType::InTree
840                     } else {
841                         SourceType::Submodule
842                     },
843                 })
844             }
845         }
846         )+
847     }
848 }
849
850 // Note: tools need to be also added to `Builder::get_step_descriptions` in `builder.rs`
851 // to make `./x.py build <tool>` work.
852 // Note: Most submodule updates for tools are handled by bootstrap.py, since they're needed just to
853 // invoke Cargo to build bootstrap. See the comment there for more details.
854 tool_extended!((self, builder),
855     Cargofmt, "src/tools/rustfmt", "cargo-fmt", stable=true, in_tree=true, {};
856     CargoClippy, "src/tools/clippy", "cargo-clippy", stable=true, in_tree=true, {};
857     Clippy, "src/tools/clippy", "clippy-driver", stable=true, in_tree=true, {};
858     Miri, "src/tools/miri", "miri", stable=false, {};
859     CargoMiri, "src/tools/miri/cargo-miri", "cargo-miri", stable=false, {};
860     Rls, "src/tools/rls", "rls", stable=true, {};
861     // FIXME: tool_std is not quite right, we shouldn't allow nightly features.
862     // But `builder.cargo` doesn't know how to handle ToolBootstrap in stages other than 0,
863     // and this is close enough for now.
864     RustDemangler, "src/tools/rust-demangler", "rust-demangler", stable=false, in_tree=true, tool_std=true, {};
865     Rustfmt, "src/tools/rustfmt", "rustfmt", stable=true, in_tree=true, {};
866 );
867
868 impl<'a> Builder<'a> {
869     /// Gets a `Command` which is ready to run `tool` in `stage` built for
870     /// `host`.
871     pub fn tool_cmd(&self, tool: Tool) -> Command {
872         let mut cmd = Command::new(self.tool_exe(tool));
873         let compiler = self.compiler(0, self.config.build);
874         let host = &compiler.host;
875         // Prepares the `cmd` provided to be able to run the `compiler` provided.
876         //
877         // Notably this munges the dynamic library lookup path to point to the
878         // right location to run `compiler`.
879         let mut lib_paths: Vec<PathBuf> = vec![
880             self.build.rustc_snapshot_libdir(),
881             self.cargo_out(compiler, Mode::ToolBootstrap, *host).join("deps"),
882         ];
883
884         // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
885         // mode) and that C compiler may need some extra PATH modification. Do
886         // so here.
887         if compiler.host.contains("msvc") {
888             let curpaths = env::var_os("PATH").unwrap_or_default();
889             let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
890             for &(ref k, ref v) in self.cc[&compiler.host].env() {
891                 if k != "PATH" {
892                     continue;
893                 }
894                 for path in env::split_paths(v) {
895                     if !curpaths.contains(&path) {
896                         lib_paths.push(path);
897                     }
898                 }
899             }
900         }
901
902         add_dylib_path(lib_paths, &mut cmd);
903
904         // Provide a RUSTC for this command to use.
905         cmd.env("RUSTC", &self.initial_rustc);
906
907         cmd
908     }
909 }