tool.rs 24.3 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;
M
Mark Rousskov 已提交
15 16 17
use crate::util::{add_lib_path, exe, CiEnv};
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 238
    let mut features = extra_features.iter().cloned().collect::<Vec<_>>();
    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
    cargo.env("CFG_RELEASE_CHANNEL", &builder.config.channel);
    cargo.env("CFG_VERSION", builder.rust_version());
257
    cargo.env("CFG_RELEASE_NUM", channel::CFG_RELEASE_NUM);
258

J
Josh Stone 已提交
259
    let info = GitInfo::new(builder.config.ignore_git, &dir);
260 261 262 263 264 265 266 267
    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);
268
    }
269
    if !features.is_empty() {
270 271
        cargo.arg("--features").arg(&features.join(", "));
    }
272
    cargo
273 274
}

275 276 277 278 279 280 281 282 283 284 285 286 287 288
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
}

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

        impl<'a> Builder<'a> {
            pub fn tool_exe(&self, tool: Tool) -> PathBuf {
                match tool {
                    $(Tool::$name =>
                        self.ensure($name {
308
                            compiler: self.compiler(0, self.config.build),
309
                            target: self.config.build,
310 311 312 313 314 315 316
                        }),
                    )+
                }
            }
        }

        $(
317 318
            #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
        pub struct $name {
319
            pub compiler: Compiler,
320
            pub target: Interned<String>,
321 322
        }

323
        impl Step for $name {
324 325
            type Output = PathBuf;

T
Taiki Endo 已提交
326
            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
327
                run.path($path)
328 329
            }

T
Taiki Endo 已提交
330
            fn make_run(run: RunConfig<'_>) {
331
                run.builder.ensure($name {
332 333
                    // snapshot compiler
                    compiler: run.builder.compiler(0, run.builder.config.build),
334
                    target: run.target,
335 336 337
                });
            }

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

364
bootstrap_tool!(
365
    Rustbook, "src/tools/rustbook", "rustbook", features = rustbook_features();
366 367 368 369
    UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen";
    Tidy, "src/tools/tidy", "tidy";
    Linkchecker, "src/tools/linkchecker", "linkchecker";
    CargoTest, "src/tools/cargotest", "cargotest";
J
Josh Stone 已提交
370
    Compiletest, "src/tools/compiletest", "compiletest";
371 372 373 374
    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";
375 376
);

377 378 379 380 381 382 383
#[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 已提交
384
        let mut cmd = Command::new(builder.ensure(ErrorIndex { compiler }));
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        add_lib_path(
            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 已提交
404 405
        run.builder
            .ensure(ErrorIndex { compiler: run.builder.compiler(stage, run.builder.config.build) });
406 407 408
    }

    fn run(self, builder: &Builder<'_>) -> PathBuf {
M
Mark Rousskov 已提交
409 410 411 412 413 414 415 416 417 418 419 420
        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")
421 422 423
    }
}

424 425
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RemoteTestServer {
426
    pub compiler: Compiler,
427
    pub target: Interned<String>,
428 429
}

430
impl Step for RemoteTestServer {
431 432
    type Output = PathBuf;

T
Taiki Endo 已提交
433
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
434
        run.path("src/tools/remote-test-server")
435 436
    }

T
Taiki Endo 已提交
437
    fn make_run(run: RunConfig<'_>) {
438
        run.builder.ensure(RemoteTestServer {
439
            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
440
            target: run.target,
441 442 443
        });
    }

T
Taiki Endo 已提交
444
    fn run(self, builder: &Builder<'_>) -> PathBuf {
M
Mark Rousskov 已提交
445 446 447 448 449 450 451 452 453 454 455 456
        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")
457 458 459
    }
}

M
Mark Simulacrum 已提交
460 461
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Rustdoc {
M
Mark Rousskov 已提交
462 463 464
    /// 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 已提交
465 466 467 468 469 470 471
}

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

T
Taiki Endo 已提交
472
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
M
Mark Simulacrum 已提交
473 474 475
        run.path("src/tools/rustdoc")
    }

T
Taiki Endo 已提交
476
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
477 478
        run.builder
            .ensure(Rustdoc { compiler: run.builder.compiler(run.builder.top_stage, run.host) });
M
Mark Simulacrum 已提交
479 480
    }

T
Taiki Endo 已提交
481
    fn run(self, builder: &Builder<'_>) -> PathBuf {
M
Mark Rousskov 已提交
482
        let target_compiler = self.compiler;
M
Mark Rousskov 已提交
483 484 485 486 487 488
        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));
        }
489
        let target = target_compiler.host;
M
Mark Rousskov 已提交
490 491 492 493 494 495 496 497 498 499 500 501
        // 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.
502

503
        let cargo = prepare_tool_cargo(
504 505 506 507 508 509
            builder,
            build_compiler,
            Mode::ToolRustc,
            target,
            "build",
            "src/tools/rustdoc",
510
            SourceType::InTree,
511
            &[],
512
        );
513

M
Mark Rousskov 已提交
514 515 516 517
        builder.info(&format!(
            "Building rustdoc for stage{} ({})",
            target_compiler.stage, target_compiler.host
        ));
518
        builder.run(&mut cargo.into());
519

520 521 522
        // 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 已提交
523 524
        let tool_rustdoc = builder
            .cargo_out(build_compiler, Mode::ToolRustc, target)
525
            .join(exe("rustdoc_tool_binary", &target_compiler.host));
M
Mark Simulacrum 已提交
526 527 528 529 530 531 532 533

        // 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);
534
            builder.copy(&tool_rustdoc, &bin_rustdoc);
