test.rs 79.2 KB
Newer Older
1
//! Implementation of the test-related targets of the build system.
2 3 4 5
//!
//! This file implements the various regression test suites that we execute on
//! our CI.

6
use std::env;
7
use std::ffi::OsString;
U
Ulrik Sverdrup 已提交
8
use std::fmt;
9
use std::fs;
10
use std::iter;
S
Santiago Pastorino 已提交
11 12
use std::path::{Path, PathBuf};
use std::process::Command;
13

14
use build_helper::{self, output, t};
15

L
ljedrz 已提交
16
use crate::builder::{Builder, Compiler, Kind, RunConfig, ShouldRun, Step};
17
use crate::cache::Interned;
L
ljedrz 已提交
18
use crate::compile;
19
use crate::config::TargetSelection;
L
ljedrz 已提交
20 21 22
use crate::dist;
use crate::flags::Subcommand;
use crate::native;
M
Mark Rousskov 已提交
23
use crate::tool::{self, SourceType, Tool};
L
ljedrz 已提交
24
use crate::toolstate::ToolState;
25
use crate::util::{self, add_link_lib_path, dylib_path, dylib_path_var};
L
ljedrz 已提交
26
use crate::Crate as CargoCrate;
M
Mark Rousskov 已提交
27
use crate::{envify, DocTests, GitRepo, Mode};
28

M
Mark Simulacrum 已提交
29
const ADB_TEST_DIR: &str = "/data/tmp/work";
30

U
Ulrik Sverdrup 已提交
31
/// The two modes of the test runner; tests or benchmarks.
K
kennytm 已提交
32
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, PartialOrd, Ord)]
U
Ulrik Sverdrup 已提交
33
pub enum TestKind {
A
Alexander Regueiro 已提交
34
    /// Run `cargo test`.
U
Ulrik Sverdrup 已提交
35
    Test,
A
Alexander Regueiro 已提交
36
    /// Run `cargo bench`.
U
Ulrik Sverdrup 已提交
37 38 39
    Bench,
}

40 41 42 43 44
impl From<Kind> for TestKind {
    fn from(kind: Kind) -> Self {
        match kind {
            Kind::Test => TestKind::Test,
            Kind::Bench => TestKind::Bench,
S
Santiago Pastorino 已提交
45
            _ => panic!("unexpected kind in crate: {:?}", kind),
46 47 48 49
        }
    }
}

U
Ulrik Sverdrup 已提交
50 51 52 53 54 55 56 57 58 59 60
impl TestKind {
    // Return the cargo subcommand for this test kind
    fn subcommand(self) -> &'static str {
        match self {
            TestKind::Test => "test",
            TestKind::Bench => "bench",
        }
    }
}

impl fmt::Display for TestKind {
T
Taiki Endo 已提交
61
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
U
Ulrik Sverdrup 已提交
62 63 64 65 66 67 68
        f.write_str(match *self {
            TestKind::Test => "Testing",
            TestKind::Bench => "Benchmarking",
        })
    }
}

T
Taiki Endo 已提交
69
fn try_run(builder: &Builder<'_>, cmd: &mut Command) -> bool {
70 71 72
    if !builder.fail_fast {
        if !builder.try_run(cmd) {
            let mut failures = builder.delayed_failures.borrow_mut();
73
            failures.push(format!("{:?}", cmd));
O
Oliver Schneider 已提交
74
            return false;
75 76
        }
    } else {
77
        builder.run(cmd);
78
    }
O
Oliver Schneider 已提交
79
    true
80 81
}

T
Taiki Endo 已提交
82
fn try_run_quiet(builder: &Builder<'_>, cmd: &mut Command) -> bool {
83 84 85
    if !builder.fail_fast {
        if !builder.try_run_quiet(cmd) {
            let mut failures = builder.delayed_failures.borrow_mut();
86
            failures.push(format!("{:?}", cmd));
87
            return false;
88 89
        }
    } else {
90
        builder.run_quiet(cmd);
91
    }
92
    true
93 94
}

95 96
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Linkcheck {
97
    host: TargetSelection,
98 99
}

100
impl Step for Linkcheck {
101
    type Output = ();
102 103
    const ONLY_HOSTS: bool = true;
    const DEFAULT: bool = true;
104 105 106 107 108

    /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
    ///
    /// This tool in `src/tools` will verify the validity of all our links in the
    /// documentation to ensure we don't have a bunch of dead ones.
M
mark 已提交
109 110
    fn run(self, builder: &Builder<'_>) {
        let host = self.host;
111 112 113 114 115 116 117 118 119 120 121 122 123
        let hosts = &builder.hosts;
        let targets = &builder.targets;

        // if we have different hosts and targets, some things may be built for
        // the host (e.g. rustc) and others for the target (e.g. std). The
        // documentation built for each will contain broken links to
        // docs built for the other platform (e.g. rustc linking to cargo)
        if (hosts != targets) && !hosts.is_empty() && !targets.is_empty() {
            panic!(
                "Linkcheck currently does not support builds with different hosts and targets.
You can skip linkcheck with --exclude src/tools/linkchecker"
            );
        }
124

M
mark 已提交
125
        builder.info(&format!("Linkcheck ({})", host));
126

127
        builder.default_doc(&[]);
128

M
mark 已提交
129 130 131 132 133
        let _time = util::timeit(&builder);
        try_run(
            builder,
            builder.tool_cmd(Tool::Linkchecker).arg(builder.out.join(host.triple).join("doc")),
        );
134
    }
135

T
Taiki Endo 已提交
136
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
137
        let builder = run.builder;
138 139
        let run = run.path("src/tools/linkchecker");
        run.default_condition(builder.config.docs)
140 141
    }

T
Taiki Endo 已提交
142
    fn make_run(run: RunConfig<'_>) {
143
        run.builder.ensure(Linkcheck { host: run.target });
144
    }
145
}
146

147 148
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Cargotest {
149
    stage: u32,
150
    host: TargetSelection,
151
}
152

153
impl Step for Cargotest {
154
    type Output = ();
155
    const ONLY_HOSTS: bool = true;
156

T
Taiki Endo 已提交
157
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
158
        run.path("src/tools/cargotest")
159 160
    }

T
Taiki Endo 已提交
161
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
162
        run.builder.ensure(Cargotest { stage: run.builder.top_stage, host: run.target });
163 164
    }

165 166 167 168
    /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
    ///
    /// This tool in `src/tools` will check out a few Rust projects and run `cargo
    /// test` to ensure that we don't regress the test suites there.
T
Taiki Endo 已提交
169
    fn run(self, builder: &Builder<'_>) {
170
        let compiler = builder.compiler(self.stage, self.host);
M
Mark Rousskov 已提交
171
        builder.ensure(compile::Rustc { compiler, target: compiler.host });
E
Eric Huss 已提交
172
        let cargo = builder.ensure(tool::Cargo { compiler, target: compiler.host });
173 174 175 176

        // Note that this is a short, cryptic, and not scoped directory name. This
        // is currently to minimize the length of path on Windows where we otherwise
        // quickly run into path name limit constraints.
177
        let out_dir = builder.out.join("ct");
178 179
        t!(fs::create_dir_all(&out_dir));

180
        let _time = util::timeit(&builder);
181
        let mut cmd = builder.tool_cmd(Tool::CargoTest);
S
Santiago Pastorino 已提交
182 183
        try_run(
            builder,
E
Eric Huss 已提交
184
            cmd.arg(&cargo)
S
Santiago Pastorino 已提交
185
                .arg(&out_dir)
186
                .args(builder.config.cmd.test_args())
S
Santiago Pastorino 已提交
187
                .env("RUSTC", builder.rustc(compiler))
M
Mark Rousskov 已提交
188
                .env("RUSTDOC", builder.rustdoc(compiler)),
S
Santiago Pastorino 已提交
189
        );
190
    }
191 192
}

193 194
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Cargo {
195
    stage: u32,
196
    host: TargetSelection,
197 198
}

199
impl Step for Cargo {
200
    type Output = ();
201 202
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
203
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
204
        run.path("src/tools/cargo")
205 206
    }

T
Taiki Endo 已提交
207
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
208
        run.builder.ensure(Cargo { stage: run.builder.top_stage, host: run.target });
209
    }
210 211

    /// Runs `cargo test` for `cargo` packaged with Rust.
212 213
    fn run(self, builder: &Builder<'_>) {
        let compiler = builder.compiler(self.stage, self.host);
214

M
Mark Rousskov 已提交
215 216 217
        builder.ensure(tool::Cargo { compiler, target: self.host });
        let mut cargo = tool::prepare_tool_cargo(
            builder,
S
Santiago Pastorino 已提交
218
            compiler,
M
Mark Rousskov 已提交
219 220 221 222 223 224 225
            Mode::ToolRustc,
            self.host,
            "test",
            "src/tools/cargo",
            SourceType::Submodule,
            &[],
        );
226

227
        if !builder.fail_fast {
228 229
            cargo.arg("--no-fail-fast");
        }
230
        cargo.arg("--").args(builder.config.cmd.test_args());
231

232 233 234
        // Don't run cross-compile tests, we may not have cross-compiled libstd libs
        // available.
        cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
235 236
        // Disable a test that has issues with mingw.
        cargo.env("CARGO_TEST_DISABLE_GIT_CLI", "1");
237 238 239
        // Forcibly disable tests using nightly features since any changes to
        // those features won't be able to land.
        cargo.env("CARGO_TEST_DISABLE_NIGHTLY", "1");
240

241 242
        cargo.env("PATH", &path_for_cargo(builder, compiler));

243
        try_run(builder, &mut cargo.into());
244
    }
N
Nick Cameron 已提交
245 246
}

M
Mark Simulacrum 已提交
247 248
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Rls {
249
    stage: u32,
250
    host: TargetSelection,
251
}
N
Nick Cameron 已提交
252

M
Mark Simulacrum 已提交
253
impl Step for Rls {
254
    type Output = ();
M
Mark Simulacrum 已提交
255 256
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
257
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
258
        run.path("src/tools/rls")
M
Mark Simulacrum 已提交
259 260
    }

T
Taiki Endo 已提交
261
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
262
        run.builder.ensure(Rls { stage: run.builder.top_stage, host: run.target });
M
Mark Simulacrum 已提交
263
    }
N
Nick Cameron 已提交
264

265
    /// Runs `cargo test` for the rls.
T
Taiki Endo 已提交
266
    fn run(self, builder: &Builder<'_>) {
267 268
        let stage = self.stage;
        let host = self.host;
M
Mark Simulacrum 已提交
269
        let compiler = builder.compiler(stage, host);
N
Nick Cameron 已提交
270

M
Mark Rousskov 已提交
271 272
        let build_result =
            builder.ensure(tool::Rls { compiler, target: self.host, extra_features: Vec::new() });
273 274 275 276 277
        if build_result.is_none() {
            eprintln!("failed to test rls: could not build");
            return;
        }

M
Mark Rousskov 已提交
278 279 280 281 282 283 284 285 286 287
        let mut cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
            Mode::ToolRustc,
            host,
            "test",
            "src/tools/rls",
            SourceType::Submodule,
            &[],
        );
N
Nick Cameron 已提交
288

289
        cargo.add_rustc_lib_path(builder, compiler);
M
Mark Rousskov 已提交
290
        cargo.arg("--").args(builder.config.cmd.test_args());
291

292
        if try_run(builder, &mut cargo.into()) {
293
            builder.save_toolstate("rls", ToolState::TestPass);
O
Oliver Schneider 已提交
294
        }
