tool.rs 25.8 KB
Newer Older
M
Mark Rousskov 已提交
1
use std::collections::HashSet;
2
use std::env;
M
Mark Rousskov 已提交
3
use std::fs;
4
use std::path::PathBuf;
M
Mark Rousskov 已提交
5
use std::process::{exit, Command};
6

7 8
use build_helper::t;

M
Mark Rousskov 已提交
9
use crate::builder::{Builder, Cargo as CargoCommand, RunConfig, ShouldRun, Step};
L
ljedrz 已提交
10
use crate::cache::Interned;
M
Mark Rousskov 已提交
11 12 13
use crate::channel;
use crate::channel::GitInfo;
use crate::compile;
L
ljedrz 已提交
14
use crate::toolstate::ToolState;
15
use crate::util::{add_dylib_path, exe, CiEnv};
M
Mark Rousskov 已提交
16 17
use crate::Compiler;
use crate::Mode;
18

19 20 21 22 23 24
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum SourceType {
    InTree,
    Submodule,
}

25
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
26 27 28 29
struct ToolBuild {
    compiler: Compiler,
    target: Interned<String>,
    tool: &'static str,
30
    path: &'static str,
31
    mode: Mode,
32
    is_optional_tool: bool,
33
    source_type: SourceType,
34
    extra_features: Vec<String>,
35 36
}

37
impl Step for ToolBuild {
38
    type Output = Option<PathBuf>;
39

T
Taiki Endo 已提交
40
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
41
        run.never()
42 43
    }

A
Alexander Regueiro 已提交
44
    /// Builds a tool in `src/tools`
45 46 47
    ///
    /// This will build the specified tool with the specified `host` compiler in
    /// `stage` into the normal cargo output directory.
T
Taiki Endo 已提交
48
    fn run(self, builder: &Builder<'_>) -> Option<PathBuf> {
49
        let compiler = self.compiler;
50 51
        let target = self.target;
        let tool = self.tool;
52
        let path = self.path;
53
        let is_optional_tool = self.is_optional_tool;
54

55
        match self.mode {
M
Mark Rousskov 已提交
56 57
            Mode::ToolRustc => builder.ensure(compile::Rustc { compiler, target }),
            Mode::ToolStd => builder.ensure(compile::Std { compiler, target }),
58
            Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs
M
Mark Rousskov 已提交
59
            _ => panic!("unexpected Mode for tool build"),
60 61
        }

62
        let cargo = prepare_tool_cargo(
63 64 65 66 67 68
            builder,
            compiler,
            self.mode,
            target,
            "build",
            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 {
M
Mark Rousskov 已提交
78
                "rls" | "cargo" | "clippy-driver" | "miri" | "rustfmt" => {}
79 80

                _ => return,
81 82 83 84 85
            }
            let (id, features, filenames) = match msg {
                compile::CargoMessage::CompilerArtifact {
                    package_id,
                    features,
J
John Kåre Alsaker 已提交
86 87
                    filenames,
                    target: _,
M
Mark Rousskov 已提交
88
                } => (package_id, features, filenames),
89 90 91 92 93 94 95 96
                _ => return,
            };
            let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();

            for path in filenames {
                let val = (tool, PathBuf::from(&*path), features.clone());
                // we're only interested in deduplicating rlibs for now
                if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
M
Mark Rousskov 已提交
97
                    continue;
98 99
                }

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
                // Don't worry about compiles that turn out to be host
                // dependencies or build scripts. To skip these we look for
                // anything that goes in `.../release/deps` but *doesn't* go in
                // `$target/release/deps`. This ensure that outputs in
                // `$target/release` are still considered candidates for
                // deduplication.
                if let Some(parent) = val.1.parent() {
                    if parent.ends_with("release/deps") {
                        let maybe_target = parent
                            .parent()
                            .and_then(|p| p.parent())
                            .and_then(|p| p.file_name())
                            .and_then(|p| p.to_str())
                            .unwrap();
                        if maybe_target != &*target {
                            continue;
                        }
117 118 119
                    }
                }

120 121 122
                // Record that we've built an artifact for `id`, and if one was
                // already listed then we need to see if we reused the same
                // artifact or produced a duplicate.
123
                let mut artifacts = builder.tool_artifacts.borrow_mut();
M
Mark Rousskov 已提交
124
                let prev_artifacts = artifacts.entry(target).or_default();
125 126 127 128 129
                let prev = match prev_artifacts.get(&*id) {
                    Some(prev) => prev,
                    None => {
                        prev_artifacts.insert(id.to_string(), val);
                        continue;
130
                    }
131 132 133
                };
                if prev.1 == val.1 {
                    return; // same path, same artifact
134
                }
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

                // If the paths are different and one of them *isn't* inside of
                // `release/deps`, then it means it's probably in
                // `$target/release`, or it's some final artifact like
                // `libcargo.rlib`. In these situations Cargo probably just
                // copied it up from `$target/release/deps/libcargo-xxxx.rlib`,
                // so if the features are equal we can just skip it.
                let prev_no_hash = prev.1.parent().unwrap().ends_with("release/deps");
                let val_no_hash = val.1.parent().unwrap().ends_with("release/deps");
                if prev.2 == val.2 || !prev_no_hash || !val_no_hash {
                    return;
                }

                // ... and otherwise this looks like we duplicated some sort of
                // compilation, so record it to generate an error later.
M
Mark Rousskov 已提交
150
                duplicates.push((id.to_string(), val, prev.clone()));
151 152 153
            }
        });

