test.rs 53.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11
//! Implementation of the test-related targets of the build system.
12 13 14 15
//!
//! This file implements the various regression test suites that we execute on
//! our CI.

16
use std::env;
N
Nick Cameron 已提交
17
use std::ffi::OsString;
M
Mark Simulacrum 已提交
18
use std::iter;
U
Ulrik Sverdrup 已提交
19
use std::fmt;
20
use std::fs::{self, File};
21 22
use std::path::{PathBuf, Path};
use std::process::Command;
23
use std::io::Read;
24

25
use build_helper::{self, output};
26

A
Alex Crichton 已提交
27
use builder::{Kind, RunConfig, ShouldRun, Builder, Compiler, Step};
28
use Crate as CargoCrate;
A
Alex Crichton 已提交
29
use cache::{INTERNER, Interned};
30
use compile;
A
Alex Crichton 已提交
31
use dist;
32
use native;
33
use tool::{self, Tool};
A
Alex Crichton 已提交
34 35
use util::{self, dylib_path, dylib_path_var};
use {Build, Mode};
36
use toolstate::ToolState;
37

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

U
Ulrik Sverdrup 已提交
40
/// The two modes of the test runner; tests or benchmarks.
41
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
U
Ulrik Sverdrup 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
pub enum TestKind {
    /// Run `cargo test`
    Test,
    /// Run `cargo bench`
    Bench,
}

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 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match *self {
            TestKind::Test => "Testing",
            TestKind::Bench => "Benchmarking",
        })
    }
}

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

81
fn try_run_quiet(build: &Build, cmd: &mut Command) -> bool {
82
    if !build.fail_fast {
83
        if !build.try_run_quiet(cmd) {
84 85
            let mut failures = build.delayed_failures.borrow_mut();
            failures.push(format!("{:?}", cmd));
86
            return false;
87 88 89 90
        }
    } else {
        build.run_quiet(cmd);
    }
91
    true
92 93
}

94 95 96
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Linkcheck {
    host: Interned<String>,
97 98
}

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

    /// 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.
    fn run(self, builder: &Builder) {
        let build = builder.build;
        let host = self.host;

112
        build.info(&format!("Linkcheck ({})", host));
113 114

        builder.default_doc(None);
115

116
        let _time = util::timeit(&build);
117
        try_run(build, builder.tool_cmd(Tool::Linkchecker)
G
Guillaume Gomez 已提交
118
                              .arg(build.out.join(host).join("doc")));
119
    }
120

121
    fn should_run(run: ShouldRun) -> ShouldRun {
122 123
        let builder = run.builder;
        run.path("src/tools/linkchecker").default_condition(builder.build.config.docs)
124 125
    }

126
    fn make_run(run: RunConfig) {
127
        run.builder.ensure(Linkcheck { host: run.target });
128
    }
129
}
130

131 132
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Cargotest {
133
    stage: u32,
134
    host: Interned<String>,
135
}
136

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

141 142
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/cargotest")
143 144
    }

145 146 147
    fn make_run(run: RunConfig) {
        run.builder.ensure(Cargotest {
            stage: run.builder.top_stage,
148
            host: run.target,
149 150 151
        });
    }

152 153 154 155 156 157
    /// 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.
    fn run(self, builder: &Builder) {
        let build = builder.build;
158
        let compiler = builder.compiler(self.stage, self.host);
159
        builder.ensure(compile::Rustc { compiler, target: compiler.host });
160 161 162 163 164 165 166

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

167
        let _time = util::timeit(&build);
168
        let mut cmd = builder.tool_cmd(Tool::CargoTest);
169 170
        try_run(build, cmd.arg(&build.initial_cargo)
                          .arg(&out_dir)
171
                          .env("RUSTC", builder.rustc(compiler))
172
                          .env("RUSTDOC", builder.rustdoc(compiler.host)));
173
    }
174 175
}

176 177
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Cargo {
178
    stage: u32,
179
    host: Interned<String>,
180 181
}

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

186 187
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/cargo")
188 189
    }

190 191 192 193
    fn make_run(run: RunConfig) {
        run.builder.ensure(Cargo {
            stage: run.builder.top_stage,
            host: run.target,
194 195
        });
    }
196 197 198 199

    /// Runs `cargo test` for `cargo` packaged with Rust.
    fn run(self, builder: &Builder) {
        let build = builder.build;
200
        let compiler = builder.compiler(self.stage, self.host);
201

202
        builder.ensure(tool::Cargo { compiler, target: self.host });
203
        let mut cargo = builder.cargo(compiler, Mode::Tool, self.host, "test");
204 205 206 207
        cargo.arg("--manifest-path").arg(build.src.join("src/tools/cargo/Cargo.toml"));
        if !build.fail_fast {
            cargo.arg("--no-fail-fast");
        }
208

209 210 211 212 213 214
        // Don't build tests dynamically, just a pain to work with
        cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");

        // Don't run cross-compile tests, we may not have cross-compiled libstd libs
        // available.
        cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
215

M
Mark Simulacrum 已提交
216
        try_run(build, cargo.env("PATH", &path_for_cargo(builder, compiler)));
217
    }
N
Nick Cameron 已提交
218 219
}

M
Mark Simulacrum 已提交
220 221
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Rls {
222
    stage: u32,
M
Mark Simulacrum 已提交
223
    host: Interned<String>,
224
}
N
Nick Cameron 已提交
225

M
Mark Simulacrum 已提交
226
impl Step for Rls {
227
    type Output = ();
M
Mark Simulacrum 已提交
228 229
    const ONLY_HOSTS: bool = true;

230 231
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/rls")
M
Mark Simulacrum 已提交
232 233
    }

234 235 236 237
    fn make_run(run: RunConfig) {
        run.builder.ensure(Rls {
            stage: run.builder.top_stage,
            host: run.target,
M
Mark Simulacrum 已提交
238 239
        });
    }
N
Nick Cameron 已提交
240

241 242 243 244 245
    /// Runs `cargo test` for the rls.
    fn run(self, builder: &Builder) {
        let build = builder.build;
        let stage = self.stage;
        let host = self.host;
M
Mark Simulacrum 已提交
246
        let compiler = builder.compiler(stage, host);
N
Nick Cameron 已提交
247

248
        builder.ensure(tool::Rls { compiler, target: self.host, extra_features: Vec::new() });
O
Oliver Schneider 已提交
249 250 251 252 253
        let mut cargo = tool::prepare_tool_cargo(builder,
                                                 compiler,
                                                 host,
                                                 "test",
                                                 "src/tools/rls");
N
Nick Cameron 已提交
254

255 256 257
        // Don't build tests dynamically, just a pain to work with
        cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");

M
Mark Simulacrum 已提交
258
        builder.add_rustc_lib_path(compiler, &mut cargo);
259

260
        if try_run(build, &mut cargo) {
261
            build.save_toolstate("rls", ToolState::TestPass);
O
Oliver Schneider 已提交
262
        }
263
    }