295
    }
N
Nick Cameron 已提交
296 297
}

N
Nick Cameron 已提交
298 299 300
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Rustfmt {
    stage: u32,
301
    host: TargetSelection,
N
Nick Cameron 已提交
302 303 304 305 306 307
}

impl Step for Rustfmt {
    type Output = ();
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
308
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
N
Nick Cameron 已提交
309 310 311
        run.path("src/tools/rustfmt")
    }

T
Taiki Endo 已提交
312
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
313
        run.builder.ensure(Rustfmt { stage: run.builder.top_stage, host: run.target });
N
Nick Cameron 已提交
314 315 316
    }

    /// Runs `cargo test` for rustfmt.
T
Taiki Endo 已提交
317
    fn run(self, builder: &Builder<'_>) {
N
Nick Cameron 已提交
318 319 320 321
        let stage = self.stage;
        let host = self.host;
        let compiler = builder.compiler(stage, host);

322 323 324
        builder
            .ensure(tool::Rustfmt { compiler, target: self.host, extra_features: Vec::new() })
            .expect("in-tree tool");
325

M
Mark Rousskov 已提交
326 327 328 329 330 331 332 333 334 335
        let mut cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
            Mode::ToolRustc,
            host,
            "test",
            "src/tools/rustfmt",
            SourceType::Submodule,
            &[],
        );
N
Nick Cameron 已提交
336

N
Nick Cameron 已提交
337 338 339
        let dir = testdir(builder, compiler.host);
        t!(fs::create_dir_all(&dir));
        cargo.env("RUSTFMT_TEST_DIR", dir);
N
Nick Cameron 已提交
340

341
        cargo.add_rustc_lib_path(builder, compiler);
N
Nick Cameron 已提交
342

343
        builder.run(&mut cargo.into());
N
Nick Cameron 已提交
344 345
    }
}
O
Oliver Schneider 已提交
346

R
Rich Kadel 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct RustDemangler {
    stage: u32,
    host: TargetSelection,
}

impl Step for RustDemangler {
    type Output = ();
    const ONLY_HOSTS: bool = true;

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

    fn make_run(run: RunConfig<'_>) {
        run.builder.ensure(RustDemangler { stage: run.builder.top_stage, host: run.target });
    }

    /// Runs `cargo test` for rust-demangler.
    fn run(self, builder: &Builder<'_>) {
        let stage = self.stage;
        let host = self.host;
        let compiler = builder.compiler(stage, host);

        let rust_demangler = builder
            .ensure(tool::RustDemangler { compiler, target: self.host, extra_features: Vec::new() })
            .expect("in-tree tool");
        let mut cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
            Mode::ToolRustc,
            host,
            "test",
            "src/tools/rust-demangler",
            SourceType::InTree,
            &[],
        );

        let dir = testdir(builder, compiler.host);
        t!(fs::create_dir_all(&dir));

        cargo.env("RUST_DEMANGLER_DRIVER_PATH", rust_demangler);
389 390 391

        cargo.arg("--").args(builder.config.cmd.test_args());

R
Rich Kadel 已提交
392 393 394 395 396 397
        cargo.add_rustc_lib_path(builder, compiler);

        builder.run(&mut cargo.into());
    }
}

O
Oliver Schneider 已提交
398
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
399
pub struct Miri {
O
Oliver Schneider 已提交
400
    stage: u32,
401
    host: TargetSelection,
402 403 404 405 406 407
}

impl Step for Miri {
    type Output = ();
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
408
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
R
Ralf Jung 已提交
409
        run.path("src/tools/miri")
410 411
    }

T
Taiki Endo 已提交
412
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
413
        run.builder.ensure(Miri { stage: run.builder.top_stage, host: run.target });
414 415 416
    }

    /// Runs `cargo test` for miri.
T
Taiki Endo 已提交
417
    fn run(self, builder: &Builder<'_>) {
O
Oliver Schneider 已提交
418
        let stage = self.stage;
419
        let host = self.host;
O
Oliver Schneider 已提交
420
        let compiler = builder.compiler(stage, host);
421

M
Mark Rousskov 已提交
422 423
        let miri =
            builder.ensure(tool::Miri { compiler, target: self.host, extra_features: Vec::new() });
424 425 426 427 428 429
        let cargo_miri = builder.ensure(tool::CargoMiri {
            compiler,
            target: self.host,
            extra_features: Vec::new(),
        });
        if let (Some(miri), Some(_cargo_miri)) = (miri, cargo_miri) {
430 431
            let mut cargo =
                builder.cargo(compiler, Mode::ToolRustc, SourceType::Submodule, host, "install");
432 433 434 435 436 437 438 439 440
            cargo.arg("xargo");
            // Configure `cargo install` path. cargo adds a `bin/`.
            cargo.env("CARGO_INSTALL_ROOT", &builder.out);

            let mut cargo = Command::from(cargo);
            if !try_run(builder, &mut cargo) {
                return;
            }

441 442 443 444 445 446 447
            // # Run `cargo miri setup`.
            let mut cargo = tool::prepare_tool_cargo(
                builder,
                compiler,
                Mode::ToolRustc,
                host,
                "run",
448
                "src/tools/miri/cargo-miri",
449 450 451
                SourceType::Submodule,
                &[],
            );
R
Ralf Jung 已提交
452
            cargo.add_rustc_lib_path(builder, compiler);
453
            cargo.arg("--").arg("miri").arg("setup");
454 455

            // Tell `cargo miri setup` where to find the sources.
R
Ralf Jung 已提交
456
            cargo.env("XARGO_RUST_SRC", builder.src.join("library"));
457 458
            // Tell it where to find Miri.
            cargo.env("MIRI", &miri);
459 460
            // Debug things.
            cargo.env("RUST_BACKTRACE", "1");
461
            // Let cargo-miri know where xargo ended up.
462
            cargo.env("XARGO_CHECK", builder.out.join("bin").join("xargo-check"));
463

464
            let mut cargo = Command::from(cargo);
465 466 467 468 469
            if !try_run(builder, &mut cargo) {
                return;
            }

            // # Determine where Miri put its sysroot.
R
Ralf Jung 已提交
470
            // To this end, we run `cargo miri setup --print-sysroot` and capture the output.
471 472 473
            // (We do this separately from the above so that when the setup actually
            // happens we get some output.)
            // We re-use the `cargo` from above.
R
Ralf Jung 已提交
474
            cargo.arg("--print-sysroot");
475 476 477 478 479

            // FIXME: Is there a way in which we can re-use the usual `run` helpers?
            let miri_sysroot = if builder.config.dry_run {
                String::new()
            } else {
480
                builder.verbose(&format!("running: {:?}", cargo));
M
Mark Rousskov 已提交
481 482
                let out = cargo
                    .output()
483 484
                    .expect("We already ran `cargo miri setup` before and that worked");
                assert!(out.status.success(), "`cargo miri setup` returned with non-0 exit code");
R
Ralf Jung 已提交
485
                // Output is "<sysroot>\n".
486 487
                let stdout = String::from_utf8(out.stdout)
                    .expect("`cargo miri setup` stdout is not valid UTF-8");
R
Ralf Jung 已提交
488 489
                let sysroot = stdout.trim_end();
                builder.verbose(&format!("`cargo miri setup --print-sysroot` said: {:?}", sysroot));
490 491 492 493 494 495 496 497 498 499 500 501 502 503
                sysroot.to_owned()
            };

            // # Run `cargo test`.
            let mut cargo = tool::prepare_tool_cargo(
                builder,
                compiler,
                Mode::ToolRustc,
                host,
                "test",
                "src/tools/miri",
                SourceType::Submodule,
                &[],
            );
R
Ralf Jung 已提交
504
            cargo.add_rustc_lib_path(builder, compiler);
O
Oliver Schneider 已提交
505 506

            // miri tests need to know about the stage sysroot
507
            cargo.env("MIRI_SYSROOT", miri_sysroot);
O
Oliver Schneider 已提交
508
            cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
509
            cargo.env("MIRI", miri);
O
Oliver Schneider 已提交
510

511 512
            cargo.arg("--").args(builder.config.cmd.test_args());

513 514 515 516 517 518 519 520
            let mut cargo = Command::from(cargo);
            if !try_run(builder, &mut cargo) {
                return;
            }

            // # Run `cargo test` with `-Zmir-opt-level=4`.
            cargo.env("MIRIFLAGS", "-O -Zmir-opt-level=4");
            if !try_run(builder, &mut cargo) {
521
                return;
O
Oliver Schneider 已提交
522
            }
523 524 525

            // # Done!
            builder.save_toolstate("miri", ToolState::TestPass);
O
Oliver Schneider 已提交
526 527 528
        } else {
            eprintln!("failed to test miri: could not build");
        }
529 530 531
    }
}

532 533
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct CompiletestTest {
534
    host: TargetSelection,
535 536 537 538 539
}

impl Step for CompiletestTest {
    type Output = ();

T
Taiki Endo 已提交
540
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
541 542 543
        run.path("src/tools/compiletest")
    }

T
Taiki Endo 已提交
544
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
545
        run.builder.ensure(CompiletestTest { host: run.target });
546 547 548
    }

    /// Runs `cargo test` for compiletest.
T
Taiki Endo 已提交
549
    fn run(self, builder: &Builder<'_>) {
550
        let host = self.host;
551
        let compiler = builder.compiler(0, host);
552

553 554 555
        // We need `ToolStd` for the locally-built sysroot because
        // compiletest uses unstable features of the `test` crate.
        builder.ensure(compile::Std { compiler, target: host });
M
Mark Rousskov 已提交
556 557 558
        let cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
559
            Mode::ToolStd,
M
Mark Rousskov 已提交
560 561 562 563 564 565
            host,
            "test",
            "src/tools/compiletest",
            SourceType::InTree,
            &[],
        );
566

567
        try_run(builder, &mut cargo.into());
568 569 570
    }
}

571 572
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Clippy {
O
Oliver Schneider 已提交
573
    stage: u32,
574
    host: TargetSelection,
575 576 577 578 579 580 581
}

impl Step for Clippy {
    type Output = ();
    const ONLY_HOSTS: bool = true;
    const DEFAULT: bool = false;

T
Taiki Endo 已提交
582
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
583 584 585
        run.path("src/tools/clippy")
    }

T
Taiki Endo 已提交
586
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
587
        run.builder.ensure(Clippy { stage: run.builder.top_stage, host: run.target });
588 589 590
    }

    /// Runs `cargo test` for clippy.
