test.rs 72.1 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

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

114
        builder.default_doc(&[]);
115

M
mark 已提交
116 117 118 119 120
        let _time = util::timeit(&builder);
        try_run(
            builder,
            builder.tool_cmd(Tool::Linkchecker).arg(builder.out.join(host.triple).join("doc")),
        );
121
    }
122

T
Taiki Endo 已提交
123
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
124
        let builder = run.builder;
M
Mark Rousskov 已提交
125
        run.path("src/tools/linkchecker").default_condition(builder.config.docs)
126 127
    }

T
Taiki Endo 已提交
128
    fn make_run(run: RunConfig<'_>) {
129
        run.builder.ensure(Linkcheck { host: run.target });
130
    }
131
}
132

133 134
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Cargotest {
135
    stage: u32,
136
    host: TargetSelection,
137
}
138

139
impl Step for Cargotest {
140
    type Output = ();
141
    const ONLY_HOSTS: bool = true;
142

T
Taiki Endo 已提交
143
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
144
        run.path("src/tools/cargotest")
145 146
    }

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

151 152 153 154
    /// 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 已提交
155
    fn run(self, builder: &Builder<'_>) {
156
        let compiler = builder.compiler(self.stage, self.host);
M
Mark Rousskov 已提交
157
        builder.ensure(compile::Rustc { compiler, target: compiler.host });
E
Eric Huss 已提交
158
        let cargo = builder.ensure(tool::Cargo { compiler, target: compiler.host });
159 160 161 162

        // 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.
163
        let out_dir = builder.out.join("ct");
164 165
        t!(fs::create_dir_all(&out_dir));

166
        let _time = util::timeit(&builder);
167
        let mut cmd = builder.tool_cmd(Tool::CargoTest);
S
Santiago Pastorino 已提交
168 169
        try_run(
            builder,
E
Eric Huss 已提交
170
            cmd.arg(&cargo)
S
Santiago Pastorino 已提交
171 172
                .arg(&out_dir)
                .env("RUSTC", builder.rustc(compiler))
M
Mark Rousskov 已提交
173
                .env("RUSTDOC", builder.rustdoc(compiler)),
S
Santiago Pastorino 已提交
174
        );
175
    }
176 177
}

178 179
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Cargo {
180
    stage: u32,
181
    host: TargetSelection,
182 183
}

184
impl Step for Cargo {
185
    type Output = ();
186 187
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
188
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
189
        run.path("src/tools/cargo")
190 191
    }

T
Taiki Endo 已提交
192
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
193
        run.builder.ensure(Cargo { stage: run.builder.top_stage, host: run.target });
194
    }
195 196

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

M
Mark Rousskov 已提交
200 201 202
        builder.ensure(tool::Cargo { compiler, target: self.host });
        let mut cargo = tool::prepare_tool_cargo(
            builder,
S
Santiago Pastorino 已提交
203
            compiler,
M
Mark Rousskov 已提交
204 205 206 207 208 209 210
            Mode::ToolRustc,
            self.host,
            "test",
            "src/tools/cargo",
            SourceType::Submodule,
            &[],
        );
211

212
        if !builder.fail_fast {
213 214
            cargo.arg("--no-fail-fast");
        }
215
        cargo.arg("--").args(builder.config.cmd.test_args());
216

217 218 219
        // Don't run cross-compile tests, we may not have cross-compiled libstd libs
        // available.
        cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
220 221
        // Disable a test that has issues with mingw.
        cargo.env("CARGO_TEST_DISABLE_GIT_CLI", "1");
222 223 224
        // 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");
225

226 227
        cargo.env("PATH", &path_for_cargo(builder, compiler));

228
        try_run(builder, &mut cargo.into());
229
    }
N
Nick Cameron 已提交
230 231
}

M
Mark Simulacrum 已提交
232 233
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Rls {
234
    stage: u32,
235
    host: TargetSelection,
236
}
N
Nick Cameron 已提交
237

M
Mark Simulacrum 已提交
238
impl Step for Rls {
239
    type Output = ();
M
Mark Simulacrum 已提交
240 241
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
242
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
243
        run.path("src/tools/rls")
M
Mark Simulacrum 已提交
244 245
    }

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

250
    /// Runs `cargo test` for the rls.
T
Taiki Endo 已提交
251
    fn run(self, builder: &Builder<'_>) {
252 253
        let stage = self.stage;
        let host = self.host;
M
Mark Simulacrum 已提交
254
        let compiler = builder.compiler(stage, host);
N
Nick Cameron 已提交
255

M
Mark Rousskov 已提交
256 257
        let build_result =
            builder.ensure(tool::Rls { compiler, target: self.host, extra_features: Vec::new() });
258 259 260 261 262
        if build_result.is_none() {
            eprintln!("failed to test rls: could not build");
            return;
        }

M
Mark Rousskov 已提交
263 264 265 266 267 268 269 270 271 272
        let mut cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
            Mode::ToolRustc,
            host,
            "test",
            "src/tools/rls",
            SourceType::Submodule,
            &[],
        );
N
Nick Cameron 已提交
273

274
        cargo.add_rustc_lib_path(builder, compiler);
M
Mark Rousskov 已提交
275
        cargo.arg("--").args(builder.config.cmd.test_args());
276

277
        if try_run(builder, &mut cargo.into()) {
278
            builder.save_toolstate("rls", ToolState::TestPass);
O
Oliver Schneider 已提交
279
        }
280
    }
N
Nick Cameron 已提交
281 282
}

N
Nick Cameron 已提交
283 284 285
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Rustfmt {
    stage: u32,
286
    host: TargetSelection,
N
Nick Cameron 已提交
287 288 289 290 291 292
}

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

T
Taiki Endo 已提交
293
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
N
Nick Cameron 已提交
294 295 296
        run.path("src/tools/rustfmt")
    }

T
Taiki Endo 已提交
297
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
298
        run.builder.ensure(Rustfmt { stage: run.builder.top_stage, host: run.target });
N
Nick Cameron 已提交
299 300 301
    }

    /// Runs `cargo test` for rustfmt.
T
Taiki Endo 已提交
302
    fn run(self, builder: &Builder<'_>) {
N
Nick Cameron 已提交
303 304 305 306
        let stage = self.stage;
        let host = self.host;
        let compiler = builder.compiler(stage, host);

307 308 309 310 311 312 313 314 315 316
        let build_result = builder.ensure(tool::Rustfmt {
            compiler,
            target: self.host,
            extra_features: Vec::new(),
        });
        if build_result.is_none() {
            eprintln!("failed to test rustfmt: could not build");
            return;
        }

M
Mark Rousskov 已提交
317 318 319 320 321 322 323 324 325 326
        let mut cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
            Mode::ToolRustc,
            host,
            "test",
            "src/tools/rustfmt",
            SourceType::Submodule,
            &[],
        );
N
Nick Cameron 已提交
327

N
Nick Cameron 已提交
328 329 330
        let dir = testdir(builder, compiler.host);
        t!(fs::create_dir_all(&dir));
        cargo.env("RUSTFMT_TEST_DIR", dir);
N
Nick Cameron 已提交
331

332
        cargo.add_rustc_lib_path(builder, compiler);
N
Nick Cameron 已提交
333

334
        if try_run(builder, &mut cargo.into()) {
335
            builder.save_toolstate("rustfmt", ToolState::TestPass);
O
Oliver Schneider 已提交
336
        }