154
        if is_expected && !duplicates.is_empty() {
M
Mark Rousskov 已提交
155 156
            println!(
                "duplicate artifacts found when compiling a tool, this \
157 158
                      typically means that something was recompiled because \
                      a transitive dependency has different features activated \
M
Mark Rousskov 已提交
159 160 161 162 163 164
                      than in a previous build:\n"
            );
            println!(
                "the following dependencies are duplicated although they \
                      have the same features enabled:"
            );
O
Oliver Schneider 已提交
165
            for (id, cur, prev) in duplicates.drain_filter(|(_, cur, prev)| cur.2 == prev.2) {
166
                println!("  {}", id);
O
Oliver Schneider 已提交
167 168
                // same features
                println!("    `{}` ({:?})\n    `{}` ({:?})", cur.0, cur.1, prev.0, prev.1);
169 170
            }
            println!("the following dependencies have different features:");
171 172
            for (id, cur, prev) in duplicates {
                println!("  {}", id);
173 174
                let cur_features: HashSet<_> = cur.2.into_iter().collect();
                let prev_features: HashSet<_> = prev.2.into_iter().collect();
M
Mark Rousskov 已提交
175 176 177 178 179 180 181 182 183 184 185 186
                println!(
                    "    `{}` additionally enabled features {:?} at {:?}",
                    cur.0,
                    &cur_features - &prev_features,
                    cur.1
                );
                println!(
                    "    `{}` additionally enabled features {:?} at {:?}",
                    prev.0,
                    &prev_features - &cur_features,
                    prev.1
                );
187
            }
188
            println!();
M
Mark Rousskov 已提交
189 190
            println!(
                "to fix this you will probably want to edit the local \
A
Alex Crichton 已提交
191 192
                      src/tools/rustc-workspace-hack/Cargo.toml crate, as \
                      that will update the dependency graph to ensure that \
M
Mark Rousskov 已提交
193 194
                      these crates all share the same feature set"
            );
195 196 197
            panic!("tools should not compile multiple copies of the same crate");
        }

M
Mark Rousskov 已提交
198 199 200 201
        builder.save_toolstate(
            tool,
            if is_expected { ToolState::TestFail } else { ToolState::BuildFail },
        );