T
Taiki Endo 已提交
591
    fn run(self, builder: &Builder<'_>) {
O
Oliver Schneider 已提交
592
        let stage = self.stage;
593
        let host = self.host;
O
Oliver Schneider 已提交
594
        let compiler = builder.compiler(stage, host);
595

M
Mark Rousskov 已提交
596 597 598 599 600
        let clippy = builder
            .ensure(tool::Clippy { compiler, target: self.host, extra_features: Vec::new() })
            .expect("in-tree tool");
        let mut cargo = tool::prepare_tool_cargo(
            builder,
601
            compiler,
M
Mark Rousskov 已提交
602 603 604 605 606 607 608
            Mode::ToolRustc,
            host,
            "test",
            "src/tools/clippy",
            SourceType::InTree,
            &[],
        );
O
Oliver Schneider 已提交
609

M
Mark Rousskov 已提交
610 611 612 613 614
        // clippy tests need to know about the stage sysroot
        cargo.env("SYSROOT", builder.sysroot(compiler));
        cargo.env("RUSTC_TEST_SUITE", builder.rustc(compiler));
        cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
        let host_libs = builder.stage_out(compiler, Mode::ToolRustc).join(builder.cargo_dir());
615 616 617 618
        let target_libs = builder
            .stage_out(compiler, Mode::ToolRustc)
            .join(&self.host.triple)
            .join(builder.cargo_dir());
M
Mark Rousskov 已提交
619 620 621 622
        cargo.env("HOST_LIBS", host_libs);
        cargo.env("TARGET_LIBS", target_libs);
        // clippy tests need to find the driver
        cargo.env("CLIPPY_DRIVER_PATH", clippy);
O
Oliver Schneider 已提交
623

M
Mark Rousskov 已提交
624
        cargo.arg("--").args(builder.config.cmd.test_args());
625

626
        cargo.add_rustc_lib_path(builder, compiler);
O
Oliver Schneider 已提交
627

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
        if builder.try_run(&mut cargo.into()) {
            // The tests succeeded; nothing to do.
            return;
        }

        if !builder.config.cmd.bless() {
            std::process::exit(1);
        }

        let mut cargo = builder.cargo(compiler, Mode::ToolRustc, SourceType::InTree, host, "run");
        cargo.arg("-p").arg("clippy_dev");
        // clippy_dev gets confused if it can't find `clippy/Cargo.toml`
        cargo.current_dir(&builder.src.join("src").join("tools").join("clippy"));
        if builder.config.rust_optimize {
            cargo.env("PROFILE", "release");
        } else {
            cargo.env("PROFILE", "debug");
        }
        cargo.arg("--");
        cargo.arg("bless");
A
Aaron Hill 已提交
648
        builder.run(&mut cargo.into());
649 650
    }
}
N
Nick Cameron 已提交
651

652 653 654 655 656 657 658 659
fn path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString {
    // Configure PATH to find the right rustc. NB. we have to use PATH
    // and not RUSTC because the Cargo test suite has tests that will
    // fail if rustc is not spelled `rustc`.
    let path = builder.sysroot(compiler).join("bin");
    let old_path = env::var_os("PATH").unwrap_or_default();
    env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
}
660

G
Guillaume Gomez 已提交
661 662 663 664 665 666 667 668 669 670
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RustdocTheme {
    pub compiler: Compiler,
}

impl Step for RustdocTheme {
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
671
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
G
Guillaume Gomez 已提交
672 673 674
        run.path("src/tools/rustdoc-themes")
    }

T
Taiki Endo 已提交
675
    fn make_run(run: RunConfig<'_>) {
676
        let compiler = run.builder.compiler(run.builder.top_stage, run.target);
G
Guillaume Gomez 已提交
677

678
        run.builder.ensure(RustdocTheme { compiler });
G
Guillaume Gomez 已提交
679 680
    }

T
Taiki Endo 已提交
681
    fn run(self, builder: &Builder<'_>) {
682
        let rustdoc = builder.out.join("bootstrap/debug/rustdoc");
G
Guillaume Gomez 已提交
683 684
        let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
        cmd.arg(rustdoc.to_str().unwrap())
M
Mark Rousskov 已提交
685
            .arg(builder.src.join("src/librustdoc/html/static/themes").to_str().unwrap())
S
Santiago Pastorino 已提交
686 687
            .env("RUSTC_STAGE", self.compiler.stage.to_string())
            .env("RUSTC_SYSROOT", builder.sysroot(self.compiler))
M
Mark Rousskov 已提交
688
            .env("RUSTDOC_LIBDIR", builder.sysroot_libdir(self.compiler, self.compiler.host))
S
Santiago Pastorino 已提交
689
            .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
M
Mark Rousskov 已提交
690
            .env("RUSTDOC_REAL", builder.rustdoc(self.compiler))
S
Santiago Pastorino 已提交
691
            .env("RUSTC_BOOTSTRAP", "1");
692
        if let Some(linker) = builder.linker(self.compiler.host) {
693 694
            cmd.env("RUSTDOC_LINKER", linker);
        }
695
        if builder.is_fuse_ld_lld(self.compiler.host) {
696
            cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
G
Guillaume Gomez 已提交
697
        }
698
        try_run(builder, &mut cmd);
G
Guillaume Gomez 已提交
699 700 701
    }
}

G
Guillaume Gomez 已提交
702
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
G
Guillaume Gomez 已提交
703
pub struct RustdocJSStd {
704
    pub target: TargetSelection,
G
Guillaume Gomez 已提交
705 706
}

G
Guillaume Gomez 已提交
707
impl Step for RustdocJSStd {
708
    type Output = ();
G
Guillaume Gomez 已提交
709 710 711
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
712
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
G
Guillaume Gomez 已提交
713
        run.path("src/test/rustdoc-js-std")
G
Guillaume Gomez 已提交
714 715
    }

T
Taiki Endo 已提交
716
    fn make_run(run: RunConfig<'_>) {
717
        run.builder.ensure(RustdocJSStd { target: run.target });
G
Guillaume Gomez 已提交
718 719
    }

T
Taiki Endo 已提交
720
    fn run(self, builder: &Builder<'_>) {
721 722
        if let Some(ref nodejs) = builder.config.nodejs {
            let mut command = Command::new(nodejs);
723
            command
724
                .arg(builder.src.join("src/tools/rustdoc-js/tester.js"))
725 726 727
                .arg("--crate-name")
                .arg("std")
                .arg("--resource-suffix")
728
                .arg(&builder.version)
729
                .arg("--doc-folder")
730
                .arg(builder.doc_out(self.target))
731
                .arg("--test-folder")
732
                .arg(builder.src.join("src/test/rustdoc-js-std"));
M
Mark Rousskov 已提交
733
            builder.ensure(crate::doc::Std { target: self.target, stage: builder.top_stage });
734 735
            builder.run(&mut command);
        } else {
M
Mark Rousskov 已提交
736
            builder.info("No nodejs found, skipping \"src/test/rustdoc-js-std\" tests");
737
        }
G
Guillaume Gomez 已提交
738 739 740
    }
}

G
Guillaume Gomez 已提交
741 742
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RustdocJSNotStd {
743
    pub target: TargetSelection,
G
Guillaume Gomez 已提交
744 745 746 747 748 749 750 751
    pub compiler: Compiler,
}

impl Step for RustdocJSNotStd {
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

G
Guillaume Gomez 已提交
752
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
G
Guillaume Gomez 已提交
753
        run.path("src/test/rustdoc-js")
G
Guillaume Gomez 已提交
754 755
    }

G
Guillaume Gomez 已提交
756
    fn make_run(run: RunConfig<'_>) {
757 758
        let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
        run.builder.ensure(RustdocJSNotStd { target: run.target, compiler });
G
Guillaume Gomez 已提交
759 760
    }

G
Guillaume Gomez 已提交
761
    fn run(self, builder: &Builder<'_>) {
762 763 764
        if builder.config.nodejs.is_some() {
            builder.ensure(Compiletest {
                compiler: self.compiler,
G
Guillaume Gomez 已提交
765
                target: self.target,
766 767
                mode: "js-doc-test",
                suite: "rustdoc-js",
768
                path: "src/test/rustdoc-js",
769
                compare_mode: None,
G
Guillaume Gomez 已提交
770 771
            });
        } else {
M
Mark Rousskov 已提交
772
            builder.info("No nodejs found, skipping \"src/test/rustdoc-js\" tests");
G
Guillaume Gomez 已提交
773 774 775 776
        }
    }
}

777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
fn check_if_browser_ui_test_is_installed_global(npm: &Path, global: bool) -> bool {
    let mut command = Command::new(&npm);
    command.arg("list").arg("--depth=0");
    if global {
        command.arg("--global");
    }
    let lines = command
        .output()
        .map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
        .unwrap_or(String::new());
    lines.contains(&" browser-ui-test@")
}

fn check_if_browser_ui_test_is_installed(npm: &Path) -> bool {
    check_if_browser_ui_test_is_installed_global(npm, false)
        || check_if_browser_ui_test_is_installed_global(npm, true)
}

G
Guillaume Gomez 已提交
795 796 797 798 799 800 801 802 803 804 805 806
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RustdocGUI {
    pub target: TargetSelection,
    pub compiler: Compiler,
}

impl Step for RustdocGUI {
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
807
        let builder = run.builder;
808
        let run = run.suite_path("src/test/rustdoc-gui");
809 810 811 812 813 814 815 816 817
        run.default_condition(
            builder.config.nodejs.is_some()
                && builder
                    .config
                    .npm
                    .as_ref()
                    .map(|p| check_if_browser_ui_test_is_installed(p))
                    .unwrap_or(false),
        )
G
Guillaume Gomez 已提交
818 819 820 821 822 823 824 825
    }

    fn make_run(run: RunConfig<'_>) {
        let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
        run.builder.ensure(RustdocGUI { target: run.target, compiler });
    }

    fn run(self, builder: &Builder<'_>) {
826 827
        let nodejs = builder.config.nodejs.as_ref().expect("nodejs isn't available");
        let npm = builder.config.npm.as_ref().expect("npm isn't available");
G
Guillaume Gomez 已提交
828

829
        builder.ensure(compile::Std { compiler: self.compiler, target: self.target });
830

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
        // The goal here is to check if the necessary packages are installed, and if not, we
        // panic.
        if !check_if_browser_ui_test_is_installed(&npm) {
            eprintln!(
                "error: rustdoc-gui test suite cannot be run because npm `browser-ui-test` \
                 dependency is missing",
            );
            eprintln!(
                "If you want to install the `{0}` dependency, run `npm install {0}`",
                "browser-ui-test",
            );
            panic!("Cannot run rustdoc-gui tests");
        }

        let out_dir = builder.test_out(self.target).join("rustdoc-gui");

        // We remove existing folder to be sure there won't be artifacts remaining.
        let _ = fs::remove_dir_all(&out_dir);

        let mut nb_generated = 0;
        // We generate docs for the libraries present in the rustdoc-gui's src folder.
        let libs_dir = builder.build.src.join("src/test/rustdoc-gui/src");
        for entry in libs_dir.read_dir().expect("read_dir call failed") {
            let entry = entry.expect("invalid entry");
            let path = entry.path();
            if path.extension().map(|e| e == "rs").unwrap_or(false) {
                let mut command = builder.rustdoc_cmd(self.compiler);
                command.arg(path).arg("-o").arg(&out_dir);
                builder.run(&mut command);
                nb_generated += 1;
            }
G
Guillaume Gomez 已提交
862
        }
863 864 865 866 867 868 869 870 871 872
        assert!(nb_generated > 0, "no documentation was generated...");

        // We now run GUI tests.
        let mut command = Command::new(&nodejs);
        command
            .arg(builder.build.src.join("src/tools/rustdoc-gui/tester.js"))
            .arg("--doc-folder")
            .arg(out_dir)
            .arg("--tests-folder")
            .arg(builder.build.src.join("src/test/rustdoc-gui"));
873 874 875 876 877 878 879
        for path in &builder.paths {
            if let Some(name) = path.file_name().and_then(|f| f.to_str()) {
                if name.ends_with(".goml") {
                    command.arg("--file").arg(name);
                }
            }
        }
880
        builder.run(&mut command);
G
Guillaume Gomez 已提交
881 882 883
    }
}

884
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
M
Mark Simulacrum 已提交
885
pub struct Tidy;
886