N
Nick Cameron 已提交
337 338
    }
}
O
Oliver Schneider 已提交
339 340

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
341
pub struct Miri {
O
Oliver Schneider 已提交
342
    stage: u32,
343
    host: TargetSelection,
344 345 346 347 348 349
}

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

T
Taiki Endo 已提交
350
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
R
Ralf Jung 已提交
351
        run.path("src/tools/miri")
352 353
    }

T
Taiki Endo 已提交
354
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
355
        run.builder.ensure(Miri { stage: run.builder.top_stage, host: run.target });
356 357 358
    }

    /// Runs `cargo test` for miri.
T
Taiki Endo 已提交
359
    fn run(self, builder: &Builder<'_>) {
O
Oliver Schneider 已提交
360
        let stage = self.stage;
361
        let host = self.host;
O
Oliver Schneider 已提交
362
        let compiler = builder.compiler(stage, host);
363

M
Mark Rousskov 已提交
364 365
        let miri =
            builder.ensure(tool::Miri { compiler, target: self.host, extra_features: Vec::new() });
366 367 368 369 370 371
        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) {
372 373
            let mut cargo =
                builder.cargo(compiler, Mode::ToolRustc, SourceType::Submodule, host, "install");
374 375 376 377 378 379 380 381 382
            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;
            }

383 384 385 386 387 388 389
            // # Run `cargo miri setup`.
            let mut cargo = tool::prepare_tool_cargo(
                builder,
                compiler,
                Mode::ToolRustc,
                host,
                "run",
390
                "src/tools/miri/cargo-miri",
391 392 393
                SourceType::Submodule,
                &[],
            );
394
            cargo.arg("--").arg("miri").arg("setup");
395 396

            // Tell `cargo miri setup` where to find the sources.
R
Ralf Jung 已提交
397
            cargo.env("XARGO_RUST_SRC", builder.src.join("library"));
398 399
            // Tell it where to find Miri.
            cargo.env("MIRI", &miri);
400 401
            // Debug things.
            cargo.env("RUST_BACKTRACE", "1");
402
            // Let cargo-miri know where xargo ended up.
403
            cargo.env("XARGO_CHECK", builder.out.join("bin").join("xargo-check"));
404

405
            let mut cargo = Command::from(cargo);
406 407 408 409 410
            if !try_run(builder, &mut cargo) {
                return;
            }

            // # Determine where Miri put its sysroot.
R
Ralf Jung 已提交
411
            // To this end, we run `cargo miri setup --print-sysroot` and capture the output.
412 413 414
            // (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 已提交
415
            cargo.arg("--print-sysroot");
416 417 418 419 420

            // 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 {
421
                builder.verbose(&format!("running: {:?}", cargo));
M
Mark Rousskov 已提交
422 423
                let out = cargo
                    .output()
424 425
                    .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 已提交
426
                // Output is "<sysroot>\n".
427 428
                let stdout = String::from_utf8(out.stdout)
                    .expect("`cargo miri setup` stdout is not valid UTF-8");
R
Ralf Jung 已提交
429 430
                let sysroot = stdout.trim_end();
                builder.verbose(&format!("`cargo miri setup --print-sysroot` said: {:?}", sysroot));
431 432 433 434 435 436 437 438 439 440 441 442 443 444
                sysroot.to_owned()
            };

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

            // miri tests need to know about the stage sysroot
447
            cargo.env("MIRI_SYSROOT", miri_sysroot);
O
Oliver Schneider 已提交
448
            cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
449
            cargo.env("MIRI", miri);
O
Oliver Schneider 已提交
450

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

453
            cargo.add_rustc_lib_path(builder, compiler);
O
Oliver Schneider 已提交
454

455
            if !try_run(builder, &mut cargo.into()) {
456
                return;
O
Oliver Schneider 已提交
457
            }
458 459 460

            // # Done!
            builder.save_toolstate("miri", ToolState::TestPass);
O
Oliver Schneider 已提交
461 462 463
        } else {
            eprintln!("failed to test miri: could not build");
        }
464 465 466
    }
}

467 468
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct CompiletestTest {
469
    host: TargetSelection,
470 471 472 473 474
}

impl Step for CompiletestTest {
    type Output = ();

T
Taiki Endo 已提交
475
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
476 477 478
        run.path("src/tools/compiletest")
    }

T
Taiki Endo 已提交
479
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
480
        run.builder.ensure(CompiletestTest { host: run.target });
481 482 483
    }

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

488 489 490
        // 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 已提交
491 492 493
        let cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
494
            Mode::ToolStd,
M
Mark Rousskov 已提交
495 496 497 498 499 500
            host,
            "test",
            "src/tools/compiletest",
            SourceType::InTree,
            &[],
        );
501

502
        try_run(builder, &mut cargo.into());
503 504 505
    }
}

506 507
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Clippy {
O
Oliver Schneider 已提交
508
    stage: u32,
509
    host: TargetSelection,
510 511 512 513 514 515 516
}

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

T
Taiki Endo 已提交
517
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
518 519 520
        run.path("src/tools/clippy")
    }

T
Taiki Endo 已提交
521
    fn make_run(run: RunConfig<'_>) {
M
Mark Rousskov 已提交
522
        run.builder.ensure(Clippy { stage: run.builder.top_stage, host: run.target });
523 524 525
    }

    /// Runs `cargo test` for clippy.
T
Taiki Endo 已提交
526
    fn run(self, builder: &Builder<'_>) {
O
Oliver Schneider 已提交
527
        let stage = self.stage;
528
        let host = self.host;
O
Oliver Schneider 已提交
529
        let compiler = builder.compiler(stage, host);
530

M
Mark Rousskov 已提交
531 532 533 534 535
        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,
536
            compiler,
M
Mark Rousskov 已提交
537 538 539 540 541 542 543
            Mode::ToolRustc,
            host,
            "test",
            "src/tools/clippy",
            SourceType::InTree,
            &[],
        );
O
Oliver Schneider 已提交
544

M
Mark Rousskov 已提交
545 546 547 548 549
        // 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());
550 551 552 553
        let target_libs = builder
            .stage_out(compiler, Mode::ToolRustc)
            .join(&self.host.triple)
            .join(builder.cargo_dir());
M
Mark Rousskov 已提交
554 555 556 557
        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 已提交
558

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

561
        cargo.add_rustc_lib_path(builder, compiler);
O
Oliver Schneider 已提交
562

A
Aaron Hill 已提交
563
        builder.run(&mut cargo.into());
564 565
    }
}
N
Nick Cameron 已提交
566

567 568 569 570 571 572 573 574
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("")
}
575

G
Guillaume Gomez 已提交
576 577 578 579 580 581 582 583 584 585
#[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 已提交
586
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
G
Guillaume Gomez 已提交
587 588 589
        run.path("src/tools/rustdoc-themes")
    }

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

593
        run.builder.ensure(RustdocTheme { compiler });
G
Guillaume Gomez 已提交
594 595
    }