202 203

        if !is_expected {
204
            if !is_optional_tool {
M
Mark Simulacrum 已提交
205
                exit(1);
206
            } else {
207
                None
208
            }
209
        } else {
M
Mark Rousskov 已提交
210 211
            let cargo_out =
                builder.cargo_out(compiler, self.mode, target).join(exe(tool, &compiler.host));
212 213
            let bin = builder.tools_dir(compiler).join(exe(tool, &compiler.host));
            builder.copy(&cargo_out, &bin);
214 215
            Some(bin)
        }
216 217
    }
}
218

219
pub fn prepare_tool_cargo(
T
Taiki Endo 已提交
220
    builder: &Builder<'_>,
221
    compiler: Compiler,
C
Collins Abitekaniza 已提交
222
    mode: Mode,
223
    target: Interned<String>,
224
    command: &'static str,
225
    path: &'static str,
226
    source_type: SourceType,
227
    extra_features: &[String],
228
) -> CargoCommand {
C
Collins Abitekaniza 已提交
229
    let mut cargo = builder.cargo(compiler, mode, target, command);
230
    let dir = builder.src.join(path);
231 232
    cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));

233
    if source_type == SourceType::Submodule {
234
        cargo.env("RUSTC_EXTERNAL_TOOL", "1");
235 236
    }

237
    let mut features = extra_features.to_vec();
238
    if builder.build.config.cargo_native_static {
M
Mark Rousskov 已提交
239 240 241 242 243 244
        if path.ends_with("cargo")
            || path.ends_with("rls")
            || path.ends_with("clippy")
            || path.ends_with("miri")
            || path.ends_with("rustbook")
            || path.ends_with("rustfmt")
245 246 247 248
        {
            cargo.env("LIBZ_SYS_STATIC", "1");
            features.push("rustc-workspace-hack/all-static".to_string());
        }
249
    }
250

A
Alex Crichton 已提交
251 252 253 254
    // if tools are using lzma we want to force the build script to build its
    // own copy
    cargo.env("LZMA_API_STATIC", "1");

255 256 257 258
    // CFG_RELEASE is needed by rustfmt (and possibly other tools) which
    // import rustc-ap-rustc_attr which requires this to be set for the
    // `#[cfg(version(...))]` attribute.
    cargo.env("CFG_RELEASE", builder.rust_release());
259 260
    cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
    cargo.env("CFG_VERSION", builder.rust_version());
261
    cargo.env("CFG_RELEASE_NUM", channel::CFG_RELEASE_NUM);
262

J
Josh Stone 已提交
263
    let info = GitInfo::new(builder.config.ignore_git, &dir);
264 265 266 267 268 269 270 271
    if let Some(sha) = info.sha() {
        cargo.env("CFG_COMMIT_HASH", sha);
    }
    if let Some(sha_short) = info.sha_short() {
        cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
    }
    if let Some(date) = info.commit_date() {
        cargo.env("CFG_COMMIT_DATE", date);
272
    }
273
    if !features.is_empty() {
274 275
        cargo.arg("--features").arg(&features.join(", "));
    }
276
    cargo
277 278
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292
fn rustbook_features() -> Vec<String> {
    let mut features = Vec::new();

    // Due to CI budged and risk of spurious failures we want to limit jobs running this check.
    // At same time local builds should run it regardless of the platform.
    // `CiEnv::None` means it's local build and `CHECK_LINKS` is defined in x86_64-gnu-tools to
    // explicitly enable it on single job
    if CiEnv::current() == CiEnv::None || env::var("CHECK_LINKS").is_ok() {
        features.push("linkcheck".to_string());
    }

    features
}