N
Nick Cameron 已提交
264 265
}

N
Nick Cameron 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Rustfmt {
    stage: u32,
    host: Interned<String>,
}

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

    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/rustfmt")
    }

    fn make_run(run: RunConfig) {
        run.builder.ensure(Rustfmt {
            stage: run.builder.top_stage,
            host: run.target,
        });
    }

    /// Runs `cargo test` for rustfmt.
    fn run(self, builder: &Builder) {
        let build = builder.build;
        let stage = self.stage;
        let host = self.host;
        let compiler = builder.compiler(stage, host);

294
        builder.ensure(tool::Rustfmt { compiler, target: self.host, extra_features: Vec::new() });
O
Oliver Schneider 已提交
295 296 297 298 299
        let mut cargo = tool::prepare_tool_cargo(builder,
                                                 compiler,
                                                 host,
                                                 "test",
                                                 "src/tools/rustfmt");
N
Nick Cameron 已提交
300 301 302 303 304 305

        // Don't build tests dynamically, just a pain to work with
        cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");

        builder.add_rustc_lib_path(compiler, &mut cargo);

306
        if try_run(build, &mut cargo) {
307
            build.save_toolstate("rustfmt", ToolState::TestPass);
O
Oliver Schneider 已提交
308
        }
N
Nick Cameron 已提交
309 310
    }
}
O
Oliver Schneider 已提交
311 312

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
313
pub struct Miri {
O
Oliver Schneider 已提交
314
    stage: u32,
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    host: Interned<String>,
}

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

    fn should_run(run: ShouldRun) -> ShouldRun {
        let test_miri = run.builder.build.config.test_miri;
        run.path("src/tools/miri").default_condition(test_miri)
    }

    fn make_run(run: RunConfig) {
        run.builder.ensure(Miri {
O
Oliver Schneider 已提交
330
            stage: run.builder.top_stage,
331 332 333 334 335 336 337
            host: run.target,
        });
    }

    /// Runs `cargo test` for miri.
    fn run(self, builder: &Builder) {
        let build = builder.build;
O
Oliver Schneider 已提交
338
        let stage = self.stage;
339
        let host = self.host;
O
Oliver Schneider 已提交
340
        let compiler = builder.compiler(stage, host);
341

342 343 344 345 346 347
        let miri = builder.ensure(tool::Miri {
            compiler,
            target: self.host,
            extra_features: Vec::new(),
        });
        if let Some(miri) = miri {
O
Oliver Schneider 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360
            let mut cargo = builder.cargo(compiler, Mode::Tool, host, "test");
            cargo.arg("--manifest-path").arg(build.src.join("src/tools/miri/Cargo.toml"));

            // Don't build tests dynamically, just a pain to work with
            cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
            // miri tests need to know about the stage sysroot
            cargo.env("MIRI_SYSROOT", builder.sysroot(compiler));
            cargo.env("RUSTC_TEST_SUITE", builder.rustc(compiler));
            cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
            cargo.env("MIRI_PATH", miri);

            builder.add_rustc_lib_path(compiler, &mut cargo);

361
            if try_run(build, &mut cargo) {
362
                build.save_toolstate("miri", ToolState::TestPass);
O
Oliver Schneider 已提交
363 364 365 366
            }
        } else {
            eprintln!("failed to test miri: could not build");
        }
367 368 369
    }
}

370 371
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Clippy {
O
Oliver Schneider 已提交
372
    stage: u32,
373 374 375 376 377 378 379 380 381 382 383 384 385 386
    host: Interned<String>,
}

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

    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/clippy")
    }

    fn make_run(run: RunConfig) {
        run.builder.ensure(Clippy {
O
Oliver Schneider 已提交
387
            stage: run.builder.top_stage,
388 389 390 391 392 393 394
            host: run.target,
        });
    }

    /// Runs `cargo test` for clippy.
    fn run(self, builder: &Builder) {
        let build = builder.build;
O
Oliver Schneider 已提交
395
        let stage = self.stage;
396
        let host = self.host;
O
Oliver Schneider 已提交
397
        let compiler = builder.compiler(stage, host);
398

399 400 401 402 403 404
        let clippy = builder.ensure(tool::Clippy {
            compiler,
            target: self.host,
            extra_features: Vec::new(),
        });
        if let Some(clippy) = clippy {
O
Oliver Schneider 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
            let mut cargo = builder.cargo(compiler, Mode::Tool, host, "test");
            cargo.arg("--manifest-path").arg(build.src.join("src/tools/clippy/Cargo.toml"));

            // Don't build tests dynamically, just a pain to work with
            cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
            // 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::Tool).join(builder.cargo_dir());
            cargo.env("HOST_LIBS", host_libs);
            // clippy tests need to find the driver
            cargo.env("CLIPPY_DRIVER_PATH", clippy);

            builder.add_rustc_lib_path(compiler, &mut cargo);

421
            if try_run(build, &mut cargo) {
422
                build.save_toolstate("clippy-driver", ToolState::TestPass);
O
Oliver Schneider 已提交
423 424 425 426
            }
        } else {
            eprintln!("failed to test clippy: could not build");
        }
427 428
    }
}
N
Nick Cameron 已提交
429

M
Mark Simulacrum 已提交
430
fn path_for_cargo(builder: &Builder, compiler: Compiler) -> OsString {
N
Nick Cameron 已提交
431 432 433
    // 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`.
M
Mark Simulacrum 已提交
434
    let path = builder.sysroot(compiler).join("bin");
N
Nick Cameron 已提交
435 436
    let old_path = env::var_os("PATH").unwrap_or_default();
    env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
437
}
438