T
Taiki Endo 已提交
596
    fn run(self, builder: &Builder<'_>) {
597
        let rustdoc = builder.out.join("bootstrap/debug/rustdoc");
G
Guillaume Gomez 已提交
598 599
        let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
        cmd.arg(rustdoc.to_str().unwrap())
M
Mark Rousskov 已提交
600
            .arg(builder.src.join("src/librustdoc/html/static/themes").to_str().unwrap())
S
Santiago Pastorino 已提交
601 602
            .env("RUSTC_STAGE", self.compiler.stage.to_string())
            .env("RUSTC_SYSROOT", builder.sysroot(self.compiler))
M
Mark Rousskov 已提交
603
            .env("RUSTDOC_LIBDIR", builder.sysroot_libdir(self.compiler, self.compiler.host))
S
Santiago Pastorino 已提交
604
            .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
M
Mark Rousskov 已提交
605
            .env("RUSTDOC_REAL", builder.rustdoc(self.compiler))
S
Santiago Pastorino 已提交
606
            .env("RUSTC_BOOTSTRAP", "1");
607
        if let Some(linker) = builder.linker(self.compiler.host) {
608 609
            cmd.env("RUSTDOC_LINKER", linker);
        }
610
        if builder.is_fuse_ld_lld(self.compiler.host) {
611
            cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
G
Guillaume Gomez 已提交
612
        }
613
        try_run(builder, &mut cmd);
G
Guillaume Gomez 已提交
614 615 616
    }
}

G
Guillaume Gomez 已提交
617
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
G
Guillaume Gomez 已提交
618
pub struct RustdocJSStd {
619
    pub target: TargetSelection,
G
Guillaume Gomez 已提交
620 621
}

G
Guillaume Gomez 已提交
622
impl Step for RustdocJSStd {
623
    type Output = ();
G
Guillaume Gomez 已提交
624 625 626
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

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

T
Taiki Endo 已提交
631
    fn make_run(run: RunConfig<'_>) {
632
        run.builder.ensure(RustdocJSStd { target: run.target });
G
Guillaume Gomez 已提交
633 634
    }

T
Taiki Endo 已提交
635
    fn run(self, builder: &Builder<'_>) {
636 637
        if let Some(ref nodejs) = builder.config.nodejs {
            let mut command = Command::new(nodejs);
638
            command
639
                .arg(builder.src.join("src/tools/rustdoc-js/tester.js"))
640 641 642
                .arg("--crate-name")
                .arg("std")
                .arg("--resource-suffix")
643
                .arg(&builder.version)
644
                .arg("--doc-folder")
645
                .arg(builder.doc_out(self.target))
646
                .arg("--test-folder")
647
                .arg(builder.src.join("src/test/rustdoc-js-std"));
M
Mark Rousskov 已提交
648
            builder.ensure(crate::doc::Std { target: self.target, stage: builder.top_stage });
649 650
            builder.run(&mut command);
        } else {
M
Mark Rousskov 已提交
651
            builder.info("No nodejs found, skipping \"src/test/rustdoc-js-std\" tests");
652
        }
G
Guillaume Gomez 已提交
653 654 655
    }
}

G
Guillaume Gomez 已提交
656 657
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RustdocJSNotStd {
658
    pub target: TargetSelection,
G
Guillaume Gomez 已提交
659 660 661 662 663 664 665 666
    pub compiler: Compiler,
}

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

G
Guillaume Gomez 已提交
667
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
G
Guillaume Gomez 已提交
668
        run.path("src/test/rustdoc-js")
G
Guillaume Gomez 已提交
669 670
    }

G
Guillaume Gomez 已提交
671
    fn make_run(run: RunConfig<'_>) {
672 673
        let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
        run.builder.ensure(RustdocJSNotStd { target: run.target, compiler });
G
Guillaume Gomez 已提交
674 675
    }

G
Guillaume Gomez 已提交
676
    fn run(self, builder: &Builder<'_>) {
677 678 679
        if builder.config.nodejs.is_some() {
            builder.ensure(Compiletest {
                compiler: self.compiler,
G
Guillaume Gomez 已提交
680
                target: self.target,
681 682
                mode: "js-doc-test",
                suite: "rustdoc-js",
683
                path: "src/test/rustdoc-js",
684
                compare_mode: None,
G
Guillaume Gomez 已提交
685 686
            });
        } else {
M
Mark Rousskov 已提交
687
            builder.info("No nodejs found, skipping \"src/test/rustdoc-js\" tests");
G
Guillaume Gomez 已提交
688 689 690 691
        }
    }
}

G
Guillaume Gomez 已提交
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
#[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<'_> {
        run.path("src/test/rustdoc-gui")
    }

    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<'_>) {
        if let (Some(nodejs), Some(npm)) = (&builder.config.nodejs, &builder.config.npm) {
            builder.ensure(compile::Std { compiler: self.compiler, target: self.target });

            // The goal here is to check if the necessary packages are installed, and if not, we
            // display a warning and move on.
            let mut command = Command::new(&npm);
            command.arg("list").arg("--depth=0");
            let lines = command
                .output()
                .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
                .unwrap_or(String::new());
            if !lines.contains(&" browser-ui-test@") {
                println!(
                    "warning: rustdoc-gui test suite cannot be run because npm `browser-ui-test` \
                     dependency is missing",
                );
                println!(
                    "If you want to install the `{0}` dependency, run `npm install {0}`",
                    "browser-ui-test",
                );
                return;
            }

            let out_dir = builder.test_out(self.target).join("rustdoc-gui");
            let mut command = builder.rustdoc_cmd(self.compiler);
            command.arg("src/test/rustdoc-gui/lib.rs").arg("-o").arg(&out_dir);
            builder.run(&mut command);

            for file in fs::read_dir("src/test/rustdoc-gui").unwrap() {
                let file = file.unwrap();
                let file_path = file.path();
                let file_name = file.file_name();

                if !file_name.to_str().unwrap().ends_with(".goml") {
                    continue;
                }
                let mut command = Command::new(&nodejs);
                command
                    .arg("src/tools/rustdoc-gui/tester.js")
                    .arg("--doc-folder")
                    .arg(out_dir.join("test_docs"))
                    .arg("--test-file")
                    .arg(file_path);
                builder.run(&mut command);
            }
        } else {
            builder.info("No nodejs found, skipping \"src/test/rustdoc-gui\" tests");
        }
    }
}

764
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
M
Mark Simulacrum 已提交
765
pub struct Tidy;
766

767
impl Step for Tidy {
768
    type Output = ();
769 770
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;
771

M
Mark Simulacrum 已提交
772
    /// Runs the `tidy` tool.
773 774 775 776
    ///
    /// 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.
777 778 779
    ///
    /// Once tidy passes, this step also runs `fmt --check` if tests are being run
    /// for the `dev` or `nightly` channels.
T
Taiki Endo 已提交
780
    fn run(self, builder: &Builder<'_>) {
781
        let mut cmd = builder.tool_cmd(Tool::Tidy);
M
mark 已提交
782
        cmd.arg(&builder.src);
783
        cmd.arg(&builder.initial_cargo);
784
        cmd.arg(&builder.out);
M
Mark Rousskov 已提交
785 786
        if builder.is_verbose() {
            cmd.arg("--verbose");
787
        }
788

789
        builder.info("tidy check");
790
        try_run(builder, &mut cmd);
791 792 793

        if builder.config.channel == "dev" || builder.config.channel == "nightly" {
            builder.info("fmt check");
794
            crate::format::format(&builder.build, !builder.config.cmd.bless());
795
        }
796
    }
797

T
Taiki Endo 已提交
798
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
799
        run.path("src/tools/tidy")
800 801
    }

T
Taiki Endo 已提交
802
    fn make_run(run: RunConfig<'_>) {
M
Mark Simulacrum 已提交
803
        run.builder.ensure(Tidy);
804
    }
805
}
806

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
#[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);
    }
}

836 837
fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
    builder.out.join(host.triple).join("test")
838 839
}

840 841 842
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 已提交
843
    };
844 845
}