887
impl Step for Tidy {
888
    type Output = ();
889 890
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;
891

M
Mark Simulacrum 已提交
892
    /// Runs the `tidy` tool.
893 894 895 896
    ///
    /// This tool in `src/tools` checks up on various bits and pieces of style and
    /// otherwise just implements a few lint-like checks that are specific to the
    /// compiler itself.
897 898 899
    ///
    /// Once tidy passes, this step also runs `fmt --check` if tests are being run
    /// for the `dev` or `nightly` channels.
T
Taiki Endo 已提交
900
    fn run(self, builder: &Builder<'_>) {
901
        let mut cmd = builder.tool_cmd(Tool::Tidy);
M
mark 已提交
902
        cmd.arg(&builder.src);
903
        cmd.arg(&builder.initial_cargo);
904
        cmd.arg(&builder.out);
905
        cmd.arg(builder.jobs().to_string());
M
Mark Rousskov 已提交
906 907
        if builder.is_verbose() {
            cmd.arg("--verbose");
908
        }
909

910
        builder.info("tidy check");
911
        try_run(builder, &mut cmd);
912 913 914

        if builder.config.channel == "dev" || builder.config.channel == "nightly" {
            builder.info("fmt check");
915 916 917 918 919 920 921 922 923 924 925 926 927
            if builder.config.initial_rustfmt.is_none() {
                let inferred_rustfmt_dir = builder.config.initial_rustc.parent().unwrap();
                eprintln!(
                    "\
error: no `rustfmt` binary found in {PATH}
info: `rust.channel` is currently set to \"{CHAN}\"
help: if you are testing a beta branch, set `rust.channel` to \"beta\" in the `config.toml` file
help: to skip test's attempt to check tidiness, pass `--exclude src/tools/tidy` to `x.py test`",
                    PATH = inferred_rustfmt_dir.display(),
                    CHAN = builder.config.channel,
                );
                std::process::exit(1);
            }
928
            crate::format::format(&builder.build, !builder.config.cmd.bless(), &[]);
929
        }
930
    }
931

T
Taiki Endo 已提交
932
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
933
        run.path("src/tools/tidy")
934 935
    }

T
Taiki Endo 已提交
936
    fn make_run(run: RunConfig<'_>) {
M
Mark Simulacrum 已提交
937
        run.builder.ensure(Tidy);
938
    }
939
}
940

941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ExpandYamlAnchors;

impl Step for ExpandYamlAnchors {
    type Output = ();
    const ONLY_HOSTS: bool = true;

    /// Ensure the `generate-ci-config` tool was run locally.
    ///
    /// The tool in `src/tools` reads the CI definition in `src/ci/builders.yml` and generates the
    /// appropriate configuration for all our CI providers. This step ensures the tool was called
    /// by the user before committing CI changes.
    fn run(self, builder: &Builder<'_>) {
        builder.info("Ensuring the YAML anchors in the GitHub Actions config were expanded");
        try_run(
            builder,
            &mut builder.tool_cmd(Tool::ExpandYamlAnchors).arg("check").arg(&builder.src),
        );
    }

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

    fn make_run(run: RunConfig<'_>) {
        run.builder.ensure(ExpandYamlAnchors);
    }
}

970 971
fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
    builder.out.join(host.triple).join("test")
972 973
}

974 975 976
macro_rules! default_test {
    ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
        test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: false });
M
Mark Rousskov 已提交
977
    };
978 979
}

980 981 982
macro_rules! default_test_with_compare_mode {
    ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr,
                   compare_mode: $compare_mode:expr }) => {
M
Mark Rousskov 已提交
983 984 985 986 987 988 989 990 991
        test_with_compare_mode!($name {
            path: $path,
            mode: $mode,
            suite: $suite,
            default: true,
            host: false,
            compare_mode: $compare_mode
        });
    };
992 993
}

994 995 996
macro_rules! host_test {
    ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
        test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: true });
M
Mark Rousskov 已提交
997
    };
998 999
}

1000
macro_rules! test {
1001 1002
    ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
                   host: $host:expr }) => {
M
Mark Rousskov 已提交
1003 1004 1005 1006 1007 1008 1009 1010 1011
        test_definitions!($name {
            path: $path,
            mode: $mode,
            suite: $suite,
            default: $default,
            host: $host,
            compare_mode: None
        });
    };
1012 1013 1014 1015 1016
}

macro_rules! test_with_compare_mode {
    ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
                   host: $host:expr, compare_mode: $compare_mode:expr }) => {
M
Mark Rousskov 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025
        test_definitions!($name {
            path: $path,
            mode: $mode,
            suite: $suite,
            default: $default,
            host: $host,
            compare_mode: Some($compare_mode)
        });
    };
1026 1027 1028
}

macro_rules! test_definitions {
1029 1030 1031 1032 1033
    ($name:ident {
        path: $path:expr,
        mode: $mode:expr,
        suite: $suite:expr,
        default: $default:expr,
1034 1035
        host: $host:expr,
        compare_mode: $compare_mode:expr
1036 1037 1038 1039
    }) => {
        #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
        pub struct $name {
            pub compiler: Compiler,
1040
            pub target: TargetSelection,
1041 1042
        }

1043 1044 1045 1046
        impl Step for $name {
            type Output = ();
            const DEFAULT: bool = $default;
            const ONLY_HOSTS: bool = $host;
1047

T
Taiki Endo 已提交
1048
            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1049
                run.suite_path($path)
1050
            }
1051

T
Taiki Endo 已提交
1052
            fn make_run(run: RunConfig<'_>) {
1053
                let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1054

M
Mark Rousskov 已提交
1055
                run.builder.ensure($name { compiler, target: run.target });
1056
            }
1057

T
Taiki Endo 已提交
1058
            fn run(self, builder: &Builder<'_>) {
1059 1060 1061 1062 1063
                builder.ensure(Compiletest {
                    compiler: self.compiler,
                    target: self.target,
                    mode: $mode,
                    suite: $suite,
1064
                    path: $path,
1065
                    compare_mode: $compare_mode,
1066 1067 1068
                })
            }
        }
M
Mark Rousskov 已提交
1069
    };
1070 1071
}

1072
default_test_with_compare_mode!(Ui {
1073 1074
    path: "src/test/ui",
    mode: "ui",
1075 1076
    suite: "ui",
    compare_mode: "nll"
1077 1078 1079 1080 1081 1082 1083 1084
});

default_test!(RunPassValgrind {
    path: "src/test/run-pass-valgrind",
    mode: "run-pass-valgrind",
    suite: "run-pass-valgrind"
});

M
Mark Rousskov 已提交
1085
default_test!(MirOpt { path: "src/test/mir-opt", mode: "mir-opt", suite: "mir-opt" });
1086

M
Mark Rousskov 已提交
1087
default_test!(Codegen { path: "src/test/codegen", mode: "codegen", suite: "codegen" });
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

default_test!(CodegenUnits {
    path: "src/test/codegen-units",
    mode: "codegen-units",
    suite: "codegen-units"
});

default_test!(Incremental {
    path: "src/test/incremental",
    mode: "incremental",
    suite: "incremental"
});

1101 1102 1103 1104 1105 1106
default_test_with_compare_mode!(Debuginfo {
    path: "src/test/debuginfo",
    mode: "debuginfo",
    suite: "debuginfo",
    compare_mode: "split-dwarf"
});
1107

M
Mark Rousskov 已提交
1108
host_test!(UiFullDeps { path: "src/test/ui-fulldeps", mode: "ui", suite: "ui-fulldeps" });
1109

M
Mark Rousskov 已提交
1110
host_test!(Rustdoc { path: "src/test/rustdoc", mode: "rustdoc", suite: "rustdoc" });
1111
host_test!(RustdocUi { path: "src/test/rustdoc-ui", mode: "ui", suite: "rustdoc-ui" });
1112

N
Nixon Enraght-Moony 已提交
1113 1114 1115 1116 1117 1118
host_test!(RustdocJson {
    path: "src/test/rustdoc-json",
    mode: "rustdoc-json",
    suite: "rustdoc-json"
});

M
Mark Rousskov 已提交
1119
host_test!(Pretty { path: "src/test/pretty", mode: "pretty", suite: "pretty" });
1120

M
Mark Rousskov 已提交
1121
default_test!(RunMake { path: "src/test/run-make", mode: "run-make", suite: "run-make" });
1122

1123 1124 1125 1126 1127 1128
host_test!(RunMakeFullDeps {
    path: "src/test/run-make-fulldeps",
    mode: "run-make",
    suite: "run-make-fulldeps"
});

M
Mark Rousskov 已提交
1129
default_test!(Assembly { path: "src/test/assembly", mode: "assembly", suite: "assembly" });
D
Denys Zariaiev 已提交
1130

1131 1132 1133
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
struct Compiletest {
    compiler: Compiler,
1134
    target: TargetSelection,
1135 1136
    mode: &'static str,
    suite: &'static str,
1137
    path: &'static str,
1138
    compare_mode: Option<&'static str>,
1139 1140 1141 1142 1143
}

impl Step for Compiletest {
    type Output = ();

T
Taiki Endo 已提交
1144
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1145 1146 1147
        run.never()
    }

1148 1149 1150 1151 1152
    /// Executes the `compiletest` tool to run a suite of tests.
    ///
    /// Compiles all tests with `compiler` for `target` with the specified
    /// compiletest `mode` and `suite` arguments. For example `mode` can be
    /// "run-pass" or `suite` can be something like `debuginfo`.
T
Taiki Endo 已提交
1153
    fn run(self, builder: &Builder<'_>) {
1154 1155 1156
        if builder.top_stage == 0 && env::var("COMPILETEST_FORCE_STAGE0").is_err() {
            eprintln!("\
error: `--stage 0` runs compiletest on the beta compiler, not your local changes, and will almost always cause tests to fail
1157 1158
help: to test the compiler, use `--stage 1` instead
help: to test the standard library, use `--stage 0 library/std` instead
1159 1160 1161 1162 1163
note: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `COMPILETEST_FORCE_STAGE0=1`."
            );
            std::process::exit(1);
        }

1164 1165 1166 1167
        let compiler = self.compiler;
        let target = self.target;
        let mode = self.mode;
        let suite = self.suite;
1168

1169
        // Path for test suite
1170
        let suite_path = self.path;
1171

1172
        // Skip codegen tests if they aren't enabled in configuration.
1173
        if !builder.config.codegen_tests && suite == "codegen" {
1174 1175 1176 1177
            return;
        }

        if suite == "debuginfo" {
M
Mark Rousskov 已提交
1178 1179
            builder
                .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target });
1180 1181
        }

1182
        if suite.ends_with("fulldeps") {
1183 1184 1185
            builder.ensure(compile::Rustc { compiler, target });
        }

1186 1187 1188
        builder.ensure(compile::Std { compiler, target });
        // ensure that `libproc_macro` is available on the host.
        builder.ensure(compile::Std { compiler, target: compiler.host });
1189

1190 1191
        // Also provide `rust_test_helpers` for the host.
        builder.ensure(native::TestHelpers { target: compiler.host });
1192

1193 1194
        // As well as the target, except for plain wasm32, which can't build it
        if !target.contains("wasm32") || target.contains("emscripten") {
1195 1196
            builder.ensure(native::TestHelpers { target });
        }
1197

1198
        builder.ensure(RemoteCopyLibs { compiler, target });
1199 1200

        let mut cmd = builder.tool_cmd(Tool::Compiletest);