293
macro_rules! bootstrap_tool {
294
    ($(
295
        $name:ident, $path:expr, $tool_name:expr
296
        $(,is_external_tool = $external:expr)*
297
        $(,is_unstable_tool = $unstable:expr)*
298
        $(,features = $features:expr)*
299 300
        ;
    )+) => {
301
        #[derive(Copy, PartialEq, Eq, Clone)]
302 303 304 305 306 307 308 309 310 311 312
        pub enum Tool {
            $(
                $name,
            )+
        }

        impl<'a> Builder<'a> {
            pub fn tool_exe(&self, tool: Tool) -> PathBuf {
                match tool {
                    $(Tool::$name =>
                        self.ensure($name {
313
                            compiler: self.compiler(0, self.config.build),
314
                            target: self.config.build,
315 316 317 318 319 320 321
                        }),
                    )+
                }
            }
        }

        $(
322 323
            #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
        pub struct $name {
324
            pub compiler: Compiler,
325
            pub target: Interned<String>,
326 327
        }

328
        impl Step for $name {
329 330
            type Output = PathBuf;

T
Taiki Endo 已提交
331
            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
332
                run.path($path)
333 334
            }

T
Taiki Endo 已提交
335
            fn make_run(run: RunConfig<'_>) {
336
                run.builder.ensure($name {
337 338
                    // snapshot compiler
                    compiler: run.builder.compiler(0, run.builder.config.build),
339
                    target: run.target,
340 341 342
                });
            }

T
Taiki Endo 已提交
343
            fn run(self, builder: &Builder<'_>) -> PathBuf {
344
                builder.ensure(ToolBuild {
345
                    compiler: self.compiler,
346 347
                    target: self.target,
                    tool: $tool_name,
348 349 350 351 352 353
                    mode: if false $(|| $unstable)* {
                        // use in-tree libraries for unstable features
                        Mode::ToolStd
                    } else {
                        Mode::ToolBootstrap
                    },
354
                    path: $path,
355
                    is_optional_tool: false,
356 357 358 359 360
                    source_type: if false $(|| $external)* {
                        SourceType::Submodule
                    } else {
                        SourceType::InTree
                    },
361 362 363 364 365 366
                    extra_features: {
                        // FIXME(#60643): avoid this lint by using `_`
                        let mut _tmp = Vec::new();
                        $(_tmp.extend($features);)*
                        _tmp
                    },
367
                }).expect("expected to build -- essential tool")
368 369 370 371 372 373
            }
        }
        )+
    }
}

374
bootstrap_tool!(
375
    Rustbook, "src/tools/rustbook", "rustbook", features = rustbook_features();
376 377 378 379
    UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
    Tidy, "src/tools/tidy", "tidy";
    Linkchecker, "src/tools/linkchecker", "linkchecker";
    CargoTest, "src/tools/cargotest", "cargotest";
380
    Compiletest, "src/tools/compiletest", "compiletest", is_unstable_tool = true;
381 382 383 384
    BuildManifest, "src/tools/build-manifest", "build-manifest";
    RemoteTestClient, "src/tools/remote-test-client", "remote-test-client";
    RustInstaller, "src/tools/rust-installer", "fabricate", is_external_tool = true;
    RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes";
385
    ExpandYamlAnchors, "src/tools/expand-yaml-anchors", "expand-yaml-anchors";
386 387
);

388 389 390 391 392 393 394
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct ErrorIndex {
    pub compiler: Compiler,
}

impl ErrorIndex {
    pub fn command(builder: &Builder<'_>, compiler: Compiler) -> Command {
M
Mark Rousskov 已提交
395
        let mut cmd = Command::new(builder.ensure(ErrorIndex { compiler }));
396
        add_dylib_path(
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
            vec![PathBuf::from(&builder.sysroot_libdir(compiler, compiler.host))],
            &mut cmd,
        );
        cmd
    }
}

impl Step for ErrorIndex {
    type Output = PathBuf;

    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
        run.path("src/tools/error_index_generator")
    }

    fn make_run(run: RunConfig<'_>) {
        // Compile the error-index in the same stage as rustdoc to avoid
        // recompiling rustdoc twice if we can.
        let stage = if run.builder.top_stage >= 2 { run.builder.top_stage } else { 0 };
M
Mark Rousskov 已提交
415 416
        run.builder
            .ensure(ErrorIndex { compiler: run.builder.compiler(stage, run.builder.config.build) });
417 418 419
    }

    fn run(self, builder: &Builder<'_>) -> PathBuf {
M
Mark Rousskov 已提交
420 421 422 423 424 425 426 427 428 429 430 431
        builder
            .ensure(ToolBuild {
                compiler: self.compiler,
                target: self.compiler.host,
                tool: "error_index_generator",
                mode: Mode::ToolRustc,
                path: "src/tools/error_index_generator",
                is_optional_tool: false,
                source_type: SourceType::InTree,
                extra_features: Vec::new(),
            })
            .expect("expected to build -- essential tool")
432 433 434
    }
}