G
Guillaume Gomez 已提交
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
#[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;

    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/rustdoc-themes")
    }

    fn make_run(run: RunConfig) {
        let compiler = run.builder.compiler(run.builder.top_stage, run.host);

        run.builder.ensure(RustdocTheme {
            compiler: compiler,
        });
    }

    fn run(self, builder: &Builder) {
        let rustdoc = builder.rustdoc(self.compiler.host);
G
Guillaume Gomez 已提交
463 464 465 466
        let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
        cmd.arg(rustdoc.to_str().unwrap())
           .arg(builder.src.join("src/librustdoc/html/static/themes").to_str().unwrap())
           .env("RUSTC_STAGE", self.compiler.stage.to_string())
G
Guillaume Gomez 已提交
467 468 469
           .env("RUSTC_SYSROOT", builder.sysroot(self.compiler))
           .env("RUSTDOC_LIBDIR", builder.sysroot_libdir(self.compiler, self.compiler.host))
           .env("CFG_RELEASE_CHANNEL", &builder.build.config.channel)
G
Guillaume Gomez 已提交
470
           .env("RUSTDOC_REAL", builder.rustdoc(self.compiler.host))
G
Guillaume Gomez 已提交
471 472
           .env("RUSTDOC_CRATE_VERSION", builder.build.rust_version())
           .env("RUSTC_BOOTSTRAP", "1");
G
Guillaume Gomez 已提交
473
        if let Some(linker) = builder.build.linker(self.compiler.host) {
G
Guillaume Gomez 已提交
474 475
            cmd.env("RUSTC_TARGET_LINKER", linker);
        }
G
Guillaume Gomez 已提交
476
        try_run(builder.build, &mut cmd);
G
Guillaume Gomez 已提交
477 478 479
    }
}

G
Guillaume Gomez 已提交
480 481 482
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RustdocJS {
    pub host: Interned<String>,
483
    pub target: Interned<String>,
G
Guillaume Gomez 已提交
484 485 486
}

impl Step for RustdocJS {
487
    type Output = ();
G
Guillaume Gomez 已提交
488 489 490 491
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

    fn should_run(run: ShouldRun) -> ShouldRun {
492
        run.path("src/test/rustdoc-js")
G
Guillaume Gomez 已提交
493 494 495 496 497
    }

    fn make_run(run: RunConfig) {
        run.builder.ensure(RustdocJS {
            host: run.host,
498
            target: run.target,
G
Guillaume Gomez 已提交
499 500 501
        });
    }

502
    fn run(self, builder: &Builder) {
503 504 505 506 507 508 509 510 511
        if let Some(ref nodejs) = builder.config.nodejs {
            let mut command = Command::new(nodejs);
            command.args(&["src/tools/rustdoc-js/tester.js", &*self.host]);
            builder.ensure(::doc::Std {
                target: self.target,
                stage: builder.top_stage,
            });
            builder.run(&mut command);
        } else {
512
            builder.info(&format!("No nodejs found, skipping \"src/test/rustdoc-js\" tests"));
513
        }
G
Guillaume Gomez 已提交
514 515 516
    }
}

517
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
M
Mark Simulacrum 已提交
518
pub struct Tidy;
519

520
impl Step for Tidy {
521
    type Output = ();
522 523
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;
524

M
Mark Simulacrum 已提交
525
    /// Runs the `tidy` tool.
526 527 528 529 530 531 532
    ///
    /// 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.
    fn run(self, builder: &Builder) {
        let build = builder.build;

533
        let mut cmd = builder.tool_cmd(Tool::Tidy);
534
        cmd.arg(build.src.join("src"));
535
        cmd.arg(&build.initial_cargo);
536 537 538 539 540 541
        if !build.config.vendor {
            cmd.arg("--no-vendor");
        }
        if build.config.quiet_tests {
            cmd.arg("--quiet");
        }
542 543

        let _folder = build.fold_output(|| "tidy");
544
        builder.info(&format!("tidy check"));
545
        try_run(build, &mut cmd);
546
    }
547

548 549
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/tidy")
550 551
    }

552
    fn make_run(run: RunConfig) {
M
Mark Simulacrum 已提交
553
        run.builder.ensure(Tidy);
554
    }
555
}
556

557
fn testdir(build: &Build, host: Interned<String>) -> PathBuf {
558 559 560
    build.out.join(host).join("test")
}

561 562 563 564
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 });
    }
565 566
}

567 568 569 570
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 });
    }
571 572
}

573 574 575 576 577 578 579 580 581 582 583 584
macro_rules! test {
    ($name:ident {
        path: $path:expr,
        mode: $mode:expr,
        suite: $suite:expr,
        default: $default:expr,
        host: $host:expr
    }) => {
        #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
        pub struct $name {
            pub compiler: Compiler,
            pub target: Interned<String>,
585 586
        }

587 588 589 590
        impl Step for $name {
            type Output = ();
            const DEFAULT: bool = $default;
            const ONLY_HOSTS: bool = $host;
591

592 593
            fn should_run(run: ShouldRun) -> ShouldRun {
                run.path($path)
594
            }
595

596 597
            fn make_run(run: RunConfig) {
                let compiler = run.builder.compiler(run.builder.top_stage, run.host);
598

599
                run.builder.ensure($name {
600
                    compiler,
601
                    target: run.target,
602 603
                });
            }
604

605 606 607 608 609 610 611 612 613
            fn run(self, builder: &Builder) {
                builder.ensure(Compiletest {
                    compiler: self.compiler,
                    target: self.target,
                    mode: $mode,
                    suite: $suite,
                })
            }
        }
614 615 616
    }
}

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 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
default_test!(Ui {
    path: "src/test/ui",
    mode: "ui",
    suite: "ui"
});

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

default_test!(CompileFail {
    path: "src/test/compile-fail",
    mode: "compile-fail",
    suite: "compile-fail"
});

default_test!(ParseFail {
    path: "src/test/parse-fail",
    mode: "parse-fail",
    suite: "parse-fail"
});

default_test!(RunFail {
    path: "src/test/run-fail",
    mode: "run-fail",
    suite: "run-fail"
});

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

default_test!(MirOpt {
    path: "src/test/mir-opt",
    mode: "mir-opt",
    suite: "mir-opt"
});

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

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

default_test!(Debuginfo {
    path: "src/test/debuginfo",
    // What this runs varies depending on the native platform being apple
    mode: "debuginfo-XXX",
    suite: "debuginfo"
});

host_test!(UiFullDeps {
    path: "src/test/ui-fulldeps",
    mode: "ui",
    suite: "ui-fulldeps"
});

host_test!(RunPassFullDeps {
    path: "src/test/run-pass-fulldeps",
    mode: "run-pass",
    suite: "run-pass-fulldeps"
});

host_test!(RunFailFullDeps {
    path: "src/test/run-fail-fulldeps",
    mode: "run-fail",
    suite: "run-fail-fulldeps"
});