846 847 848
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 已提交
849 850 851 852 853 854 855 856 857
        test_with_compare_mode!($name {
            path: $path,
            mode: $mode,
            suite: $suite,
            default: true,
            host: false,
            compare_mode: $compare_mode
        });
    };
858 859
}

860 861 862
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 已提交
863
    };
864 865
}

866
macro_rules! test {
867 868
    ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
                   host: $host:expr }) => {
M
Mark Rousskov 已提交
869 870 871 872 873 874 875 876 877
        test_definitions!($name {
            path: $path,
            mode: $mode,
            suite: $suite,
            default: $default,
            host: $host,
            compare_mode: None
        });
    };
878 879 880 881 882
}

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 已提交
883 884 885 886 887 888 889 890 891
        test_definitions!($name {
            path: $path,
            mode: $mode,
            suite: $suite,
            default: $default,
            host: $host,
            compare_mode: Some($compare_mode)
        });
    };
892 893 894
}

macro_rules! test_definitions {
895 896 897 898 899
    ($name:ident {
        path: $path:expr,
        mode: $mode:expr,
        suite: $suite:expr,
        default: $default:expr,
900 901
        host: $host:expr,
        compare_mode: $compare_mode:expr
902 903 904 905
    }) => {
        #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
        pub struct $name {
            pub compiler: Compiler,
906
            pub target: TargetSelection,
907 908
        }

909 910 911 912
        impl Step for $name {
            type Output = ();
            const DEFAULT: bool = $default;
            const ONLY_HOSTS: bool = $host;
913

T
Taiki Endo 已提交
914
            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
915
                run.suite_path($path)
916
            }
917

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

M
Mark Rousskov 已提交
921
                run.builder.ensure($name { compiler, target: run.target });
922
            }
923

T
Taiki Endo 已提交
924
            fn run(self, builder: &Builder<'_>) {
925 926 927 928 929
                builder.ensure(Compiletest {
                    compiler: self.compiler,
                    target: self.target,
                    mode: $mode,
                    suite: $suite,
930
                    path: $path,
931
                    compare_mode: $compare_mode,
932 933 934
                })
            }
        }
M
Mark Rousskov 已提交
935
    };
936 937
}

938
default_test_with_compare_mode!(Ui {
939 940
    path: "src/test/ui",
    mode: "ui",
941 942
    suite: "ui",
    compare_mode: "nll"
943 944 945 946 947 948 949 950
});

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

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

M
Mark Rousskov 已提交
953
default_test!(Codegen { path: "src/test/codegen", mode: "codegen", suite: "codegen" });
954 955 956 957 958 959 960 961 962 963 964 965 966

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"
});

967 968 969 970 971 972
default_test_with_compare_mode!(Debuginfo {
    path: "src/test/debuginfo",
    mode: "debuginfo",
    suite: "debuginfo",
    compare_mode: "split-dwarf"
});
973

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

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

N
Nixon Enraght-Moony 已提交
979 980 981 982 983 984
host_test!(RustdocJson {
    path: "src/test/rustdoc-json",
    mode: "rustdoc-json",
    suite: "rustdoc-json"
});

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

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

989 990 991 992 993 994
host_test!(RunMakeFullDeps {
    path: "src/test/run-make-fulldeps",
    mode: "run-make",
    suite: "run-make-fulldeps"
});

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

997 998 999
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
struct Compiletest {
    compiler: Compiler,
1000
    target: TargetSelection,
1001 1002
    mode: &'static str,
    suite: &'static str,
1003
    path: &'static str,
1004
    compare_mode: Option<&'static str>,
1005 1006 1007 1008 1009
}

impl Step for Compiletest {
    type Output = ();

T
Taiki Endo 已提交
1010
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1011 1012 1013
        run.never()
    }

1014 1015 1016 1017 1018
    /// 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 已提交
1019
    fn run(self, builder: &Builder<'_>) {
1020 1021 1022
        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
1023 1024
help: to test the compiler, use `--stage 1` instead
help: to test the standard library, use `--stage 0 library/std` instead
1025 1026 1027 1028 1029
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);
        }

1030 1031 1032 1033
        let compiler = self.compiler;
        let target = self.target;
        let mode = self.mode;
        let suite = self.suite;
1034

1035
        // Path for test suite
1036
        let suite_path = self.path;
1037

1038
        // Skip codegen tests if they aren't enabled in configuration.
1039
        if !builder.config.codegen_tests && suite == "codegen" {
1040 1041 1042 1043
            return;
        }

        if suite == "debuginfo" {
M
Mark Rousskov 已提交
1044 1045
            builder
                .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target });
1046 1047
        }

1048
        if suite.ends_with("fulldeps") {
1049 1050 1051
            builder.ensure(compile::Rustc { compiler, target });
        }

1052 1053 1054
        builder.ensure(compile::Std { compiler, target });
        // ensure that `libproc_macro` is available on the host.
        builder.ensure(compile::Std { compiler, target: compiler.host });
1055

1056 1057
        // Also provide `rust_test_helpers` for the host.
        builder.ensure(native::TestHelpers { target: compiler.host });
1058

1059 1060
        // As well as the target, except for plain wasm32, which can't build it
        if !target.contains("wasm32") || target.contains("emscripten") {
1061 1062
            builder.ensure(native::TestHelpers { target });
        }
1063

1064
        builder.ensure(RemoteCopyLibs { compiler, target });
1065 1066

        let mut cmd = builder.tool_cmd(Tool::Compiletest);
1067 1068 1069 1070

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

M
Mark Rousskov 已提交
1071 1072
        cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
        cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
1073
        cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1074

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

1077
        // Avoid depending on rustdoc when we don't need it.
S
Santiago Pastorino 已提交
1078 1079
        if mode == "rustdoc"
            || (mode == "run-make" && suite.ends_with("fulldeps"))
1080 1081
            || (mode == "ui" && is_rustdoc)
            || mode == "js-doc-test"
N
Nixon Enraght-Moony 已提交
1082
            || mode == "rustdoc-json"
S
Santiago Pastorino 已提交
1083
        {
M
Mark Rousskov 已提交
1084
            cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler));
1085 1086
        }

1087 1088 1089 1090 1091 1092 1093
        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 已提交
1094 1095 1096 1097
        if mode == "run-make" && suite.ends_with("fulldeps") {
            cmd.arg("--rust-demangler-path").arg(builder.tool_exe(Tool::RustDemangler));
        }

M
Mark Rousskov 已提交
1098 1099 1100
        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));
1101
        cmd.arg("--suite").arg(suite);
1102
        cmd.arg("--mode").arg(mode);
1103 1104
        cmd.arg("--target").arg(target.rustc_target_arg());
        cmd.arg("--host").arg(&*compiler.host.triple);
M
Mark Rousskov 已提交
1105
        cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.build));
1106

1107
        if builder.config.cmd.bless() {
1108 1109 1110
            cmd.arg("--bless");
        }

M
Mark Rousskov 已提交
1111 1112 1113 1114
        let compare_mode =
            builder.config.cmd.compare_mode().or_else(|| {
                if builder.config.test_compare_mode { self.compare_mode } else { None }
            });
S
Santiago Pastorino 已提交
1115

1116 1117 1118 1119 1120
        if let Some(ref pass) = builder.config.cmd.pass() {
            cmd.arg("--pass");
            cmd.arg(pass);
        }

1121
        if let Some(ref nodejs) = builder.config.nodejs {
1122 1123
            cmd.arg("--nodejs").arg(nodejs);
        }