1201 1202 1203 1204

        // compiletest currently has... a lot of arguments, so let's just pass all
        // of them!

M
Mark Rousskov 已提交
1205 1206
        cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
        cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
1207
        cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1208

1209
        let is_rustdoc = suite.ends_with("rustdoc-ui") || suite.ends_with("rustdoc-js");
G
Guillaume Gomez 已提交
1210

1211
        // Avoid depending on rustdoc when we don't need it.
S
Santiago Pastorino 已提交
1212
        if mode == "rustdoc"
1213
            || mode == "run-make"
1214 1215
            || (mode == "ui" && is_rustdoc)
            || mode == "js-doc-test"
N
Nixon Enraght-Moony 已提交
1216
            || mode == "rustdoc-json"
S
Santiago Pastorino 已提交
1217
        {
M
Mark Rousskov 已提交
1218
            cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler));
1219 1220
        }

1221 1222 1223 1224 1225 1226 1227
        if mode == "rustdoc-json" {
            // Use the beta compiler for jsondocck
            let json_compiler = compiler.with_stage(0);
            cmd.arg("--jsondocck-path")
                .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target }));
        }

R
Rich Kadel 已提交
1228
        if mode == "run-make" && suite.ends_with("fulldeps") {
R
Rich Kadel 已提交
1229 1230 1231 1232
            let rust_demangler = builder
                .ensure(tool::RustDemangler { compiler, target, extra_features: Vec::new() })
                .expect("in-tree tool");
            cmd.arg("--rust-demangler-path").arg(rust_demangler);
R
Rich Kadel 已提交
1233 1234
        }

M
Mark Rousskov 已提交
1235 1236 1237
        cmd.arg("--src-base").arg(builder.src.join("src/test").join(suite));
        cmd.arg("--build-base").arg(testdir(builder, compiler.host).join(suite));
        cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
1238
        cmd.arg("--suite").arg(suite);
1239
        cmd.arg("--mode").arg(mode);
1240 1241
        cmd.arg("--target").arg(target.rustc_target_arg());
        cmd.arg("--host").arg(&*compiler.host.triple);
M
Mark Rousskov 已提交
1242
        cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.build));
1243

1244
        if builder.config.cmd.bless() {
1245 1246 1247
            cmd.arg("--bless");
        }

M
Mark Rousskov 已提交
1248 1249 1250 1251
        let compare_mode =
            builder.config.cmd.compare_mode().or_else(|| {
                if builder.config.test_compare_mode { self.compare_mode } else { None }
            });
S
Santiago Pastorino 已提交
1252

1253 1254 1255 1256 1257
        if let Some(ref pass) = builder.config.cmd.pass() {
            cmd.arg("--pass");
            cmd.arg(pass);
        }

T
Tyler Mandry 已提交
1258 1259 1260 1261 1262
        if let Some(ref run) = builder.config.cmd.run() {
            cmd.arg("--run");
            cmd.arg(run);
        }

1263
        if let Some(ref nodejs) = builder.config.nodejs {
1264 1265
            cmd.arg("--nodejs").arg(nodejs);
        }
G
Guillaume Gomez 已提交
1266 1267 1268
        if let Some(ref npm) = builder.config.npm {
            cmd.arg("--npm").arg(npm);
        }
1269

M
Mark Rousskov 已提交
1270
        let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
1271
        if !is_rustdoc {
1272
            if builder.config.rust_optimize_tests {
G
Guillaume Gomez 已提交
1273 1274
                flags.push("-O".to_string());
            }
1275
        }
1276
        flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests));
1277
        flags.push(builder.config.cmd.rustc_args().join(" "));
1278

1279
        if let Some(linker) = builder.linker(target) {
O
Oliver Schneider 已提交
1280 1281 1282
            cmd.arg("--linker").arg(linker);
        }

1283
        let mut hostflags = flags.clone();
M
Mark Rousskov 已提交
1284
        hostflags.push(format!("-Lnative={}", builder.test_helpers_out(compiler.host).display()));
1285
        hostflags.extend(builder.lld_flags(compiler.host));
1286 1287
        cmd.arg("--host-rustcflags").arg(hostflags.join(" "));

S
Shotaro Yamada 已提交
1288
        let mut targetflags = flags;
M
Mark Rousskov 已提交
1289
        targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
1290
        targetflags.extend(builder.lld_flags(target));
1291 1292
        cmd.arg("--target-rustcflags").arg(targetflags.join(" "));

1293
        cmd.arg("--docck-python").arg(builder.python());
1294

1295
        if builder.config.build.ends_with("apple-darwin") {
1296
            // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1297 1298
            // LLDB plugin's compiled module which only works with the system python
            // (namely not Homebrew-installed python)
1299
            cmd.arg("--lldb-python").arg("/usr/bin/python3");
1300
        } else {
1301
            cmd.arg("--lldb-python").arg(builder.python());
1302
        }
1303

1304
        if let Some(ref gdb) = builder.config.gdb {
1305 1306
            cmd.arg("--gdb").arg(gdb);
        }
1307 1308 1309 1310

        let run = |cmd: &mut Command| {
            cmd.output().map(|output| {
                String::from_utf8_lossy(&output.stdout)
M
Mark Rousskov 已提交
1311 1312 1313 1314
                    .lines()
                    .next()
                    .unwrap_or_else(|| panic!("{:?} failed {:?}", cmd, output))
                    .to_string()
1315 1316
            })
        };
1317 1318
        let lldb_exe = "lldb";
        let lldb_version = Command::new(lldb_exe)
1319 1320
            .arg("--version")
            .output()
M
Mark Rousskov 已提交
1321
            .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
1322 1323
            .ok();
        if let Some(ref vers) = lldb_version {
1324
            cmd.arg("--lldb-version").arg(vers);
1325
            let lldb_python_dir = run(Command::new(lldb_exe).arg("-P")).ok();
1326 1327 1328
            if let Some(ref dir) = lldb_python_dir {
                cmd.arg("--lldb-python-dir").arg(dir);
            }
1329
        }
1330

1331 1332 1333
        if util::forcing_clang_based_tests() {
            let clang_exe = builder.llvm_out(target).join("bin").join("clang");
            cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
1334 1335
        }

1336 1337
        // Get paths from cmd args
        let paths = match &builder.config.cmd {
S
Santiago Pastorino 已提交
1338 1339
            Subcommand::Test { ref paths, .. } => &paths[..],
            _ => &[],
1340 1341 1342
        };

        // Get test-args by striping suite path
S
Santiago Pastorino 已提交
1343 1344
        let mut test_args: Vec<&str> = paths
            .iter()
M
Mark Rousskov 已提交
1345 1346 1347
            .map(|p| match p.strip_prefix(".") {
                Ok(path) => path,
                Err(_) => p,
1348
            })
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
            .filter(|p| p.starts_with(suite_path))
            .filter(|p| {
                let exists = p.is_dir() || p.is_file();
                if !exists {
                    if let Some(p) = p.to_str() {
                        builder.info(&format!(
                            "Warning: Skipping \"{}\": not a regular file or directory",
                            p
                        ));
                    }
                }
                exists
            })
1362
            .filter_map(|p| {
V
varkor 已提交
1363 1364 1365 1366 1367 1368
                // Since test suite paths are themselves directories, if we don't
                // specify a directory or file, we'll get an empty string here
                // (the result of the test suite directory without its suite prefix).
                // Therefore, we need to filter these out, as only the first --test-args
                // flag is respected, so providing an empty --test-args conflicts with
                // any following it.
1369
                match p.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
M
Matthias Krüger 已提交
1370
                    Some(s) if !s.is_empty() => Some(s),
1371 1372 1373
                    _ => None,
                }
            })
S
Santiago Pastorino 已提交
1374
            .collect();
1375 1376 1377 1378

        test_args.append(&mut builder.config.cmd.test_args());

        cmd.args(&test_args);
1379

1380
        if builder.is_verbose() {
1381 1382
            cmd.arg("--verbose");
        }
1383

O
Oliver Schneider 已提交
1384
        if !builder.config.verbose_tests {
1385 1386
            cmd.arg("--quiet");
        }
1387

1388 1389
        let mut llvm_components_passed = false;
        let mut copts_passed = false;
B
bjorn3 已提交
1390
        if builder.config.llvm_enabled() {
M
Mark Rousskov 已提交
1391
            let llvm_config = builder.ensure(native::Llvm { target: builder.config.build });
1392
            if !builder.config.dry_run {
1393
                let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1394
                let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1395
                // Remove trailing newline from llvm-config output.
1396 1397 1398 1399 1400
                cmd.arg("--llvm-version")
                    .arg(llvm_version.trim())
                    .arg("--llvm-components")
                    .arg(llvm_components.trim());
                llvm_components_passed = true;
1401
            }
1402
            if !builder.is_rust_llvm(target) {
B
bjorn3 已提交
1403 1404 1405
                cmd.arg("--system-llvm");
            }

1406 1407 1408 1409 1410 1411 1412 1413 1414
            // Tests that use compiler libraries may inherit the `-lLLVM` link
            // requirement, but the `-L` library path is not propagated across
            // separate compilations. We can add LLVM's library path to the
            // platform-specific environment variable as a workaround.
            if !builder.config.dry_run && suite.ends_with("fulldeps") {
                let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
                add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cmd);
            }

B
bjorn3 已提交
1415 1416
            // Only pass correct values for these flags for the `run-make` suite as it
            // requires that a C++ compiler was configured which isn't always the case.
1417
            if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1418 1419
                // The llvm/bin directory contains many useful cross-platform
                // tools. Pass the path to run-make tests so they can use them.
M
Mark Rousskov 已提交
1420 1421
                let llvm_bin_path = llvm_config
                    .parent()
1422 1423 1424
                    .expect("Expected llvm-config to be contained in directory");
                assert!(llvm_bin_path.is_dir());
                cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
1425 1426 1427

                // If LLD is available, add it to the PATH
                if builder.config.lld_enabled {
M
Mark Rousskov 已提交
1428 1429
                    let lld_install_root =
                        builder.ensure(native::Lld { target: builder.config.build });
1430 1431 1432 1433

                    let lld_bin_path = lld_install_root.join("bin");

                    let old_path = env::var_os("PATH").unwrap_or_default();
M
Mark Rousskov 已提交
1434 1435 1436 1437
                    let new_path = env::join_paths(
                        std::iter::once(lld_bin_path).chain(env::split_paths(&old_path)),
                    )
                    .expect("Could not add LLD bin path to PATH");
1438 1439
                    cmd.env("PATH", new_path);
                }
B
bjorn3 已提交
1440 1441 1442
            }
        }

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
        // Only pass correct values for these flags for the `run-make` suite as it
        // requires that a C++ compiler was configured which isn't always the case.
        if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
            cmd.arg("--cc")
                .arg(builder.cc(target))
                .arg("--cxx")
                .arg(builder.cxx(target).unwrap())
                .arg("--cflags")
                .arg(builder.cflags(target, GitRepo::Rustc).join(" "));
            copts_passed = true;
            if let Some(ar) = builder.ar(target) {
                cmd.arg("--ar").arg(ar);
            }
        }

1458 1459 1460 1461 1462
        if !llvm_components_passed {
            cmd.arg("--llvm-components").arg("");
        }
        if !copts_passed {
            cmd.arg("--cc").arg("").arg("--cxx").arg("").arg("--cflags").arg("");
1463
        }
1464