host_test!(CompileFailFullDeps {
    path: "src/test/compile-fail-fulldeps",
    mode: "compile-fail",
    suite: "compile-fail-fulldeps"
});

host_test!(IncrementalFullDeps {
    path: "src/test/incremental-fulldeps",
    mode: "incremental",
    suite: "incremental-fulldeps"
});

host_test!(Rustdoc {
    path: "src/test/rustdoc",
    mode: "rustdoc",
    suite: "rustdoc"
});

test!(Pretty {
    path: "src/test/pretty",
    mode: "pretty",
    suite: "pretty",
    default: false,
    host: true
});
test!(RunPassPretty {
    path: "src/test/run-pass/pretty",
    mode: "pretty",
    suite: "run-pass",
    default: false,
    host: true
});
test!(RunFailPretty {
    path: "src/test/run-fail/pretty",
    mode: "pretty",
    suite: "run-fail",
    default: false,
    host: true
});
test!(RunPassValgrindPretty {
    path: "src/test/run-pass-valgrind/pretty",
    mode: "pretty",
    suite: "run-pass-valgrind",
    default: false,
    host: true
});
test!(RunPassFullDepsPretty {
    path: "src/test/run-pass-fulldeps/pretty",
    mode: "pretty",
    suite: "run-pass-fulldeps",
    default: false,
    host: true
});
test!(RunFailFullDepsPretty {
    path: "src/test/run-fail-fulldeps/pretty",
    mode: "pretty",
    suite: "run-fail-fulldeps",
    default: false,
    host: true
});

763
default_test!(RunMake {
764 765 766 767 768
    path: "src/test/run-make",
    mode: "run-make",
    suite: "run-make"
});

769 770 771 772 773 774
host_test!(RunMakeFullDeps {
    path: "src/test/run-make-fulldeps",
    mode: "run-make",
    suite: "run-make-fulldeps"
});

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
struct Compiletest {
    compiler: Compiler,
    target: Interned<String>,
    mode: &'static str,
    suite: &'static str,
}

impl Step for Compiletest {
    type Output = ();

    fn should_run(run: ShouldRun) -> ShouldRun {
        run.never()
    }

790 791 792 793 794 795 796 797 798 799 800
    /// 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`.
    fn run(self, builder: &Builder) {
        let build = builder.build;
        let compiler = self.compiler;
        let target = self.target;
        let mode = self.mode;
        let suite = self.suite;
801 802 803 804 805 806 807

        // Skip codegen tests if they aren't enabled in configuration.
        if !build.config.codegen_tests && suite == "codegen" {
            return;
        }

        if suite == "debuginfo" {
808 809 810 811 812
            // Skip debuginfo tests on MSVC
            if build.build.contains("msvc") {
                return;
            }

813 814 815 816 817
            if mode == "debuginfo-XXX" {
                return if build.build.contains("apple") {
                    builder.ensure(Compiletest {
                        mode: "debuginfo-lldb",
                        ..self
818
                    });
819 820 821 822
                } else {
                    builder.ensure(Compiletest {
                        mode: "debuginfo-gdb",
                        ..self
823
                    });
824 825 826 827
                };
            }

            builder.ensure(dist::DebuggerScripts {
828
                sysroot: builder.sysroot(compiler),
829
                host: target
830 831 832 833 834 835 836
            });
        }

        if suite.ends_with("fulldeps") ||
            // FIXME: Does pretty need librustc compiled? Note that there are
            // fulldeps test suites with mode = pretty as well.
            mode == "pretty" ||
837
            mode == "rustdoc" {
838 839 840 841 842
            builder.ensure(compile::Rustc { compiler, target });
        }

        builder.ensure(compile::Test { compiler, target });
        builder.ensure(native::TestHelpers { target });
843
        builder.ensure(RemoteCopyLibs { compiler, target });
844 845

        let mut cmd = builder.tool_cmd(Tool::Compiletest);
846 847 848 849

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

850
        cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
851
        cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
852
        cmd.arg("--rustc-path").arg(builder.rustc(compiler));
853 854

        // Avoid depending on rustdoc when we don't need it.
855
        if mode == "rustdoc" || (mode == "run-make" && suite.ends_with("fulldeps")) {
856
            cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler.host));
857 858
        }

859 860 861 862 863
        cmd.arg("--src-base").arg(build.src.join("src/test").join(suite));
        cmd.arg("--build-base").arg(testdir(build, compiler.host).join(suite));
        cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
        cmd.arg("--mode").arg(mode);
        cmd.arg("--target").arg(target);
864 865
        cmd.arg("--host").arg(&*compiler.host);
        cmd.arg("--llvm-filecheck").arg(build.llvm_filecheck(build.build));
866 867 868 869

        if let Some(ref nodejs) = build.config.nodejs {
            cmd.arg("--nodejs").arg(nodejs);
        }
870

871 872 873 874 875 876 877
        let mut flags = vec!["-Crpath".to_string()];
        if build.config.rust_optimize_tests {
            flags.push("-O".to_string());
        }
        if build.config.rust_debuginfo_tests {
            flags.push("-g".to_string());
        }
878
        flags.push("-Zmiri -Zunstable-options".to_string());
879
        flags.push(build.config.cmd.rustc_args().join(" "));
880

O
Oliver Schneider 已提交
881 882 883 884 885
        if let Some(linker) = build.linker(target) {
            cmd.arg("--linker").arg(linker);
        }

        let hostflags = flags.clone();
886 887
        cmd.arg("--host-rustcflags").arg(hostflags.join(" "));

O
Oliver Schneider 已提交
888
        let mut targetflags = flags.clone();
889 890 891 892 893 894 895 896 897 898 899 900 901 902
        targetflags.push(format!("-Lnative={}",
                                 build.test_helpers_out(target).display()));
        cmd.arg("--target-rustcflags").arg(targetflags.join(" "));

        cmd.arg("--docck-python").arg(build.python());

        if build.build.ends_with("apple-darwin") {
            // Force /usr/bin/python on macOS for LLDB tests because we're loading the
            // LLDB plugin's compiled module which only works with the system python
            // (namely not Homebrew-installed python)
            cmd.arg("--lldb-python").arg("/usr/bin/python");
        } else {
            cmd.arg("--lldb-python").arg(build.python());
        }
903

904 905 906 907 908 909 910 911 912
        if let Some(ref gdb) = build.config.gdb {
            cmd.arg("--gdb").arg(gdb);
        }
        if let Some(ref vers) = build.lldb_version {
            cmd.arg("--lldb-version").arg(vers);
        }
        if let Some(ref dir) = build.lldb_python_dir {
            cmd.arg("--lldb-python-dir").arg(dir);
        }