435 436
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RemoteTestServer {
437
    pub compiler: Compiler,
438
    pub target: Interned<String>,
439 440
}

441
impl Step for RemoteTestServer {
442 443
    type Output = PathBuf;

T
Taiki Endo 已提交
444
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
445
        run.path("src/tools/remote-test-server")
446 447
    }

T
Taiki Endo 已提交
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
        });
    }

T
Taiki Endo 已提交
455
    fn run(self, builder: &Builder<'_>) -> PathBuf {
M
Mark Rousskov 已提交
456 457 458 459 460 461 462 463 464 465 466 467
        builder
            .ensure(ToolBuild {
                compiler: self.compiler,
                target: self.target,
                tool: "remote-test-server",
                mode: Mode::ToolStd,
                path: "src/tools/remote-test-server",
                is_optional_tool: false,
                source_type: SourceType::InTree,
                extra_features: Vec::new(),
            })
            .expect("expected to build -- essential tool")
468 469 470
    }
}

M
Mark Simulacrum 已提交
471 472
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Rustdoc {
M
Mark Rousskov 已提交
473 474 475
    /// This should only ever be 0 or 2.
    /// We sometimes want to reference the "bootstrap" rustdoc, which is why this option is here.
    pub compiler: Compiler,
M
Mark Simulacrum 已提交
476 477 478 479 480 481 482
}

impl Step for Rustdoc {
    type Output = PathBuf;
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
483
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
M
Mark Simulacrum 已提交
484 485 486
        run.path("src/tools/rustdoc")
    }

T
Taiki Endo 已提交
487
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
488 489
        run.builder
            .ensure(Rustdoc { compiler: run.builder.compiler(run.builder.top_stage, run.host) });
M
Mark Simulacrum 已提交
490 491
    }

T
Taiki Endo 已提交
492
    fn run(self, builder: &Builder<'_>) -> PathBuf {
M
Mark Rousskov 已提交
493
        let target_compiler = self.compiler;
M
Mark Rousskov 已提交
494 495 496 497 498 499
        if target_compiler.stage == 0 {
            if !target_compiler.is_snapshot(builder) {
                panic!("rustdoc in stage 0 must be snapshot rustdoc");
            }
            return builder.initial_rustc.with_file_name(exe("rustdoc", &target_compiler.host));
        }
500
        let target = target_compiler.host;
M
Mark Rousskov 已提交
501 502 503 504 505 506 507 508 509 510 511 512
        // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
        // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
        // compilers, which isn't what we want. Rustdoc should be linked in the same way as the
        // rustc compiler it's paired with, so it must be built with the previous stage compiler.
        let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);

        // The presence of `target_compiler` ensures that the necessary libraries (codegen backends,
        // compiler libraries, ...) are built. Rustdoc does not require the presence of any
        // libraries within sysroot_libdir (i.e., rustlib), though doctests may want it (since
        // they'll be linked to those libraries). As such, don't explicitly `ensure` any additional
        // libraries here. The intuition here is that If we've built a compiler, we should be able
        // to build rustdoc.
513

514
        let cargo = prepare_tool_cargo(
515 516 517 518 519 520
            builder,
            build_compiler,
            Mode::ToolRustc,
            target,
            "build",
            "src/tools/rustdoc",
521
            SourceType::InTree,
522
            &[],
523
        );
524

M
Mark Rousskov 已提交
525 526 527 528
        builder.info(&format!(
            "Building rustdoc for stage{} ({})",
            target_compiler.stage, target_compiler.host
        ));