G
Guillaume Gomez 已提交
1124 1125 1126
        if let Some(ref npm) = builder.config.npm {
            cmd.arg("--npm").arg(npm);
        }
1127

M
Mark Rousskov 已提交
1128
        let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
1129
        if !is_rustdoc {
1130
            if builder.config.rust_optimize_tests {
G
Guillaume Gomez 已提交
1131 1132
                flags.push("-O".to_string());
            }
1133
        }
1134
        flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests));
G
Guillaume Gomez 已提交
1135
        flags.push("-Zunstable-options".to_string());
1136
        flags.push(builder.config.cmd.rustc_args().join(" "));
1137

1138
        if let Some(linker) = builder.linker(target) {
O
Oliver Schneider 已提交
1139 1140 1141
            cmd.arg("--linker").arg(linker);
        }

1142
        let mut hostflags = flags.clone();
M
Mark Rousskov 已提交
1143
        hostflags.push(format!("-Lnative={}", builder.test_helpers_out(compiler.host).display()));
1144
        if builder.is_fuse_ld_lld(compiler.host) {
1145 1146
            hostflags.push("-Clink-args=-fuse-ld=lld".to_string());
        }
1147 1148
        cmd.arg("--host-rustcflags").arg(hostflags.join(" "));

S
Shotaro Yamada 已提交
1149
        let mut targetflags = flags;
M
Mark Rousskov 已提交
1150
        targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
1151
        if builder.is_fuse_ld_lld(target) {
1152 1153
            targetflags.push("-Clink-args=-fuse-ld=lld".to_string());
        }
1154 1155
        cmd.arg("--target-rustcflags").arg(targetflags.join(" "));

1156
        cmd.arg("--docck-python").arg(builder.python());
1157

1158
        if builder.config.build.ends_with("apple-darwin") {
1159
            // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1160 1161
            // LLDB plugin's compiled module which only works with the system python
            // (namely not Homebrew-installed python)
1162
            cmd.arg("--lldb-python").arg("/usr/bin/python3");
1163
        } else {
1164
            cmd.arg("--lldb-python").arg(builder.python());
1165
        }
1166

1167
        if let Some(ref gdb) = builder.config.gdb {
1168 1169
            cmd.arg("--gdb").arg(gdb);
        }
1170 1171 1172 1173

        let run = |cmd: &mut Command| {
            cmd.output().map(|output| {
                String::from_utf8_lossy(&output.stdout)
M
Mark Rousskov 已提交
1174 1175 1176 1177
                    .lines()
                    .next()
                    .unwrap_or_else(|| panic!("{:?} failed {:?}", cmd, output))
                    .to_string()
1178 1179
            })
        };
1180 1181
        let lldb_exe = "lldb";
        let lldb_version = Command::new(lldb_exe)
1182 1183
            .arg("--version")
            .output()
M
Mark Rousskov 已提交
1184
            .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
1185 1186
            .ok();
        if let Some(ref vers) = lldb_version {
1187
            cmd.arg("--lldb-version").arg(vers);
1188
            let lldb_python_dir = run(Command::new(lldb_exe).arg("-P")).ok();
1189 1190 1191
            if let Some(ref dir) = lldb_python_dir {
                cmd.arg("--lldb-python-dir").arg(dir);
            }
1192
        }
1193

1194 1195 1196
        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);
1197 1198
        }

1199 1200
        // Get paths from cmd args
        let paths = match &builder.config.cmd {
S
Santiago Pastorino 已提交
1201 1202
            Subcommand::Test { ref paths, .. } => &paths[..],
            _ => &[],
1203 1204 1205
        };

        // Get test-args by striping suite path
S
Santiago Pastorino 已提交
1206 1207
        let mut test_args: Vec<&str> = paths
            .iter()
M
Mark Rousskov 已提交
1208 1209 1210
            .map(|p| match p.strip_prefix(".") {
                Ok(path) => path,
                Err(_) => p,
1211
            })
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
            .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
            })
1225
            .filter_map(|p| {
V
varkor 已提交
1226 1227 1228 1229 1230 1231
                // 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.
1232
                match p.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
M
Matthias Krüger 已提交
1233
                    Some(s) if !s.is_empty() => Some(s),
1234 1235 1236
                    _ => None,
                }
            })
S
Santiago Pastorino 已提交
1237
            .collect();
1238 1239 1240 1241

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

        cmd.args(&test_args);
1242

1243
        if builder.is_verbose() {
1244 1245
            cmd.arg("--verbose");
        }
1246

O
Oliver Schneider 已提交
1247
        if !builder.config.verbose_tests {
1248 1249
            cmd.arg("--quiet");
        }
1250

1251 1252
        let mut llvm_components_passed = false;
        let mut copts_passed = false;
B
bjorn3 已提交
1253
        if builder.config.llvm_enabled() {
M
Mark Rousskov 已提交
1254
            let llvm_config = builder.ensure(native::Llvm { target: builder.config.build });
1255
            if !builder.config.dry_run {
1256
                let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1257
                let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1258
                // Remove trailing newline from llvm-config output.
1259 1260 1261 1262 1263
                cmd.arg("--llvm-version")
                    .arg(llvm_version.trim())
                    .arg("--llvm-components")
                    .arg(llvm_components.trim());
                llvm_components_passed = true;
1264
            }
1265
            if !builder.is_rust_llvm(target) {
B
bjorn3 已提交
1266 1267 1268
                cmd.arg("--system-llvm");
            }

1269 1270 1271 1272 1273 1274 1275 1276 1277
            // 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 已提交
1278 1279
            // 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.
1280
            if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1281 1282
                // 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 已提交
1283 1284
                let llvm_bin_path = llvm_config
                    .parent()
1285 1286 1287
                    .expect("Expected llvm-config to be contained in directory");
                assert!(llvm_bin_path.is_dir());
                cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
1288 1289 1290

                // If LLD is available, add it to the PATH
                if builder.config.lld_enabled {
M
Mark Rousskov 已提交
1291 1292
                    let lld_install_root =
                        builder.ensure(native::Lld { target: builder.config.build });
1293 1294 1295 1296

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

                    let old_path = env::var_os("PATH").unwrap_or_default();
M
Mark Rousskov 已提交
1297 1298 1299 1300
                    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");
1301 1302
                    cmd.env("PATH", new_path);
                }
B
bjorn3 已提交
1303 1304 1305
            }
        }

1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
        // 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);
            }
        }

1321 1322 1323 1324 1325
        if !llvm_components_passed {
            cmd.arg("--llvm-components").arg("");
        }
        if !copts_passed {
            cmd.arg("--cc").arg("").arg("--cxx").arg("").arg("--cflags").arg("");
1326
        }
1327

1328
        if builder.remote_tested(target) {
M
Mark Rousskov 已提交
1329
            cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
1330
        }
1331

1332 1333 1334 1335 1336 1337
        // 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") {
1338
            for &(ref k, ref v) in builder.cc[&target].env() {
1339 1340 1341
                if k != "PATH" {
                    cmd.env(k, v);
                }
1342 1343
            }
        }
1344
        cmd.env("RUSTC_BOOTSTRAP", "1");
1345
        builder.add_rust_test_threads(&mut cmd);
1346

1347
        if builder.config.sanitizers_enabled(target) {
1348
            cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
1349
        }
1350

1351
        if builder.config.profiler_enabled(target) {
1352
            cmd.env("RUSTC_PROFILER_SUPPORT", "1");
1353
        }
1354