1465
        if builder.remote_tested(target) {
M
Mark Rousskov 已提交
1466
            cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
1467
        }
1468

1469 1470 1471 1472 1473 1474
        // Running a C compiler on MSVC requires a few env vars to be set, to be
        // sure to set them here.
        //
        // Note that if we encounter `PATH` we make sure to append to our own `PATH`
        // rather than stomp over it.
        if target.contains("msvc") {
1475
            for &(ref k, ref v) in builder.cc[&target].env() {
1476 1477 1478
                if k != "PATH" {
                    cmd.env(k, v);
                }
1479 1480
            }
        }
1481
        cmd.env("RUSTC_BOOTSTRAP", "1");
1482
        cmd.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
1483
        builder.add_rust_test_threads(&mut cmd);
1484

1485
        if builder.config.sanitizers_enabled(target) {
1486
            cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
1487
        }
1488

1489
        if builder.config.profiler_enabled(target) {
1490
            cmd.env("RUSTC_PROFILER_SUPPORT", "1");
1491
        }
1492

M
Mark Rousskov 已提交
1493 1494 1495 1496
        let tmp = builder.out.join("tmp");
        std::fs::create_dir_all(&tmp).unwrap();
        cmd.env("RUST_TEST_TMPDIR", tmp);

1497 1498 1499 1500 1501
        cmd.arg("--adb-path").arg("adb");
        cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
        if target.contains("android") {
            // Assume that cc for this target comes from the android sysroot
            cmd.arg("--android-cross-path")
S
Santiago Pastorino 已提交
1502
                .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1503 1504 1505
        } else {
            cmd.arg("--android-cross-path").arg("");
        }
1506

1507 1508 1509 1510
        if builder.config.cmd.rustfix_coverage() {
            cmd.arg("--rustfix-coverage");
        }

1511 1512
        cmd.env("BOOTSTRAP_CARGO", &builder.initial_cargo);

1513 1514
        cmd.arg("--channel").arg(&builder.config.channel);

1515
        builder.ci_env.force_coloring_in_ci(&mut cmd);
1516

S
Santiago Pastorino 已提交
1517 1518 1519 1520
        builder.info(&format!(
            "Check compiletest suite={} mode={} ({} -> {})",
            suite, mode, &compiler.host, target
        ));
1521 1522
        let _time = util::timeit(&builder);
        try_run(builder, &mut cmd);
1523 1524 1525

        if let Some(compare_mode) = compare_mode {
            cmd.arg("--compare-mode").arg(compare_mode);
S
Santiago Pastorino 已提交
1526 1527 1528 1529
            builder.info(&format!(
                "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
                suite, mode, compare_mode, &compiler.host, target
            ));
1530 1531 1532
            let _time = util::timeit(&builder);
            try_run(builder, &mut cmd);
        }
1533
    }
1534
}
1535

E
Eric Huss 已提交
1536 1537
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct BookTest {
1538
    compiler: Compiler,
E
Eric Huss 已提交
1539
    path: PathBuf,
1540 1541
    name: &'static str,
    is_ext_doc: bool,
1542 1543
}

E
Eric Huss 已提交
1544
impl Step for BookTest {
1545 1546
    type Output = ();
    const ONLY_HOSTS: bool = true;
1547

T
Taiki Endo 已提交
1548
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1549
        run.never()
1550
    }
M
Mark Simulacrum 已提交
1551

E
Eric Huss 已提交
1552
    /// Runs the documentation tests for a book in `src/doc`.
1553
    ///
E
Eric Huss 已提交
1554
    /// This uses the `rustdoc` that sits next to `compiler`.
T
Taiki Endo 已提交
1555
    fn run(self, builder: &Builder<'_>) {
E
Eric Huss 已提交
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
        // External docs are different from local because:
        // - Some books need pre-processing by mdbook before being tested.
        // - They need to save their state to toolstate.
        // - They are only tested on the "checktools" builders.
        //
        // The local docs are tested by default, and we don't want to pay the
        // cost of building mdbook, so they use `rustdoc --test` directly.
        // Also, the unstable book is special because SUMMARY.md is generated,
        // so it is easier to just run `rustdoc` on its files.
        if self.is_ext_doc {
            self.run_ext_doc(builder);
        } else {
            self.run_local_doc(builder);
        }
    }
}

impl BookTest {
    /// This runs the equivalent of `mdbook test` (via the rustbook wrapper)
    /// which in turn runs `rustdoc --test` on each file in the book.
    fn run_ext_doc(self, builder: &Builder<'_>) {
        let compiler = self.compiler;

        builder.ensure(compile::Std { compiler, target: compiler.host });

        // mdbook just executes a binary named "rustdoc", so we need to update
        // PATH so that it points to our rustdoc.
        let mut rustdoc_path = builder.rustdoc(compiler);
        rustdoc_path.pop();
        let old_path = env::var_os("PATH").unwrap_or_default();
        let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path)))
            .expect("could not add rustdoc to PATH");

        let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
        let path = builder.src.join(&self.path);
        rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
        builder.add_rust_test_threads(&mut rustbook_cmd);
        builder.info(&format!("Testing rustbook {}", self.path.display()));
        let _time = util::timeit(&builder);
        let toolstate = if try_run(builder, &mut rustbook_cmd) {
            ToolState::TestPass
        } else {
            ToolState::TestFail
        };
        builder.save_toolstate(self.name, toolstate);
    }

    /// This runs `rustdoc --test` on all `.md` files in the path.
    fn run_local_doc(self, builder: &Builder<'_>) {
1605
        let compiler = self.compiler;
1606

M
Mark Rousskov 已提交
1607
        builder.ensure(compile::Std { compiler, target: compiler.host });
1608

1609 1610
        // Do a breadth-first traversal of the `src/doc` directory and just run
        // tests for all files that end in `*.md`
1611 1612
        let mut stack = vec![builder.src.join(self.path)];
        let _time = util::timeit(&builder);
1613
        let mut files = Vec::new();
1614 1615 1616
        while let Some(p) = stack.pop() {
            if p.is_dir() {
                stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
S
Santiago Pastorino 已提交
1617
                continue;
1618 1619 1620 1621 1622 1623
            }

            if p.extension().and_then(|s| s.to_str()) != Some("md") {
                continue;
            }

1624 1625 1626 1627 1628 1629
            files.push(p);
        }

        files.sort();

        for file in files {
E
Eric Huss 已提交
1630
            markdown_test(builder, compiler, &file);
1631
        }
1632 1633 1634
    }
}

1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
macro_rules! test_book {
    ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => {
        $(
            #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
            pub struct $name {
                compiler: Compiler,
            }

            impl Step for $name {
                type Output = ();
                const DEFAULT: bool = $default;
                const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
1648
                fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1649 1650 1651
                    run.path($path)
                }

T
Taiki Endo 已提交
1652
                fn make_run(run: RunConfig<'_>) {
1653
                    run.builder.ensure($name {
1654
                        compiler: run.builder.compiler(run.builder.top_stage, run.target),
1655 1656 1657
                    });
                }

T
Taiki Endo 已提交
1658
                fn run(self, builder: &Builder<'_>) {
E
Eric Huss 已提交
1659
                    builder.ensure(BookTest {
1660
                        compiler: self.compiler,
E
Eric Huss 已提交
1661
                        path: PathBuf::from($path),
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
                        name: $book_name,
                        is_ext_doc: !$default,
                    });
                }
            }
        )+
    }
}

test_book!(
    Nomicon, "src/doc/nomicon", "nomicon", default=false;
    Reference, "src/doc/reference", "reference", default=false;
    RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
1675
    RustcBook, "src/doc/rustc", "rustc", default=true;
1676
    RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1677
    EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
1678 1679
    TheBook, "src/doc/book", "book", default=false;
    UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
E
Eric Huss 已提交
1680
    EditionGuide, "src/doc/edition-guide", "edition-guide", default=false;
1681 1682
);

1683 1684 1685
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ErrorIndex {
    compiler: Compiler,
1686
}
1687

1688
impl Step for ErrorIndex {
1689
    type Output = ();
1690 1691 1692
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
1693
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1694
        run.path("src/tools/error_index_generator")
1695 1696
    }

T
Taiki Endo 已提交
1697
    fn make_run(run: RunConfig<'_>) {
E
Eric Huss 已提交
1698 1699 1700
        // error_index_generator depends on librustdoc. Use the compiler that
        // is normally used to build rustdoc for other tests (like compiletest
        // tests in src/test/rustdoc) so that it shares the same artifacts.
1701
        let compiler = run.builder.compiler(run.builder.top_stage, run.builder.config.build);
E
Eric Huss 已提交
1702
        run.builder.ensure(ErrorIndex { compiler });
1703
    }
1704

A
Alexander Regueiro 已提交
1705
    /// Runs the error index generator tool to execute the tests located in the error
1706 1707 1708 1709 1710
    /// index.
    ///
    /// The `error_index_generator` tool lives in `src/tools` and is used to
    /// generate a markdown file from the error indexes of the code base which is
    /// then passed to `rustdoc --test`.
T
Taiki Endo 已提交
1711
    fn run(self, builder: &Builder<'_>) {
1712 1713
        let compiler = self.compiler;

1714
        let dir = testdir(builder, compiler.host);
1715 1716 1717
        t!(fs::create_dir_all(&dir));
        let output = dir.join("error-index.md");

1718
        let mut tool = tool::ErrorIndex::command(builder);
E
Eric Huss 已提交
1719
        tool.arg("markdown").arg(&output);
1720

1721
        builder.info(&format!("Testing error-index stage{}", compiler.stage));
1722
        let _time = util::timeit(&builder);
1723
        builder.run_quiet(&mut tool);
1724 1725 1726 1727
        // The tests themselves need to link to std, so make sure it is
        // available.
        builder.ensure(compile::Std { compiler, target: compiler.host });
        markdown_test(builder, compiler, &output);
1728
    }
1729 1730
}

T
Taiki Endo 已提交
1731
fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
1732 1733 1734
    if let Ok(contents) = fs::read_to_string(markdown) {
        if !contents.contains("```") {
            return true;
1735
        }
1736 1737
    }

1738
    builder.info(&format!("doc tests for: {}", markdown.display()));
M
Mark Rousskov 已提交
1739
    let mut cmd = builder.rustdoc_cmd(compiler);
1740
    builder.add_rust_test_threads(&mut cmd);
1741 1742 1743
    // allow for unstable options such as new editions
    cmd.arg("-Z");
    cmd.arg("unstable-options");
1744 1745
    cmd.arg("--test");
    cmd.arg(markdown);
1746
    cmd.env("RUSTC_BOOTSTRAP", "1");
1747

1748
    let test_args = builder.config.cmd.test_args().join(" ");
1749 1750
    cmd.arg("--test-args").arg(test_args);

O
Oliver Schneider 已提交
1751
    if builder.config.verbose_tests {
1752
        try_run(builder, &mut cmd)
O
Oliver Schneider 已提交
1753 1754
    } else {
        try_run_quiet(builder, &mut cmd)
1755
    }
1756
}
1757

1758 1759 1760 1761 1762 1763 1764 1765 1766
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct RustcGuide;