529
        builder.run(&mut cargo.into());
530

531 532 533
        // Cargo adds a number of paths to the dylib search path on windows, which results in
        // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
        // rustdoc a different name.
M
Mark Rousskov 已提交
534 535
        let tool_rustdoc = builder
            .cargo_out(build_compiler, Mode::ToolRustc, target)
536
            .join(exe("rustdoc_tool_binary", &target_compiler.host));
M
Mark Simulacrum 已提交
537 538 539 540 541 542 543 544

        // don't create a stage0-sysroot/bin directory.
        if target_compiler.stage > 0 {
            let sysroot = builder.sysroot(target_compiler);
            let bindir = sysroot.join("bin");
            t!(fs::create_dir_all(&bindir));
            let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
            let _ = fs::remove_file(&bin_rustdoc);
545
            builder.copy(&tool_rustdoc, &bin_rustdoc);
M
Mark Simulacrum 已提交
546 547 548 549 550 551 552
            bin_rustdoc
        } else {
            tool_rustdoc
        }
    }
}

553 554
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Cargo {
555
    pub compiler: Compiler,
556
    pub target: Interned<String>,
557 558
}

559
impl Step for Cargo {
560 561 562 563
    type Output = PathBuf;
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
564
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
565
        let builder = run.builder;
566
        run.path("src/tools/cargo").default_condition(builder.config.extended)
567 568
    }

T
Taiki Endo 已提交
569
    fn make_run(run: RunConfig<'_>) {
570
        run.builder.ensure(Cargo {
571
            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
572
            target: run.target,
573 574 575
        });
    }

T
Taiki Endo 已提交
576
    fn run(self, builder: &Builder<'_>) -> PathBuf {
M
Mark Rousskov 已提交
577 578 579 580 581 582 583 584 585 586 587 588
        builder
            .ensure(ToolBuild {
                compiler: self.compiler,
                target: self.target,
                tool: "cargo",
                mode: Mode::ToolRustc,
                path: "src/tools/cargo",
                is_optional_tool: false,
                source_type: SourceType::Submodule,
                extra_features: Vec::new(),
            })
            .expect("expected to build -- essential tool")
589 590 591
    }
}

592 593 594 595 596 597
macro_rules! tool_extended {
    (($sel:ident, $builder:ident),
       $($name:ident,
       $toolstate:ident,
       $path:expr,
       $tool_name:expr,
R
Ralf Jung 已提交
598
       stable = $stable:expr,
599 600
       $extra_deps:block;)+) => {
        $(
601
            #[derive(Debug, Clone, Hash, PartialEq, Eq)]
602 603 604
        pub struct $name {
            pub compiler: Compiler,
            pub target: Interned<String>,
605
            pub extra_features: Vec<String>,
606
        }
O
Oliver Schneider 已提交
607

608 609
        impl Step for $name {
            type Output = Option<PathBuf>;
R
Ralf Jung 已提交
610
            const DEFAULT: bool = true; // Overwritten below
611
            const ONLY_HOSTS: bool = true;
O
Oliver Schneider 已提交
612

T
Taiki Endo 已提交
613
            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
614
                let builder = run.builder;
615 616
                run.path($path).default_condition(
                    builder.config.extended
R
Ralf Jung 已提交
617 618 619 620 621 622 623 624 625
                        && builder.config.tools.as_ref().map_or(
                            // By default, on nightly/dev enable all tools, else only
                            // build stable tools.
                            $stable || builder.build.unstable_features(),
                            // If `tools` is set, search list for this tool.
                            |tools| {
                                tools.iter().any(|tool| match tool.as_ref() {
                                    "clippy" => $tool_name == "clippy-driver",
                                    x => $tool_name == x,
626 627 628
                            })
                        }),
                )
629
            }
O
Oliver Schneider 已提交
630

T
Taiki Endo 已提交
631
            fn make_run(run: RunConfig<'_>) {
632
                run.builder.ensure($name {
633
                    compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
634
                    target: run.target,
635
                    extra_features: Vec::new(),
636 637 638
                });
            }

639
            #[allow(unused_mut)]
T
Taiki Endo 已提交
640
            fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
641 642 643 644 645
                $extra_deps
                $builder.ensure(ToolBuild {
                    compiler: $sel.compiler,
                    target: $sel.target,
                    tool: $tool_name,
C
Collins Abitekaniza 已提交
646
                    mode: Mode::ToolRustc,
647
                    path: $path,
648
                    extra_features: $sel.extra_features,
649
                    is_optional_tool: true,
650
                    source_type: SourceType::Submodule,
651 652 653 654
                })
            }
        }
        )+