913

M
Mark Simulacrum 已提交
914
        cmd.args(&build.config.cmd.test_args());
915

916 917 918
        if build.is_verbose() {
            cmd.arg("--verbose");
        }
919

920 921 922
        if build.config.quiet_tests {
            cmd.arg("--quiet");
        }
923

B
bjorn3 已提交
924
        if build.config.llvm_enabled {
925 926 927 928
            let llvm_config = builder.ensure(native::Llvm {
                target: build.config.build,
                emscripten: false,
            });
B
bjorn3 已提交
929 930 931 932 933 934 935 936
            let llvm_version = output(Command::new(&llvm_config).arg("--version"));
            cmd.arg("--llvm-version").arg(llvm_version);
            if !build.is_rust_llvm(target) {
                cmd.arg("--system-llvm");
            }

            // 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.
937
            if suite == "run-make-fulldeps" {
B
bjorn3 已提交
938 939 940 941 942 943 944
                let llvm_components = output(Command::new(&llvm_config).arg("--components"));
                let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
                cmd.arg("--cc").arg(build.cc(target))
                .arg("--cxx").arg(build.cxx(target).unwrap())
                .arg("--cflags").arg(build.cflags(target).join(" "))
                .arg("--llvm-components").arg(llvm_components.trim())
                .arg("--llvm-cxxflags").arg(llvm_cxxflags.trim());
O
Oliver Schneider 已提交
945 946 947
                if let Some(ar) = build.ar(target) {
                    cmd.arg("--ar").arg(ar);
                }
B
bjorn3 已提交
948 949
            }
        }
950
        if suite == "run-make-fulldeps" && !build.config.llvm_enabled {
951 952
            builder.info(
                &format!("Ignoring run-make test suite as they generally don't work without LLVM"));
B
bjorn3 已提交
953 954 955
            return;
        }

956
        if suite != "run-make-fulldeps" {
957 958 959 960 961 962
            cmd.arg("--cc").arg("")
               .arg("--cxx").arg("")
               .arg("--cflags").arg("")
               .arg("--llvm-components").arg("")
               .arg("--llvm-cxxflags").arg("");
        }
963

964
        if build.remote_tested(target) {
965
            cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
966
        }
967

968 969 970 971 972 973
        // 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") {
O
Oliver Schneider 已提交
974
            for &(ref k, ref v) in build.cc[&target].env() {
975 976 977
                if k != "PATH" {
                    cmd.env(k, v);
                }
978 979
            }
        }
980 981
        cmd.env("RUSTC_BOOTSTRAP", "1");
        build.add_rust_test_threads(&mut cmd);
982

983 984 985
        if build.config.sanitizers {
            cmd.env("SANITIZER_SUPPORT", "1");
        }
986

987 988 989
        if build.config.profiler {
            cmd.env("PROFILER_SUPPORT", "1");
        }
990

991 992
        cmd.env("RUST_TEST_TMPDIR", build.out.join("tmp"));

993 994 995 996 997 998 999 1000 1001
        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")
               .arg(build.cc(target).parent().unwrap().parent().unwrap());
        } else {
            cmd.arg("--android-cross-path").arg("");
        }
1002

1003
        build.ci_env.force_coloring_in_ci(&mut cmd);
1004

1005
        let _folder = build.fold_output(|| format!("test_{}", suite));
1006 1007 1008
        builder.info(&format!("Check compiletest suite={} mode={} ({} -> {})",
                 suite, mode, &compiler.host, target));
        let _time = util::timeit(&build);
1009 1010
        try_run(build, &mut cmd);
    }
1011
}
1012

1013
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1014
struct DocTest {
1015
    compiler: Compiler,
1016 1017 1018
    path: &'static str,
    name: &'static str,
    is_ext_doc: bool,
1019 1020
}