M
Mark Simulacrum 已提交
535 536 537 538 539 540 541
            bin_rustdoc
        } else {
            tool_rustdoc
        }
    }
}

542 543
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Cargo {
544
    pub compiler: Compiler,
545
    pub target: Interned<String>,
546 547
}

548
impl Step for Cargo {
549 550 551 552
    type Output = PathBuf;
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
553
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
554
        let builder = run.builder;
555
        run.path("src/tools/cargo").default_condition(builder.config.extended)
556 557
    }

T
Taiki Endo 已提交
558
    fn make_run(run: RunConfig<'_>) {
559
        run.builder.ensure(Cargo {
560
            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
561
            target: run.target,
562 563 564
        });
    }

T
Taiki Endo 已提交
565
    fn run(self, builder: &Builder<'_>) -> PathBuf {
M
Mark Rousskov 已提交
566 567 568 569 570 571 572 573 574 575 576 577
        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")
578 579 580
    }
}

581 582 583 584 585 586 587 588
macro_rules! tool_extended {
    (($sel:ident, $builder:ident),
       $($name:ident,
       $toolstate:ident,
       $path:expr,
       $tool_name:expr,
       $extra_deps:block;)+) => {
        $(
589
            #[derive(Debug, Clone, Hash, PartialEq, Eq)]
590 591 592
        pub struct $name {
            pub compiler: Compiler,
            pub target: Interned<String>,
593
            pub extra_features: Vec<String>,
594
        }
O
Oliver Schneider 已提交
595

596 597 598 599
        impl Step for $name {
            type Output = Option<PathBuf>;
            const DEFAULT: bool = true;
            const ONLY_HOSTS: bool = true;
O
Oliver Schneider 已提交
600

T
Taiki Endo 已提交
601
            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
602
                let builder = run.builder;
603
                run.path($path).default_condition(builder.config.extended)
604
            }
O
Oliver Schneider 已提交
605

T
Taiki Endo 已提交
606
            fn make_run(run: RunConfig<'_>) {
607
                run.builder.ensure($name {
608
                    compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
609
                    target: run.target,
610
                    extra_features: Vec::new(),
611 612 613
                });
            }

614
            #[allow(unused_mut)]
T
Taiki Endo 已提交
615
            fn run(mut $sel, $builder: &Builder<'_>) -> Option<PathBuf> {
616 617 618 619 620
                $extra_deps
                $builder.ensure(ToolBuild {
                    compiler: $sel.compiler,
                    target: $sel.target,
                    tool: $tool_name,
C
Collins Abitekaniza 已提交
621
                    mode: Mode::ToolRustc,
622
                    path: $path,
623
                    extra_features: $sel.extra_features,
624
                    is_optional_tool: true,
625
                    source_type: SourceType::Submodule,
626 627 628 629
                })
            }
        }
        )+
O
Oliver Schneider 已提交
630
    }
631
}
O
Oliver Schneider 已提交
632

633
tool_extended!((self, builder),
634
    Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
635 636
    CargoClippy, clippy, "src/tools/clippy", "cargo-clippy", {};
    Clippy, clippy, "src/tools/clippy", "clippy-driver", {};
637
    Miri, miri, "src/tools/miri", "miri", {};
638
    CargoMiri, miri, "src/tools/miri", "cargo-miri", {};
639
    Rls, rls, "src/tools/rls", "rls", {
640 641 642 643 644
        let clippy = builder.ensure(Clippy {
            compiler: self.compiler,
            target: self.target,
            extra_features: Vec::new(),
        });
645
        if clippy.is_some() {
646 647
            self.extra_features.push("clippy".to_owned());
        }
648 649 650
    };
    Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
);
651

M
Mark Simulacrum 已提交
652
impl<'a> Builder<'a> {
A
Alexander Regueiro 已提交
653
    /// Gets a `Command` which is ready to run `tool` in `stage` built for
M
Mark Simulacrum 已提交
654
    /// `host`.
M
Mark Simulacrum 已提交
655 656
    pub fn tool_cmd(&self, tool: Tool) -> Command {
        let mut cmd = Command::new(self.tool_exe(tool));
657
        let compiler = self.compiler(0, self.config.build);
658
        let host = &compiler.host;
M
Mark Rousskov 已提交
659 660 661 662
        // 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`.
663
        let mut lib_paths: Vec<PathBuf> = vec![
M
Mark Rousskov 已提交
664
            self.build.rustc_snapshot_libdir(),
M
Mark Rousskov 已提交
665
            self.cargo_out(compiler, Mode::ToolBootstrap, *host).join("deps"),
M
Mark Simulacrum 已提交
666 667
        ];

668
        // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make
M
Mark Simulacrum 已提交
669 670 671
        // mode) and that C compiler may need some extra PATH modification. Do
        // so here.
        if compiler.host.contains("msvc") {
M
Mark Simulacrum 已提交
672
            let curpaths = env::var_os("PATH").unwrap_or_default();
M
Mark Simulacrum 已提交
673
            let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
674
            for &(ref k, ref v) in self.cc[&compiler.host].env() {
M
Mark Simulacrum 已提交
675
                if k != "PATH" {
M
Mark Rousskov 已提交
676
                    continue;
M
Mark Simulacrum 已提交
677 678 679
                }
                for path in env::split_paths(v) {
                    if !curpaths.contains(&path) {
680
                        lib_paths.push(path);
M
Mark Simulacrum 已提交
681 682 683 684
                    }
                }
            }
        }
685

M
Mark Rousskov 已提交
686 687
        add_lib_path(lib_paths, &mut cmd);
        cmd
688
    }
M
Mark Simulacrum 已提交
689
}