M
Mark Rousskov 已提交
1355 1356 1357 1358
        let tmp = builder.out.join("tmp");
        std::fs::create_dir_all(&tmp).unwrap();
        cmd.env("RUST_TEST_TMPDIR", tmp);

1359 1360 1361 1362 1363
        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 已提交
1364
                .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1365 1366 1367
        } else {
            cmd.arg("--android-cross-path").arg("");
        }
1368

1369 1370 1371 1372
        if builder.config.cmd.rustfix_coverage() {
            cmd.arg("--rustfix-coverage");
        }

1373 1374
        cmd.env("BOOTSTRAP_CARGO", &builder.initial_cargo);

1375
        builder.ci_env.force_coloring_in_ci(&mut cmd);
1376

S
Santiago Pastorino 已提交
1377 1378 1379 1380
        builder.info(&format!(
            "Check compiletest suite={} mode={} ({} -> {})",
            suite, mode, &compiler.host, target
        ));
1381 1382
        let _time = util::timeit(&builder);
        try_run(builder, &mut cmd);
1383 1384 1385

        if let Some(compare_mode) = compare_mode {
            cmd.arg("--compare-mode").arg(compare_mode);
S
Santiago Pastorino 已提交
1386 1387 1388 1389
            builder.info(&format!(
                "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
                suite, mode, compare_mode, &compiler.host, target
            ));
1390 1391 1392
            let _time = util::timeit(&builder);
            try_run(builder, &mut cmd);
        }
1393
    }
1394
}
1395

E
Eric Huss 已提交
1396 1397
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct BookTest {
1398
    compiler: Compiler,
E
Eric Huss 已提交
1399
    path: PathBuf,
1400 1401
    name: &'static str,
    is_ext_doc: bool,
1402 1403
}

E
Eric Huss 已提交
1404
impl Step for BookTest {
1405 1406
    type Output = ();
    const ONLY_HOSTS: bool = true;
1407

T
Taiki Endo 已提交
1408
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1409
        run.never()
1410
    }
M
Mark Simulacrum 已提交
1411

E
Eric Huss 已提交
1412
    /// Runs the documentation tests for a book in `src/doc`.
1413
    ///
E
Eric Huss 已提交
1414
    /// This uses the `rustdoc` that sits next to `compiler`.
T
Taiki Endo 已提交
1415
    fn run(self, builder: &Builder<'_>) {
E
Eric Huss 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
        // 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<'_>) {
1465
        let compiler = self.compiler;
1466

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

1469 1470
        // Do a breadth-first traversal of the `src/doc` directory and just run
        // tests for all files that end in `*.md`
1471 1472
        let mut stack = vec![builder.src.join(self.path)];
        let _time = util::timeit(&builder);
1473
        let mut files = Vec::new();
1474 1475 1476
        while let Some(p) = stack.pop() {
            if p.is_dir() {
                stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
S
Santiago Pastorino 已提交
1477
                continue;
1478 1479 1480 1481 1482 1483
            }

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

1484 1485 1486 1487 1488 1489
            files.push(p);
        }

        files.sort();

        for file in files {
E
Eric Huss 已提交
1490
            markdown_test(builder, compiler, &file);
1491
        }
1492 1493 1494
    }
}

1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
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 已提交
1508
                fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1509 1510 1511
                    run.path($path)
                }

T
Taiki Endo 已提交
1512
                fn make_run(run: RunConfig<'_>) {
1513
                    run.builder.ensure($name {
1514
                        compiler: run.builder.compiler(run.builder.top_stage, run.target),
1515 1516 1517
                    });
                }

T
Taiki Endo 已提交
1518
                fn run(self, builder: &Builder<'_>) {
E
Eric Huss 已提交
1519
                    builder.ensure(BookTest {
1520
                        compiler: self.compiler,
E
Eric Huss 已提交
1521
                        path: PathBuf::from($path),
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
                        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;
1535
    RustcBook, "src/doc/rustc", "rustc", default=true;
1536
    RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1537
    EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
1538 1539
    TheBook, "src/doc/book", "book", default=false;
    UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
E
Eric Huss 已提交
1540
    EditionGuide, "src/doc/edition-guide", "edition-guide", default=false;
1541 1542
);

1543 1544 1545
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ErrorIndex {
    compiler: Compiler,
1546
}
1547

1548
impl Step for ErrorIndex {
1549
    type Output = ();
1550 1551 1552
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
1553
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1554
        run.path("src/tools/error_index_generator")
1555 1556
    }

T
Taiki Endo 已提交
1557
    fn make_run(run: RunConfig<'_>) {
E
Eric Huss 已提交
1558 1559 1560
        // 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.
1561
        let compiler = run.builder.compiler(run.builder.top_stage, run.builder.config.build);
E
Eric Huss 已提交
1562
        run.builder.ensure(ErrorIndex { compiler });
1563
    }
1564

A
Alexander Regueiro 已提交
1565
    /// Runs the error index generator tool to execute the tests located in the error
1566 1567 1568 1569 1570
    /// 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 已提交
1571
    fn run(self, builder: &Builder<'_>) {
1572 1573
        let compiler = self.compiler;

1574
        let dir = testdir(builder, compiler.host);
1575 1576 1577
        t!(fs::create_dir_all(&dir));
        let output = dir.join("error-index.md");

1578
        let mut tool = tool::ErrorIndex::command(builder);
E
Eric Huss 已提交
1579
        tool.arg("markdown").arg(&output);
1580

1581
        builder.info(&format!("Testing error-index stage{}", compiler.stage));
1582
        let _time = util::timeit(&builder);
1583
        builder.run_quiet(&mut tool);
1584 1585 1586 1587
        // 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);
1588
    }
1589 1590
}

T
Taiki Endo 已提交
1591
fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
1592 1593 1594
    if let Ok(contents) = fs::read_to_string(markdown) {
        if !contents.contains("```") {
            return true;
1595
        }
1596 1597
    }

1598
    builder.info(&format!("doc tests for: {}", markdown.display()));
M
Mark Rousskov 已提交
1599
    let mut cmd = builder.rustdoc_cmd(compiler);
1600
    builder.add_rust_test_threads(&mut cmd);
1601 1602
    cmd.arg("--test");
    cmd.arg(markdown);
1603
    cmd.env("RUSTC_BOOTSTRAP", "1");
1604

1605
    let test_args = builder.config.cmd.test_args().join(" ");
1606 1607
    cmd.arg("--test-args").arg(test_args);

O
Oliver Schneider 已提交
1608
    if builder.config.verbose_tests {
1609
        try_run(builder, &mut cmd)
O
Oliver Schneider 已提交
1610 1611
    } else {
        try_run_quiet(builder, &mut cmd)
1612
    }
1613
}
1614

1615 1616 1617 1618 1619 1620 1621 1622 1623
#[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<'_> {
1624
        run.path("src/doc/rustc-dev-guide")
1625 1626 1627 1628 1629 1630 1631
    }

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

    fn run(self, builder: &Builder<'_>) {
1632
        let src = builder.src.join("src/doc/rustc-dev-guide");
1633
        let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
E
Eric Huss 已提交
1634 1635 1636 1637 1638
        let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) {
            ToolState::TestPass
        } else {
            ToolState::TestFail
        };
1639
        builder.save_toolstate("rustc-dev-guide", toolstate);
1640 1641 1642
    }
}

1643
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
M
Mark Simulacrum 已提交
1644
pub struct CrateLibrustc {
1645
    compiler: Compiler,
1646
    target: TargetSelection,
1647
    test_kind: TestKind,
1648
    krate: Interned<String>,
1649 1650
}