1021
impl Step for DocTest {
1022 1023
    type Output = ();
    const ONLY_HOSTS: bool = true;
1024

1025
    fn should_run(run: ShouldRun) -> ShouldRun {
1026
        run.never()
1027
    }
M
Mark Simulacrum 已提交
1028

1029 1030 1031 1032 1033 1034 1035 1036
    /// Run `rustdoc --test` for all documentation in `src/doc`.
    ///
    /// This will run all tests in our markdown documentation (e.g. the book)
    /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to
    /// `compiler`.
    fn run(self, builder: &Builder) {
        let build = builder.build;
        let compiler = self.compiler;
1037 1038 1039

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

1040 1041
        // Do a breadth-first traversal of the `src/doc` directory and just run
        // tests for all files that end in `*.md`
1042
        let mut stack = vec![build.src.join(self.path)];
1043
        let _time = util::timeit(&build);
1044
        let _folder = build.fold_output(|| format!("test_{}", self.name));
1045

1046
        let mut files = Vec::new();
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
        while let Some(p) = stack.pop() {
            if p.is_dir() {
                stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
                continue
            }

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

            // The nostarch directory in the book is for no starch, and so isn't
            // guaranteed to build. We don't care if it doesn't build, so skip it.
            if p.to_str().map_or(false, |p| p.contains("nostarch")) {
                continue;
            }

1063 1064 1065 1066 1067 1068 1069
            files.push(p);
        }

        files.sort();

        for file in files {
            let test_result = markdown_test(builder, compiler, &file);
1070 1071 1072 1073 1074 1075 1076 1077
            if self.is_ext_doc {
                let toolstate = if test_result {
                    ToolState::TestPass
                } else {
                    ToolState::TestFail
                };
                build.save_toolstate(self.name, toolstate);
            }
1078
        }
1079 1080 1081
    }
}

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
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;

                fn should_run(run: ShouldRun) -> ShouldRun {
                    run.path($path)
                }

                fn make_run(run: RunConfig) {
                    run.builder.ensure($name {
                        compiler: run.builder.compiler(run.builder.top_stage, run.host),
                    });
                }

                fn run(self, builder: &Builder) {
                    builder.ensure(DocTest {
                        compiler: self.compiler,
                        path: $path,
                        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;
    RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
    TheBook, "src/doc/book", "book", default=false;
    UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
);

1127 1128 1129
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct ErrorIndex {
    compiler: Compiler,
1130
}
1131

1132
impl Step for ErrorIndex {
1133
    type Output = ();
1134 1135 1136
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

1137 1138
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/error_index_generator")
1139 1140
    }

1141 1142 1143
    fn make_run(run: RunConfig) {
        run.builder.ensure(ErrorIndex {
            compiler: run.builder.compiler(run.builder.top_stage, run.host),
1144 1145
        });
    }
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156

    /// Run the error index generator tool to execute the tests located in the error
    /// 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`.
    fn run(self, builder: &Builder) {
        let build = builder.build;
        let compiler = self.compiler;

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

1159 1160 1161 1162
        let dir = testdir(build, compiler.host);
        t!(fs::create_dir_all(&dir));
        let output = dir.join("error-index.md");

1163 1164 1165 1166 1167 1168
        let mut tool = builder.tool_cmd(Tool::ErrorIndex);
        tool.arg("markdown")
            .arg(&output)
            .env("CFG_BUILD", &build.build)
            .env("RUSTC_ERROR_METADATA_DST", build.extended_error_dir());

1169

1170
        let _folder = build.fold_output(|| "test_error_index");
1171 1172
        build.info(&format!("Testing error-index stage{}", compiler.stage));
        let _time = util::timeit(&build);
1173
        build.run(&mut tool);
1174
        markdown_test(builder, compiler, &output);
1175
    }
1176 1177
}

1178
fn markdown_test(builder: &Builder, compiler: Compiler, markdown: &Path) -> bool {
1179
    let build = builder.build;
1180 1181 1182 1183
    let mut file = t!(File::open(markdown));
    let mut contents = String::new();
    t!(file.read_to_string(&mut contents));
    if !contents.contains("```") {
1184
        return true;
1185 1186
    }

1187
    build.info(&format!("doc tests for: {}", markdown.display()));
1188
    let mut cmd = builder.rustdoc_cmd(compiler.host);
1189
    build.add_rust_test_threads(&mut cmd);
1190 1191
    cmd.arg("--test");
    cmd.arg(markdown);
1192
    cmd.env("RUSTC_BOOTSTRAP", "1");
1193

M
Mark Simulacrum 已提交
1194
    let test_args = build.config.cmd.test_args().join(" ");
1195 1196
    cmd.arg("--test-args").arg(test_args);

1197
    if build.config.quiet_tests {
1198
        try_run_quiet(build, &mut cmd)
1199
    } else {
1200
        try_run(build, &mut cmd)
1201
    }
1202
}
1203

1204
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
M
Mark Simulacrum 已提交
1205
pub struct CrateLibrustc {
1206 1207
    compiler: Compiler,
    target: Interned<String>,
1208
    test_kind: TestKind,
1209
    krate: Interned<String>,
1210 1211
}

M
Mark Simulacrum 已提交
1212
impl Step for CrateLibrustc {
1213 1214 1215 1216
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

1217 1218
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.krate("rustc-main")
1219 1220
    }

1221 1222 1223
    fn make_run(run: RunConfig) {
        let builder = run.builder;
        let compiler = builder.compiler(builder.top_stage, run.host);
1224

1225 1226 1227 1228 1229 1230 1231 1232 1233
        for krate in builder.in_tree_crates("rustc-main") {
            if run.path.ends_with(&krate.path) {
                let test_kind = if builder.kind == Kind::Test {
                    TestKind::Test
                } else if builder.kind == Kind::Bench {
                    TestKind::Bench
                } else {
                    panic!("unexpected builder.kind in crate: {:?}", builder.kind);
                };
1234

1235 1236 1237 1238 1239 1240
                builder.ensure(CrateLibrustc {
                    compiler,
                    target: run.target,
                    test_kind,
                    krate: krate.name,
                });
1241 1242 1243 1244 1245
            }
        }
    }

    fn run(self, builder: &Builder) {
M
Mark Simulacrum 已提交
1246
        builder.ensure(Crate {
1247 1248 1249 1250 1251 1252 1253 1254 1255
            compiler: self.compiler,
            target: self.target,
            mode: Mode::Librustc,
            test_kind: self.test_kind,
            krate: self.krate,
        });
    }
}

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct CrateNotDefault {
    compiler: Compiler,
    target: Interned<String>,
    test_kind: TestKind,
    krate: &'static str,
}

impl Step for CrateNotDefault {
    type Output = ();

    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/liballoc_jemalloc")
            .path("src/librustc_asan")
            .path("src/librustc_lsan")
            .path("src/librustc_msan")
            .path("src/librustc_tsan")
    }

    fn make_run(run: RunConfig) {
        let builder = run.builder;
        let compiler = builder.compiler(builder.top_stage, run.host);

        let test_kind = if builder.kind == Kind::Test {
            TestKind::Test
        } else if builder.kind == Kind::Bench {
            TestKind::Bench
        } else {
            panic!("unexpected builder.kind in crate: {:?}", builder.kind);
        };

        builder.ensure(CrateNotDefault {
            compiler,
            target: run.target,
            test_kind,
            krate: match run.path {
                _ if run.path.ends_with("src/liballoc_jemalloc") => "alloc_jemalloc",
                _ if run.path.ends_with("src/librustc_asan") => "rustc_asan",
                _ if run.path.ends_with("src/librustc_lsan") => "rustc_lsan",
                _ if run.path.ends_with("src/librustc_msan") => "rustc_msan",
                _ if run.path.ends_with("src/librustc_tsan") => "rustc_tsan",
                _ => panic!("unexpected path {:?}", run.path),
            },
        });
    }

    fn run(self, builder: &Builder) {
        builder.ensure(Crate {
            compiler: self.compiler,
            target: self.target,
            mode: Mode::Libstd,
            test_kind: self.test_kind,
            krate: INTERNER.intern_str(self.krate),
        });
    }
}


1314
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
M
Mark Simulacrum 已提交
1315
pub struct Crate {
1316 1317
    compiler: Compiler,
    target: Interned<String>,
1318 1319
    mode: Mode,
    test_kind: TestKind,
1320
    krate: Interned<String>,
1321
}
1322