O
Oliver Schneider 已提交
655
    }
656
}
O
Oliver Schneider 已提交
657

658 659
// Note: tools need to be also added to `Builder::get_step_descriptions` in `build.rs`
// to make `./x.py build <tool>` work.
660
tool_extended!((self, builder),
R
Ralf Jung 已提交
661 662 663 664 665 666
    Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", stable=true, {};
    CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", stable=true, {};
    Clippy, clippy, "src/tools/clippy", "clippy-driver", stable=true, {};
    Miri, miri, "src/tools/miri", "miri", stable=false, {};
    CargoMiri, miri, "src/tools/miri/cargo-miri", "cargo-miri", stable=false, {};
    Rls, rls, "src/tools/rls", "rls", stable=true, {
O
Oliver Scherer 已提交
667
        builder.ensure(Clippy {
668 669 670 671
            compiler: self.compiler,
            target: self.target,
            extra_features: Vec::new(),
        });
O
Oliver Scherer 已提交
672
        self.extra_features.push("clippy".to_owned());
673
    };
R
Ralf Jung 已提交
674
    Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", stable=true, {};
675
);
676

M
Mark Simulacrum 已提交
677
impl<'a> Builder<'a> {
A
Alexander Regueiro 已提交
678
    /// Gets a `Command` which is ready to run `tool` in `stage` built for
M
Mark Simulacrum 已提交
679
    /// `host`.
M
Mark Simulacrum 已提交
680 681
    pub fn tool_cmd(&self, tool: Tool) -> Command {
        let mut cmd = Command::new(self.tool_exe(tool));
682
        let compiler = self.compiler(0, self.config.build);
683
        let host = &compiler.host;
M
Mark Rousskov 已提交
684 685 686 687
        // Prepares the `cmd` provided to be able to run the `compiler` provided.
        //
        // Notably this munges the dynamic library lookup path to point to the
        // right location to run `compiler`.
688
        let mut lib_paths: Vec<PathBuf> = vec![
M
Mark Rousskov 已提交
689
            self.build.rustc_snapshot_libdir(),
M
Mark Rousskov 已提交
690
            self.cargo_out(compiler, Mode::ToolBootstrap, *host).join("deps"),
M
Mark Simulacrum 已提交
691 692
        ];

693
        // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
M
Mark Simulacrum 已提交
694 695 696
        // mode) and that C compiler may need some extra PATH modification. Do
        // so here.
        if compiler.host.contains("msvc") {
M
Mark Simulacrum 已提交
697
            let curpaths = env::var_os("PATH").unwrap_or_default();
M
Mark Simulacrum 已提交
698
            let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
699
            for &(ref k, ref v) in self.cc[&compiler.host].env() {
M
Mark Simulacrum 已提交
700
                if k != "PATH" {
M
Mark Rousskov 已提交
701
                    continue;
M
Mark Simulacrum 已提交
702 703 704
                }
                for path in env::split_paths(v) {
                    if !curpaths.contains(&path) {
705
                        lib_paths.push(path);
M
Mark Simulacrum 已提交
706 707 708 709
                    }
                }
            }
        }
710

711
        add_dylib_path(lib_paths, &mut cmd);
M
Mark Rousskov 已提交
712
        cmd
713
    }
M
Mark Simulacrum 已提交
714
}