M
Mark Simulacrum 已提交
1651
impl Step for CrateLibrustc {
1652 1653 1654 1655
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

T
Taiki Endo 已提交
1656
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1657
        run.krate("rustc-main")
1658 1659
    }

T
Taiki Endo 已提交
1660
    fn make_run(run: RunConfig<'_>) {
1661
        let builder = run.builder;
1662
        let compiler = builder.compiler(builder.top_stage, run.build_triple());
1663

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

1668 1669 1670 1671 1672 1673
                builder.ensure(CrateLibrustc {
                    compiler,
                    target: run.target,
                    test_kind,
                    krate: krate.name,
                });
1674 1675 1676 1677
            }
        }
    }

T
Taiki Endo 已提交
1678
    fn run(self, builder: &Builder<'_>) {
M
Mark Simulacrum 已提交
1679
        builder.ensure(Crate {
1680 1681
            compiler: self.compiler,
            target: self.target,
C
Collins Abitekaniza 已提交
1682
            mode: Mode::Rustc,
1683 1684 1685 1686 1687 1688
            test_kind: self.test_kind,
            krate: self.krate,
        });
    }
}

K
kennytm 已提交
1689
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
M
Mark Simulacrum 已提交
1690
pub struct Crate {
K
kennytm 已提交
1691
    pub compiler: Compiler,
1692
    pub target: TargetSelection,
K
kennytm 已提交
1693 1694 1695
    pub mode: Mode,
    pub test_kind: TestKind,
    pub krate: Interned<String>,
1696
}
1697

M
Mark Simulacrum 已提交
1698
impl Step for Crate {
1699
    type Output = ();
1700 1701
    const DEFAULT: bool = true;

1702 1703
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
        run.krate("test")
1704 1705
    }

T
Taiki Endo 已提交
1706
    fn make_run(run: RunConfig<'_>) {
1707
        let builder = run.builder;
1708
        let compiler = builder.compiler(builder.top_stage, run.build_triple());
1709

1710
        let make = |mode: Mode, krate: &CargoCrate| {
1711
            let test_kind = builder.kind.into();
1712

M
Mark Simulacrum 已提交
1713
            builder.ensure(Crate {
1714 1715
                compiler,
                target: run.target,
1716 1717
                mode,
                test_kind,
1718
                krate: krate.name,
1719 1720 1721
            });
        };

1722
        for krate in builder.in_tree_crates("test", Some(run.target)) {
E
Eric Huss 已提交
1723
            if krate.path.ends_with(&run.path) {
1724
                make(Mode::Std, krate);
1725 1726 1727
            }
        }
    }
1728

A
Alexander Regueiro 已提交
1729
    /// Runs all unit tests plus documentation tests for a given crate defined
1730
    /// by a `Cargo.toml` (single manifest)
1731 1732 1733 1734 1735 1736
    ///
    /// 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 已提交
1737
    fn run(self, builder: &Builder<'_>) {
1738 1739 1740 1741 1742 1743
        let compiler = self.compiler;
        let target = self.target;
        let mode = self.mode;
        let test_kind = self.test_kind;
        let krate = self.krate;

1744
        builder.ensure(compile::Std { compiler, target });
1745
        builder.ensure(RemoteCopyLibs { compiler, target });
A
Alex Crichton 已提交
1746

1747 1748 1749 1750 1751
        // 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 已提交
1752

1753 1754
        let mut cargo =
            builder.cargo(compiler, mode, SourceType::InTree, target, test_kind.subcommand());
1755
        match mode {
C
Collins Abitekaniza 已提交
1756
            Mode::Std => {
1757
                compile::std_cargo(builder, target, compiler.stage, &mut cargo);
1758
            }
C
Collins Abitekaniza 已提交
1759
            Mode::Rustc => {
1760
                builder.ensure(compile::Rustc { compiler, target });
1761
                compile::rustc_cargo(builder, &mut cargo, target);
1762 1763 1764 1765 1766 1767 1768 1769 1770
            }
            _ => 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.
1771
        if test_kind.subcommand() == "test" && !builder.fail_fast {
1772 1773
            cargo.arg("--no-fail-fast");
        }
K
kennytm 已提交
1774
        match builder.doc_tests {
K
kennytm 已提交
1775
            DocTests::Only => {
K
kennytm 已提交
1776 1777
                cargo.arg("--doc");
            }
K
kennytm 已提交
1778
            DocTests::No => {
K
kennytm 已提交
1779 1780
                cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
            }
K
kennytm 已提交
1781
            DocTests::Yes => {}
1782
        }
1783

1784
        cargo.arg("-p").arg(krate);
1785

1786 1787 1788 1789 1790 1791
        // 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();
1792
        dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1793 1794 1795
        cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());

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

O
Oliver Schneider 已提交
1798
        if !builder.config.verbose_tests {
1799 1800
            cargo.arg("--quiet");
        }
1801

1802
        if target.contains("emscripten") {
S
Santiago Pastorino 已提交
1803
            cargo.env(
1804
                format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
M
Mark Rousskov 已提交
1805
                builder.config.nodejs.as_ref().expect("nodejs not configured"),
S
Santiago Pastorino 已提交
1806
            );
O
Oliver Schneider 已提交
1807
        } else if target.starts_with("wasm32") {
M
Mark Rousskov 已提交
1808 1809 1810
            let node = builder.config.nodejs.as_ref().expect("nodejs not configured");
            let runner =
                format!("{} {}/src/etc/wasm32-shim.js", node.display(), builder.src.display());
1811
            cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), &runner);
1812
        } else if builder.remote_tested(target) {
S
Santiago Pastorino 已提交
1813
            cargo.env(
1814
                format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
1815
                format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
S
Santiago Pastorino 已提交
1816
            );
1817
        }
1818

S
Santiago Pastorino 已提交
1819 1820 1821 1822
        builder.info(&format!(
            "{} {} stage{} ({} -> {})",
            test_kind, krate, compiler.stage, &compiler.host, target
        ));
1823
        let _time = util::timeit(&builder);
1824
        try_run(builder, &mut cargo.into());
1825 1826
    }
}
1827

M
Mark Simulacrum 已提交
1828
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1829
pub struct CrateRustdoc {
1830
    host: TargetSelection,
M
Mark Simulacrum 已提交
1831 1832 1833
    test_kind: TestKind,
}

1834
impl Step for CrateRustdoc {
M
Mark Simulacrum 已提交
1835 1836 1837 1838
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

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

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

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

1848
        builder.ensure(CrateRustdoc { host: run.target, test_kind });
M
Mark Simulacrum 已提交
1849 1850
    }

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

E
Eric Huss 已提交
1855 1856 1857 1858 1859
        // 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);
1860
        builder.ensure(compile::Rustc { compiler, target });
M
Mark Simulacrum 已提交
1861

M
Mark Rousskov 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
        let mut cargo = tool::prepare_tool_cargo(
            builder,
            compiler,
            Mode::ToolRustc,
            target,
            test_kind.subcommand(),
            "src/tools/rustdoc",
            SourceType::InTree,
            &[],
        );
1872
        if test_kind.subcommand() == "test" && !builder.fail_fast {
M
Mark Simulacrum 已提交
1873 1874 1875 1876 1877 1878
            cargo.arg("--no-fail-fast");
        }

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

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

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

E
Eric Huss 已提交
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
        // 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 已提交
1911
        if !builder.config.verbose_tests {
M
Mark Simulacrum 已提交
1912 1913 1914
            cargo.arg("--quiet");
        }