impl Step for RustcGuide {
    type Output = ();
    const DEFAULT: bool = false;
    const ONLY_HOSTS: bool = true;

    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1767
        run.path("src/doc/rustc-dev-guide")
1768 1769 1770 1771 1772 1773 1774
    }

    fn make_run(run: RunConfig<'_>) {
        run.builder.ensure(RustcGuide);
    }

    fn run(self, builder: &Builder<'_>) {
1775
        let src = builder.src.join("src/doc/rustc-dev-guide");
1776
        let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
E
Eric Huss 已提交
1777 1778 1779 1780 1781
        let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) {
            ToolState::TestPass
        } else {
            ToolState::TestFail
        };
1782
        builder.save_toolstate("rustc-dev-guide", toolstate);
1783 1784 1785
    }
}

1786
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
M
Mark Simulacrum 已提交
1787
pub struct CrateLibrustc {
1788
    compiler: Compiler,
1789
    target: TargetSelection,
1790
    test_kind: TestKind,
1791
    krate: Interned<String>,
1792 1793
}

M
Mark Simulacrum 已提交
1794
impl Step for CrateLibrustc {
1795 1796 1797 1798
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
1799
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1800
        run.krate("rustc-main")
1801 1802
    }

T
Taiki Endo 已提交
1803
    fn make_run(run: RunConfig<'_>) {
1804
        let builder = run.builder;
1805
        let compiler = builder.compiler(builder.top_stage, run.build_triple());
1806

1807
        for krate in builder.in_tree_crates("rustc-main", Some(run.target)) {
E
Eric Huss 已提交
1808
            if krate.path.ends_with(&run.path) {
1809
                let test_kind = builder.kind.into();
1810

1811 1812 1813 1814 1815 1816
                builder.ensure(CrateLibrustc {
                    compiler,
                    target: run.target,
                    test_kind,
                    krate: krate.name,
                });
1817 1818 1819 1820
            }
        }
    }

T
Taiki Endo 已提交
1821
    fn run(self, builder: &Builder<'_>) {
M
Mark Simulacrum 已提交
1822
        builder.ensure(Crate {
1823 1824
            compiler: self.compiler,
            target: self.target,
C
Collins Abitekaniza 已提交
1825
            mode: Mode::Rustc,
1826 1827 1828 1829 1830 1831
            test_kind: self.test_kind,
            krate: self.krate,
        });
    }
}

K
kennytm 已提交
1832
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
M
Mark Simulacrum 已提交
1833
pub struct Crate {
K
kennytm 已提交
1834
    pub compiler: Compiler,
1835
    pub target: TargetSelection,
K
kennytm 已提交
1836 1837 1838
    pub mode: Mode,
    pub test_kind: TestKind,
    pub krate: Interned<String>,
1839
}
1840

M
Mark Simulacrum 已提交
1841
impl Step for Crate {
1842
    type Output = ();
1843 1844
    const DEFAULT: bool = true;

1845 1846
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
        run.krate("test")
1847 1848
    }

T
Taiki Endo 已提交
1849
    fn make_run(run: RunConfig<'_>) {
1850
        let builder = run.builder;
1851
        let compiler = builder.compiler(builder.top_stage, run.build_triple());
1852

1853
        let make = |mode: Mode, krate: &CargoCrate| {
1854
            let test_kind = builder.kind.into();
1855

M
Mark Simulacrum 已提交
1856
            builder.ensure(Crate {
1857 1858
                compiler,
                target: run.target,
1859 1860
                mode,
                test_kind,
1861
                krate: krate.name,
1862 1863 1864
            });
        };

1865
        for krate in builder.in_tree_crates("test", Some(run.target)) {
E
Eric Huss 已提交
1866
            if krate.path.ends_with(&run.path) {
1867
                make(Mode::Std, krate);
1868 1869 1870
            }
        }
    }
1871

A
Alexander Regueiro 已提交
1872
    /// Runs all unit tests plus documentation tests for a given crate defined
1873
    /// by a `Cargo.toml` (single manifest)
1874 1875 1876 1877 1878 1879
    ///
    /// This is what runs tests for crates like the standard library, compiler, etc.
    /// It essentially is the driver for running `cargo test`.
    ///
    /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
    /// arguments, and those arguments are discovered from `cargo metadata`.
T
Taiki Endo 已提交
1880
    fn run(self, builder: &Builder<'_>) {
1881 1882 1883 1884 1885 1886
        let compiler = self.compiler;
        let target = self.target;
        let mode = self.mode;
        let test_kind = self.test_kind;
        let krate = self.krate;

1887
        builder.ensure(compile::Std { compiler, target });
1888
        builder.ensure(RemoteCopyLibs { compiler, target });
A
Alex Crichton 已提交
1889

1890 1891 1892 1893 1894
        // If we're not doing a full bootstrap but we're testing a stage2
        // version of libstd, then what we're actually testing is the libstd
        // produced in stage1. Reflect that here by updating the compiler that
        // we're working with automatically.
        let compiler = builder.compiler_for(compiler.stage, compiler.host, target);
A
Alex Crichton 已提交
1895

1896 1897
        let mut cargo =
            builder.cargo(compiler, mode, SourceType::InTree, target, test_kind.subcommand());
1898
        match mode {
C
Collins Abitekaniza 已提交
1899
            Mode::Std => {
1900
                compile::std_cargo(builder, target, compiler.stage, &mut cargo);
1901
            }
C
Collins Abitekaniza 已提交
1902
            Mode::Rustc => {
1903
                builder.ensure(compile::Rustc { compiler, target });
1904
                compile::rustc_cargo(builder, &mut cargo, target);
1905 1906 1907 1908 1909 1910 1911 1912 1913
            }
            _ => panic!("can only test libraries"),
        };

        // Build up the base `cargo test` command.
        //
        // Pass in some standard flags then iterate over the graph we've discovered
        // in `cargo metadata` with the maps above and figure out what `-p`
        // arguments need to get passed.
1914
        if test_kind.subcommand() == "test" && !builder.fail_fast {
1915 1916
            cargo.arg("--no-fail-fast");
        }
K
kennytm 已提交
1917
        match builder.doc_tests {
K
kennytm 已提交
1918
            DocTests::Only => {
K
kennytm 已提交
1919 1920
                cargo.arg("--doc");
            }
K
kennytm 已提交
1921
            DocTests::No => {
K
kennytm 已提交
1922 1923
                cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
            }
K
kennytm 已提交
1924
            DocTests::Yes => {}
1925
        }
1926

1927
        cargo.arg("-p").arg(krate);
1928

1929 1930 1931 1932 1933 1934
        // The tests are going to run with the *target* libraries, so we need to
        // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
        //
        // Note that to run the compiler we need to run with the *host* libraries,
        // but our wrapper scripts arrange for that to be the case anyway.
        let mut dylib_path = dylib_path();
1935
        dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1936 1937 1938
        cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());

        cargo.arg("--");
1939
        cargo.args(&builder.config.cmd.test_args());
1940

O
Oliver Schneider 已提交
1941
        if !builder.config.verbose_tests {
1942 1943
            cargo.arg("--quiet");
        }
1944

1945
        if target.contains("emscripten") {
S
Santiago Pastorino 已提交
1946
            cargo.env(
1947
                format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
M
Mark Rousskov 已提交
1948
                builder.config.nodejs.as_ref().expect("nodejs not configured"),
S
Santiago Pastorino 已提交
1949
            );
O
Oliver Schneider 已提交
1950
        } else if target.starts_with("wasm32") {
M
Mark Rousskov 已提交
1951 1952 1953
            let node = builder.config.nodejs.as_ref().expect("nodejs not configured");
            let runner =
                format!("{} {}/src/etc/wasm32-shim.js", node.display(), builder.src.display());
1954
            cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), &runner);
1955
        } else if builder.remote_tested(target) {
S
Santiago Pastorino 已提交
1956
            cargo.env(
1957
                format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
1958
                format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
S
Santiago Pastorino 已提交
1959
            );
1960
        }
1961

S
Santiago Pastorino 已提交
1962 1963 1964 1965
        builder.info(&format!(
            "{} {} stage{} ({} -> {})",
            test_kind, krate, compiler.stage, &compiler.host, target
        ));
1966
        let _time = util::timeit(&builder);
1967
        try_run(builder, &mut cargo.into());
1968 1969
    }
}
1970

M
Mark Simulacrum 已提交
1971
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1972
pub struct CrateRustdoc {
1973
    host: TargetSelection,
M
Mark Simulacrum 已提交
1974 1975 1976
    test_kind: TestKind,
}

1977
impl Step for CrateRustdoc {
M
Mark Simulacrum 已提交
1978 1979 1980 1981
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
1982
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1983
        run.paths(&["src/librustdoc", "src/tools/rustdoc"])
M
Mark Simulacrum 已提交
1984 1985
    }

T
Taiki Endo 已提交
1986
    fn make_run(run: RunConfig<'_>) {
M
Mark Simulacrum 已提交
1987 1988
        let builder = run.builder;

1989
        let test_kind = builder.kind.into();
M
Mark Simulacrum 已提交
1990

1991
        builder.ensure(CrateRustdoc { host: run.target, test_kind });
M
Mark Simulacrum 已提交
1992 1993
    }

T
Taiki Endo 已提交
1994
    fn run(self, builder: &Builder<'_>) {
M
Mark Simulacrum 已提交
1995
        let test_kind = self.test_kind;
E
Eric Huss 已提交
1996
        let target = self.host;
M
Mark Simulacrum 已提交
1997

E
Eric Huss 已提交
1998 1999 2000 2001 2002
        // Use the previous stage compiler to reuse the artifacts that are
        // created when running compiletest for src/test/rustdoc. If this used
        // `compiler`, then it would cause rustdoc to be built *again*, which
        // isn't really necessary.
        let compiler = builder.compiler_for(builder.top_stage, target, target);
2003
        builder.ensure(compile::Rustc { compiler, target });
M
Mark Simulacrum 已提交
2004

M
Mark Rousskov 已提交
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
        let mut cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
            Mode::ToolRustc,
            target,
            test_kind.subcommand(),
            "src/tools/rustdoc",
            SourceType::InTree,
            &[],
        );
2015
        if test_kind.subcommand() == "test" && !builder.fail_fast {
M
Mark Simulacrum 已提交
2016 2017 2018 2019 2020 2021
            cargo.arg("--no-fail-fast");
        }

        cargo.arg("-p").arg("rustdoc:0.0.0");

        cargo.arg("--");
2022
        cargo.args(&builder.config.cmd.test_args());
M
Mark Simulacrum 已提交
2023

2024 2025 2026 2027
        if self.host.contains("musl") {
            cargo.arg("'-Ctarget-feature=-crt-static'");
        }

E
Eric Huss 已提交
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
        // This is needed for running doctests on librustdoc. This is a bit of
        // an unfortunate interaction with how bootstrap works and how cargo
        // sets up the dylib path, and the fact that the doctest (in
        // html/markdown.rs) links to rustc-private libs. For stage1, the
        // compiler host dylibs (in stage1/lib) are not the same as the target
        // dylibs (in stage1/lib/rustlib/...). This is different from a normal
        // rust distribution where they are the same.
        //
        // On the cargo side, normal tests use `target_process` which handles
        // setting up the dylib for a *target* (stage1/lib/rustlib/... in this
        // case). However, for doctests it uses `rustdoc_process` which only
        // sets up the dylib path for the *host* (stage1/lib), which is the
        // wrong directory.
        //
        // It should be considered to just stop running doctests on
        // librustdoc. There is only one test, and it doesn't look too
        // important. There might be other ways to avoid this, but it seems
        // pretty convoluted.
        //
        // See also https://github.com/rust-lang/rust/issues/13983 where the
        // host vs target dylibs for rustdoc are consistently tricky to deal
        // with.
        let mut dylib_path = dylib_path();
        dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
        cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());