M
Mark Simulacrum 已提交
1323
impl Step for Crate {
1324
    type Output = ();
1325 1326
    const DEFAULT: bool = true;

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
    fn should_run(mut run: ShouldRun) -> ShouldRun {
        let builder = run.builder;
        run = run.krate("test");
        for krate in run.builder.in_tree_crates("std") {
            if krate.is_local(&run.builder) &&
                !krate.name.contains("jemalloc") &&
                !(krate.name.starts_with("rustc_") && krate.name.ends_with("san")) &&
                krate.name != "dlmalloc" {
                run = run.path(krate.local_path(&builder).to_str().unwrap());
            }
        }
        run
1339 1340
    }

1341 1342 1343
    fn make_run(run: RunConfig) {
        let builder = run.builder;
        let compiler = builder.compiler(builder.top_stage, run.host);
1344

1345
        let make = |mode: Mode, krate: &CargoCrate| {
1346 1347 1348 1349 1350
            let test_kind = if builder.kind == Kind::Test {
                TestKind::Test
            } else if builder.kind == Kind::Bench {
                TestKind::Bench
            } else {
M
Mark Simulacrum 已提交
1351
                panic!("unexpected builder.kind in crate: {:?}", builder.kind);
1352 1353
            };

M
Mark Simulacrum 已提交
1354
            builder.ensure(Crate {
1355 1356
                compiler,
                target: run.target,
1357 1358
                mode,
                test_kind,
1359
                krate: krate.name,
1360 1361 1362
            });
        };

1363 1364 1365
        for krate in builder.in_tree_crates("std") {
            if run.path.ends_with(&krate.local_path(&builder)) {
                make(Mode::Libstd, krate);
1366
            }
1367 1368 1369 1370
        }
        for krate in builder.in_tree_crates("test") {
            if run.path.ends_with(&krate.local_path(&builder)) {
                make(Mode::Libtest, krate);
1371 1372 1373
            }
        }
    }
1374

1375 1376
    /// Run all unit tests plus documentation tests for a given crate defined
    /// by a `Cargo.toml` (single manifest)
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
    ///
    /// 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`.
    fn run(self, builder: &Builder) {
        let build = builder.build;
        let compiler = self.compiler;
        let target = self.target;
        let mode = self.mode;
        let test_kind = self.test_kind;
        let krate = self.krate;

1391 1392
        builder.ensure(compile::Test { compiler, target });
        builder.ensure(RemoteCopyLibs { compiler, target });
A
Alex Crichton 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

        // 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 = if build.force_use_stage1(compiler, target) {
            builder.compiler(1, compiler.host)
        } else {
            compiler.clone()
        };

        let mut cargo = builder.cargo(compiler, mode, target, test_kind.subcommand());
1405
        match mode {
1406
            Mode::Libstd => {
1407
                compile::std_cargo(builder, &compiler, target, &mut cargo);
1408 1409
            }
            Mode::Libtest => {
A
Alex Crichton 已提交
1410
                compile::test_cargo(build, &compiler, target, &mut cargo);
1411 1412
            }
            Mode::Librustc => {
1413
                builder.ensure(compile::Rustc { compiler, target });
1414
                compile::rustc_cargo(build, &mut cargo);
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
            }
            _ => 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.
        if test_kind.subcommand() == "test" && !build.fail_fast {
            cargo.arg("--no-fail-fast");
        }
1427 1428 1429
        if build.doc_tests {
            cargo.arg("--doc");
        }
1430

1431
        cargo.arg("-p").arg(krate);
1432

1433 1434 1435 1436 1437 1438
        // 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();
1439
        dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1440 1441 1442
        cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());

        cargo.arg("--");
M
Mark Simulacrum 已提交
1443
        cargo.args(&build.config.cmd.test_args());
1444

1445 1446 1447
        if build.config.quiet_tests {
            cargo.arg("--quiet");
        }
1448

1449
        if target.contains("emscripten") {
1450 1451
            cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target)),
                      build.config.nodejs.as_ref().expect("nodejs not configured"));
O
Oliver Schneider 已提交
1452
        } else if target.starts_with("wasm32") {
1453 1454 1455 1456
            // Warn about running tests without the `wasm_syscall` feature enabled.
            // The javascript shim implements the syscall interface so that test
            // output can be correctly reported.
            if !build.config.wasm_syscall {
1457 1458
                build.info(&format!("Libstd was built without `wasm_syscall` feature enabled: \
                          test output may not be visible."));
1459 1460
            }

O
Oliver Schneider 已提交
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
            // On the wasm32-unknown-unknown target we're using LTO which is
            // incompatible with `-C prefer-dynamic`, so disable that here
            cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");

            let node = build.config.nodejs.as_ref()
                .expect("nodejs not configured");
            let runner = format!("{} {}/src/etc/wasm32-shim.js",
                                 node.display(),
                                 build.src.display());
            cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target)), &runner);
1471
        } else if build.remote_tested(target) {
1472 1473 1474
            cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target)),
                      format!("{} run",
                              builder.tool_exe(Tool::RemoteTestClient).display()));
1475
        }
1476 1477 1478 1479

        let _folder = build.fold_output(|| {
            format!("{}_stage{}-{}", test_kind.subcommand(), compiler.stage, krate)
        });
1480 1481 1482
        build.info(&format!("{} {} stage{} ({} -> {})", test_kind, krate, compiler.stage,
                &compiler.host, target));
        let _time = util::timeit(&build);
1483
        try_run(build, &mut cargo);
1484 1485
    }
}
1486

M
Mark Simulacrum 已提交
1487
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1488
pub struct CrateRustdoc {
M
Mark Simulacrum 已提交
1489 1490 1491 1492
    host: Interned<String>,
    test_kind: TestKind,
}

1493
impl Step for CrateRustdoc {
M
Mark Simulacrum 已提交
1494 1495 1496 1497 1498
    type Output = ();
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

    fn should_run(run: ShouldRun) -> ShouldRun {
1499
        run.paths(&["src/librustdoc", "src/tools/rustdoc"])
M
Mark Simulacrum 已提交
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
    }

    fn make_run(run: RunConfig) {
        let builder = run.builder;

        let test_kind = if builder.kind == Kind::Test {
            TestKind::Test
        } else if builder.kind == Kind::Bench {
            TestKind::Bench
        } else {
            panic!("unexpected builder.kind in crate: {:?}", builder.kind);
        };

1513
        builder.ensure(CrateRustdoc {
M
Mark Simulacrum 已提交
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
            host: run.host,
            test_kind,
        });
    }