S
Santiago Pastorino 已提交
1915 1916 1917 1918
        builder.info(&format!(
            "{} rustdoc stage{} ({} -> {})",
            test_kind, compiler.stage, &compiler.host, target
        ));
1919
        let _time = util::timeit(&builder);
M
Mark Simulacrum 已提交
1920

1921
        try_run(builder, &mut cargo.into());
M
Mark Simulacrum 已提交
1922 1923 1924
    }
}

1925 1926 1927 1928 1929
/// 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 已提交
1930
/// Most of the time this is a no-op. For some steps such as shipping data to
1931 1932 1933
/// 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.
1934 1935 1936
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct RemoteCopyLibs {
    compiler: Compiler,
1937
    target: TargetSelection,
1938
}
1939

1940
impl Step for RemoteCopyLibs {
1941
    type Output = ();
1942

T
Taiki Endo 已提交
1943
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1944
        run.never()
1945 1946
    }

T
Taiki Endo 已提交
1947
    fn run(self, builder: &Builder<'_>) {
1948 1949
        let compiler = self.compiler;
        let target = self.target;
1950
        if !builder.remote_tested(target) {
S
Santiago Pastorino 已提交
1951
            return;
1952 1953
        }

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

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

1959
        let server = builder.ensure(tool::RemoteTestServer { compiler, target });
1960 1961

        // Spawn the emulator and wait for it to come online
1962
        let tool = builder.tool_exe(Tool::RemoteTestClient);
1963
        let mut cmd = Command::new(&tool);
1964
        cmd.arg("spawn-emulator").arg(target.triple).arg(&server).arg(builder.out.join("tmp"));
1965
        if let Some(rootfs) = builder.qemu_rootfs(target) {
1966 1967
            cmd.arg(rootfs);
        }
1968
        builder.run(&mut cmd);
1969 1970

        // Push all our dylibs to the emulator
1971
        for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
1972 1973 1974
            let f = t!(f);
            let name = f.file_name().into_string().unwrap();
            if util::is_dylib(&name) {
S
Santiago Pastorino 已提交
1975
                builder.run(Command::new(&tool).arg("push").arg(f.path()));
1976
            }
1977 1978 1979 1980
        }
    }
}

1981
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1982
pub struct Distcheck;
A
Alex Crichton 已提交
1983

1984
impl Step for Distcheck {
1985 1986
    type Output = ();

T
Taiki Endo 已提交
1987
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1988
        run.path("distcheck")
1989 1990
    }

T
Taiki Endo 已提交
1991
    fn make_run(run: RunConfig<'_>) {
M
Mark Simulacrum 已提交
1992 1993 1994
        run.builder.ensure(Distcheck);
    }

A
Alexander Regueiro 已提交
1995
    /// Runs "distcheck", a 'make check' from a tarball
T
Taiki Endo 已提交
1996
    fn run(self, builder: &Builder<'_>) {
1997
        builder.info("Distcheck");
1998
        let dir = builder.out.join("tmp").join("distcheck");
1999 2000 2001
        let _ = fs::remove_dir_all(&dir);
        t!(fs::create_dir_all(&dir));

M
Mark Simulacrum 已提交
2002 2003 2004 2005
        // Guarantee that these are built before we begin running.
        builder.ensure(dist::PlainSourceTarball);
        builder.ensure(dist::Src);

2006
        let mut cmd = Command::new("tar");
2007
        cmd.arg("-xf")
2008
            .arg(builder.ensure(dist::PlainSourceTarball).tarball())
S
Santiago Pastorino 已提交
2009 2010
            .arg("--strip-components=1")
            .current_dir(&dir);
2011
        builder.run(&mut cmd);
S
Santiago Pastorino 已提交
2012 2013 2014 2015 2016 2017 2018
        builder.run(
            Command::new("./configure")
                .args(&builder.config.configure_args)
                .arg("--enable-vendor")
                .current_dir(&dir),
        );
        builder.run(
2019 2020 2021
            Command::new(build_helper::make(&builder.config.build.triple))
                .arg("check")
                .current_dir(&dir),
S
Santiago Pastorino 已提交
2022
        );
2023 2024

        // Now make sure that rust-src has all of libstd's dependencies
2025
        builder.info("Distcheck rust-src");
2026
        let dir = builder.out.join("tmp").join("distcheck-src");
2027 2028 2029 2030
        let _ = fs::remove_dir_all(&dir);
        t!(fs::create_dir_all(&dir));

        let mut cmd = Command::new("tar");
2031 2032 2033 2034
        cmd.arg("-xf")
            .arg(builder.ensure(dist::Src).tarball())
            .arg("--strip-components=1")
            .current_dir(&dir);
2035
        builder.run(&mut cmd);
2036

M
mark 已提交
2037
        let toml = dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
S
Santiago Pastorino 已提交
2038 2039 2040 2041 2042 2043 2044
        builder.run(
            Command::new(&builder.initial_cargo)
                .arg("generate-lockfile")
                .arg("--manifest-path")
                .arg(&toml)
                .current_dir(&dir),
        );
2045
    }
A
Alex Crichton 已提交
2046
}
2047

2048
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2049 2050
pub struct Bootstrap;

2051
impl Step for Bootstrap {
2052
    type Output = ();
2053 2054
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;
2055

A
Alexander Regueiro 已提交
2056
    /// Tests the build system itself.
T
Taiki Endo 已提交
2057
    fn run(self, builder: &Builder<'_>) {
2058
        let mut cmd = Command::new(&builder.initial_cargo);
2059
        cmd.arg("test")
S
Santiago Pastorino 已提交
2060 2061 2062
            .current_dir(builder.src.join("src/bootstrap"))
            .env("RUSTFLAGS", "-Cdebuginfo=2")
            .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
2063 2064
            .env("BOOTSTRAP_OUTPUT_DIRECTORY", &builder.config.out)
            .env("BOOTSTRAP_INITIAL_CARGO", &builder.config.initial_cargo)
S
Santiago Pastorino 已提交
2065 2066
            .env("RUSTC_BOOTSTRAP", "1")
            .env("RUSTC", &builder.initial_rustc);
2067 2068 2069 2070 2071 2072
        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);
        }
2073
        if !builder.fail_fast {
2074 2075
            cmd.arg("--no-fail-fast");
        }
2076
        cmd.arg("--").args(&builder.config.cmd.test_args());
2077 2078 2079
        // 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");
2080
        try_run(builder, &mut cmd);
2081
    }
2082

T
Taiki Endo 已提交
2083
    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2084
        run.path("src/bootstrap")
2085 2086
    }

T
Taiki Endo 已提交
2087
    fn make_run(run: RunConfig<'_>) {
2088
        run.builder.ensure(Bootstrap);
2089
    }
2090
}
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106

#[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<'_>) {
2107 2108 2109
        let compiler =
            run.builder.compiler_for(run.builder.top_stage, run.builder.build.build, run.target);
        run.builder.ensure(TierCheck { compiler });
2110 2111 2112 2113
    }

    /// Tests the Platform Support page in the rustc book.
    fn run(self, builder: &Builder<'_>) {
2114
        builder.ensure(compile::Std { compiler: self.compiler, target: self.compiler.host });
2115 2116 2117
        let mut cargo = tool::prepare_tool_cargo(
            builder,
            self.compiler,
2118 2119
            Mode::ToolStd,
            self.compiler.host,
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
            "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());
    }
}
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167

#[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,
        });
    }
}