O
Oliver Schneider 已提交
2054
        if !builder.config.verbose_tests {
M
Mark Simulacrum 已提交
2055 2056 2057
            cargo.arg("--quiet");
        }

S
Santiago Pastorino 已提交
2058 2059 2060 2061
        builder.info(&format!(
            "{} rustdoc stage{} ({} -> {})",
            test_kind, compiler.stage, &compiler.host, target
        ));
2062
        let _time = util::timeit(&builder);
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133

        try_run(builder, &mut cargo.into());
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct CrateRustdocJsonTypes {
    host: TargetSelection,
    test_kind: TestKind,
}

impl Step for CrateRustdocJsonTypes {
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
        run.path("src/rustdoc-json-types")
    }

    fn make_run(run: RunConfig<'_>) {
        let builder = run.builder;

        let test_kind = builder.kind.into();

        builder.ensure(CrateRustdocJsonTypes { host: run.target, test_kind });
    }

    fn run(self, builder: &Builder<'_>) {
        let test_kind = self.test_kind;
        let target = self.host;

        // Use the previous stage compiler to reuse the artifacts that are
        // created when running compiletest for src/test/rustdoc. If this used
        // `compiler`, then it would cause rustdoc to be built *again*, which
        // isn't really necessary.
        let compiler = builder.compiler_for(builder.top_stage, target, target);
        builder.ensure(compile::Rustc { compiler, target });

        let mut cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
            Mode::ToolRustc,
            target,
            test_kind.subcommand(),
            "src/rustdoc-json-types",
            SourceType::InTree,
            &[],
        );
        if test_kind.subcommand() == "test" && !builder.fail_fast {
            cargo.arg("--no-fail-fast");
        }

        cargo.arg("-p").arg("rustdoc-json-types");

        cargo.arg("--");
        cargo.args(&builder.config.cmd.test_args());

        if self.host.contains("musl") {
            cargo.arg("'-Ctarget-feature=-crt-static'");
        }

        if !builder.config.verbose_tests {
            cargo.arg("--quiet");
        }

        builder.info(&format!(
            "{} rustdoc-json-types stage{} ({} -> {})",
            test_kind, compiler.stage, &compiler.host, target
        ));
        let _time = util::timeit(&builder);
M
Mark Simulacrum 已提交
2134

2135
        try_run(builder, &mut cargo.into());
M
Mark Simulacrum 已提交
2136 2137 2138
    }
}

2139 2140 2141 2142 2143
/// Some test suites are run inside emulators or on remote devices, and most
/// of our test binaries are linked dynamically which means we need to ship
/// the standard library and such to the emulator ahead of time. This step
/// represents this and is a dependency of all test suites.
///
A
Alexander Regueiro 已提交
2144
/// Most of the time this is a no-op. For some steps such as shipping data to
2145 2146 2147
/// QEMU we have to build our own tools so we've got conditional dependencies
/// on those programs as well. Note that the remote test client is built for
/// the build target (us) and the server is built for the target.
2148 2149 2150
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct RemoteCopyLibs {
    compiler: Compiler,
2151
    target: TargetSelection,
2152
}
2153

2154
impl Step for RemoteCopyLibs {
2155
    type Output = ();
2156

T
Taiki Endo 已提交
2157
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2158
        run.never()
2159 2160
    }

T
Taiki Endo 已提交
2161
    fn run(self, builder: &Builder<'_>) {
2162 2163
        let compiler = self.compiler;
        let target = self.target;
2164
        if !builder.remote_tested(target) {
S
Santiago Pastorino 已提交
2165
            return;
2166 2167
        }

2168
        builder.ensure(compile::Std { compiler, target });
2169

2170 2171
        builder.info(&format!("REMOTE copy libs to emulator ({})", target));
        t!(fs::create_dir_all(builder.out.join("tmp")));
2172

2173
        let server = builder.ensure(tool::RemoteTestServer { compiler, target });
2174 2175

        // Spawn the emulator and wait for it to come online
2176
        let tool = builder.tool_exe(Tool::RemoteTestClient);
2177
        let mut cmd = Command::new(&tool);
2178
        cmd.arg("spawn-emulator").arg(target.triple).arg(&server).arg(builder.out.join("tmp"));
2179
        if let Some(rootfs) = builder.qemu_rootfs(target) {
2180 2181
            cmd.arg(rootfs);
        }
2182
        builder.run(&mut cmd);
2183 2184

        // Push all our dylibs to the emulator
2185
        for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
2186 2187 2188
            let f = t!(f);
            let name = f.file_name().into_string().unwrap();
            if util::is_dylib(&name) {
S
Santiago Pastorino 已提交
2189
                builder.run(Command::new(&tool).arg("push").arg(f.path()));
2190
            }
2191 2192 2193 2194
        }
    }
}

2195
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2196
pub struct Distcheck;
A
Alex Crichton 已提交
2197

2198
impl Step for Distcheck {
2199 2200
    type Output = ();

T
Taiki Endo 已提交
2201
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2202
        run.path("distcheck")
2203 2204
    }

T
Taiki Endo 已提交
2205
    fn make_run(run: RunConfig<'_>) {
M
Mark Simulacrum 已提交
2206 2207 2208
        run.builder.ensure(Distcheck);
    }

A
Alexander Regueiro 已提交
2209
    /// Runs "distcheck", a 'make check' from a tarball
T
Taiki Endo 已提交
2210
    fn run(self, builder: &Builder<'_>) {
2211
        builder.info("Distcheck");
2212
        let dir = builder.out.join("tmp").join("distcheck");
2213 2214 2215
        let _ = fs::remove_dir_all(&dir);
        t!(fs::create_dir_all(&dir));

M
Mark Simulacrum 已提交
2216 2217 2218 2219
        // Guarantee that these are built before we begin running.
        builder.ensure(dist::PlainSourceTarball);
        builder.ensure(dist::Src);

2220
        let mut cmd = Command::new("tar");
2221
        cmd.arg("-xf")
2222
            .arg(builder.ensure(dist::PlainSourceTarball).tarball())
S
Santiago Pastorino 已提交
2223 2224
            .arg("--strip-components=1")
            .current_dir(&dir);
2225
        builder.run(&mut cmd);
S
Santiago Pastorino 已提交
2226 2227 2228 2229 2230 2231 2232
        builder.run(
            Command::new("./configure")
                .args(&builder.config.configure_args)
                .arg("--enable-vendor")
                .current_dir(&dir),
        );
        builder.run(
2233 2234 2235
            Command::new(build_helper::make(&builder.config.build.triple))
                .arg("check")
                .current_dir(&dir),
S
Santiago Pastorino 已提交
2236
        );
2237 2238

        // Now make sure that rust-src has all of libstd's dependencies
2239
        builder.info("Distcheck rust-src");
2240
        let dir = builder.out.join("tmp").join("distcheck-src");
2241 2242 2243 2244
        let _ = fs::remove_dir_all(&dir);
        t!(fs::create_dir_all(&dir));

        let mut cmd = Command::new("tar");
2245 2246 2247 2248
        cmd.arg("-xf")
            .arg(builder.ensure(dist::Src).tarball())
            .arg("--strip-components=1")
            .current_dir(&dir);
2249
        builder.run(&mut cmd);
2250

M
mark 已提交
2251
        let toml = dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
S
Santiago Pastorino 已提交
2252 2253 2254 2255 2256 2257 2258
        builder.run(
            Command::new(&builder.initial_cargo)
                .arg("generate-lockfile")
                .arg("--manifest-path")
                .arg(&toml)
                .current_dir(&dir),
        );
2259
    }
A
Alex Crichton 已提交
2260
}
2261

2262
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2263 2264
pub struct Bootstrap;

2265
impl Step for Bootstrap {
2266
    type Output = ();
2267 2268
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;
2269

A
Alexander Regueiro 已提交
2270
    /// Tests the build system itself.
T
Taiki Endo 已提交
2271
    fn run(self, builder: &Builder<'_>) {
2272
        let mut cmd = Command::new(&builder.initial_cargo);
2273
        cmd.arg("test")
S
Santiago Pastorino 已提交
2274 2275 2276
            .current_dir(builder.src.join("src/bootstrap"))
            .env("RUSTFLAGS", "-Cdebuginfo=2")
            .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
2277 2278
            .env("BOOTSTRAP_OUTPUT_DIRECTORY", &builder.config.out)
            .env("BOOTSTRAP_INITIAL_CARGO", &builder.config.initial_cargo)
S
Santiago Pastorino 已提交
2279 2280
            .env("RUSTC_BOOTSTRAP", "1")
            .env("RUSTC", &builder.initial_rustc);
2281 2282 2283 2284 2285 2286
        if let Some(flags) = option_env!("RUSTFLAGS") {
            // Use the same rustc flags for testing as for "normal" compilation,
            // so that Cargo doesn’t recompile the entire dependency graph every time:
            // https://github.com/rust-lang/rust/issues/49215
            cmd.env("RUSTFLAGS", flags);
        }
2287
        if !builder.fail_fast {
2288 2289
            cmd.arg("--no-fail-fast");
        }
2290
        cmd.arg("--").args(&builder.config.cmd.test_args());
2291 2292 2293
        // rustbuild tests are racy on directory creation so just run them one at a time.
        // Since there's not many this shouldn't be a problem.
        cmd.arg("--test-threads=1");
2294
        try_run(builder, &mut cmd);
2295
    }
2296

T
Taiki Endo 已提交
2297
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2298
        run.path("src/bootstrap")
2299 2300
    }

T
Taiki Endo 已提交
2301
    fn make_run(run: RunConfig<'_>) {
2302
        run.builder.ensure(Bootstrap);
2303
    }
2304
}
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct TierCheck {
    pub compiler: Compiler,
}

impl Step for TierCheck {
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

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

    fn make_run(run: RunConfig<'_>) {
2321 2322 2323
        let compiler =
            run.builder.compiler_for(run.builder.top_stage, run.builder.build.build, run.target);
        run.builder.ensure(TierCheck { compiler });
2324 2325 2326 2327
    }

    /// Tests the Platform Support page in the rustc book.
    fn run(self, builder: &Builder<'_>) {
2328
        builder.ensure(compile::Std { compiler: self.compiler, target: self.compiler.host });
2329 2330 2331
        let mut cargo = tool::prepare_tool_cargo(
            builder,
            self.compiler,
2332 2333
            Mode::ToolStd,
            self.compiler.host,
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
            "run",
            "src/tools/tier-check",
            SourceType::InTree,
            &[],
        );
        cargo.arg(builder.src.join("src/doc/rustc/src/platform-support.md"));
        cargo.arg(&builder.rustc(self.compiler));
        if builder.is_verbose() {
            cargo.arg("--verbose");
        }

        builder.info("platform support check");
        try_run(builder, &mut cargo.into());
    }
}
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct LintDocs {
    pub compiler: Compiler,
    pub target: TargetSelection,
}

impl Step for LintDocs {
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

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

    fn make_run(run: RunConfig<'_>) {
        run.builder.ensure(LintDocs {
            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
            target: run.target,
        });
    }

    /// Tests that the lint examples in the rustc book generate the correct
    /// lints and have the expected format.
    fn run(self, builder: &Builder<'_>) {
        builder.ensure(crate::doc::RustcBook {
            compiler: self.compiler,
            target: self.target,
            validate: true,
        });
    }
}