    fn run(self, builder: &Builder) {
        let build = builder.build;
        let test_kind = self.test_kind;

        let compiler = builder.compiler(builder.top_stage, self.host);
        let target = compiler.host;

1526 1527 1528 1529 1530
        let mut cargo = tool::prepare_tool_cargo(builder,
                                                 compiler,
                                                 target,
                                                 test_kind.subcommand(),
                                                 "src/tools/rustdoc");
M
Mark Simulacrum 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
        if test_kind.subcommand() == "test" && !build.fail_fast {
            cargo.arg("--no-fail-fast");
        }

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

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

        if build.config.quiet_tests {
            cargo.arg("--quiet");
        }

1544 1545 1546
        let _folder = build.fold_output(|| {
            format!("{}_stage{}-rustdoc", test_kind.subcommand(), compiler.stage)
        });
1547 1548 1549
        build.info(&format!("{} rustdoc stage{} ({} -> {})", test_kind, compiler.stage,
                &compiler.host, target));
        let _time = util::timeit(&build);
M
Mark Simulacrum 已提交
1550 1551 1552 1553 1554

        try_run(build, &mut cargo);
    }
}

1555 1556 1557 1558 1559
fn envify(s: &str) -> String {
    s.chars().map(|c| {
        match c {
            '-' => '_',
            c => c,
1560
        }
1561
    }).flat_map(|c| c.to_uppercase()).collect()
1562 1563
}

1564 1565 1566 1567 1568 1569 1570 1571 1572
/// 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.
///
/// Most of the time this is a noop. For some steps such as shipping data to
/// 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.
1573 1574 1575 1576
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct RemoteCopyLibs {
    compiler: Compiler,
    target: Interned<String>,
1577
}
1578

1579
impl Step for RemoteCopyLibs {
1580
    type Output = ();
1581

1582 1583
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.never()
1584 1585
    }

1586 1587 1588 1589 1590 1591 1592 1593
    fn run(self, builder: &Builder) {
        let build = builder.build;
        let compiler = self.compiler;
        let target = self.target;
        if !build.remote_tested(target) {
            return
        }

1594 1595
        builder.ensure(compile::Test { compiler, target });

1596
        build.info(&format!("REMOTE copy libs to emulator ({})", target));
1597
        t!(fs::create_dir_all(build.out.join("tmp")));
1598

1599
        let server = builder.ensure(tool::RemoteTestServer { compiler, target });
1600 1601

        // Spawn the emulator and wait for it to come online
1602
        let tool = builder.tool_exe(Tool::RemoteTestClient);
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
        let mut cmd = Command::new(&tool);
        cmd.arg("spawn-emulator")
           .arg(target)
           .arg(&server)
           .arg(build.out.join("tmp"));
        if let Some(rootfs) = build.qemu_rootfs(target) {
            cmd.arg(rootfs);
        }
        build.run(&mut cmd);

        // Push all our dylibs to the emulator
1614
        for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
1615 1616 1617 1618 1619 1620 1621
            let f = t!(f);
            let name = f.file_name().into_string().unwrap();
            if util::is_dylib(&name) {
                build.run(Command::new(&tool)
                                  .arg("push")
                                  .arg(f.path()));
            }
1622 1623 1624 1625
        }
    }
}

1626
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1627
pub struct Distcheck;
A
Alex Crichton 已提交
1628

1629
impl Step for Distcheck {
1630 1631
    type Output = ();

1632 1633
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("distcheck")
1634 1635
    }

M
Mark Simulacrum 已提交
1636 1637 1638 1639
    fn make_run(run: RunConfig) {
        run.builder.ensure(Distcheck);
    }

1640 1641 1642 1643
    /// Run "distcheck", a 'make check' from a tarball
    fn run(self, builder: &Builder) {
        let build = builder.build;

1644
        build.info(&format!("Distcheck"));
1645 1646 1647 1648
        let dir = build.out.join("tmp").join("distcheck");
        let _ = fs::remove_dir_all(&dir);
        t!(fs::create_dir_all(&dir));

M
Mark Simulacrum 已提交
1649 1650 1651 1652
        // Guarantee that these are built before we begin running.
        builder.ensure(dist::PlainSourceTarball);
        builder.ensure(dist::Src);

1653 1654
        let mut cmd = Command::new("tar");
        cmd.arg("-xzf")
M
Mark Simulacrum 已提交
1655
           .arg(builder.ensure(dist::PlainSourceTarball))
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
           .arg("--strip-components=1")
           .current_dir(&dir);
        build.run(&mut cmd);
        build.run(Command::new("./configure")
                         .args(&build.config.configure_args)
                         .arg("--enable-vendor")
                         .current_dir(&dir));
        build.run(Command::new(build_helper::make(&build.build))
                         .arg("check")
                         .current_dir(&dir));

        // Now make sure that rust-src has all of libstd's dependencies
1668
        build.info(&format!("Distcheck rust-src"));
1669 1670 1671 1672 1673 1674
        let dir = build.out.join("tmp").join("distcheck-src");
        let _ = fs::remove_dir_all(&dir);
        t!(fs::create_dir_all(&dir));

        let mut cmd = Command::new("tar");
        cmd.arg("-xzf")
M
Mark Simulacrum 已提交
1675
           .arg(builder.ensure(dist::Src))
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
           .arg("--strip-components=1")
           .current_dir(&dir);
        build.run(&mut cmd);

        let toml = dir.join("rust-src/lib/rustlib/src/rust/src/libstd/Cargo.toml");
        build.run(Command::new(&build.initial_cargo)
                         .arg("generate-lockfile")
                         .arg("--manifest-path")
                         .arg(&toml)
                         .current_dir(&dir));
    }
A
Alex Crichton 已提交
1687
}
1688

1689
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1690 1691
pub struct Bootstrap;

1692
impl Step for Bootstrap {
1693
    type Output = ();
1694 1695
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;
1696 1697 1698 1699 1700 1701 1702

    /// Test the build system itself
    fn run(self, builder: &Builder) {
        let build = builder.build;
        let mut cmd = Command::new(&build.initial_cargo);
        cmd.arg("test")
           .current_dir(build.src.join("src/bootstrap"))
M
Mark Simulacrum 已提交
1703
           .env("RUSTFLAGS", "-Cdebuginfo=2")
1704 1705 1706
           .env("CARGO_TARGET_DIR", build.out.join("bootstrap"))
           .env("RUSTC_BOOTSTRAP", "1")
           .env("RUSTC", &build.initial_rustc);
1707 1708 1709 1710 1711 1712
        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);
        }
1713 1714 1715
        if !build.fail_fast {
            cmd.arg("--no-fail-fast");
        }
M
Mark Simulacrum 已提交
1716
        cmd.arg("--").args(&build.config.cmd.test_args());
1717
        try_run(build, &mut cmd);
1718
    }
1719

1720 1721
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/bootstrap")
1722 1723
    }

1724 1725
    fn make_run(run: RunConfig) {
        run.builder.ensure(Bootstrap);
1726
    }
1727
}