]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/test.rs
Auto merge of #96232 - sunfishcode:sunfishcode/io-safety-const-fns, r=joshtriplett
[rust.git] / src / bootstrap / test.rs
1 //! Implementation of the test-related targets of the build system.
2 //!
3 //! This file implements the various regression test suites that we execute on
4 //! our CI.
5
6 use std::env;
7 use std::ffi::OsString;
8 use std::fmt;
9 use std::fs;
10 use std::iter;
11 use std::path::{Path, PathBuf};
12 use std::process::{Command, Stdio};
13
14 use crate::builder::{Builder, Compiler, Kind, RunConfig, ShouldRun, Step};
15 use crate::cache::Interned;
16 use crate::compile;
17 use crate::config::TargetSelection;
18 use crate::dist;
19 use crate::flags::Subcommand;
20 use crate::native;
21 use crate::tool::{self, SourceType, Tool};
22 use crate::toolstate::ToolState;
23 use crate::util::{self, add_link_lib_path, dylib_path, dylib_path_var, output, t};
24 use crate::{envify, CLang, DocTests, GitRepo, Mode};
25
26 const ADB_TEST_DIR: &str = "/data/tmp/work";
27
28 /// The two modes of the test runner; tests or benchmarks.
29 #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, PartialOrd, Ord)]
30 pub enum TestKind {
31     /// Run `cargo test`.
32     Test,
33     /// Run `cargo bench`.
34     Bench,
35 }
36
37 impl From<Kind> for TestKind {
38     fn from(kind: Kind) -> Self {
39         match kind {
40             Kind::Test => TestKind::Test,
41             Kind::Bench => TestKind::Bench,
42             _ => panic!("unexpected kind in crate: {:?}", kind),
43         }
44     }
45 }
46
47 impl TestKind {
48     // Return the cargo subcommand for this test kind
49     fn subcommand(self) -> &'static str {
50         match self {
51             TestKind::Test => "test",
52             TestKind::Bench => "bench",
53         }
54     }
55 }
56
57 impl fmt::Display for TestKind {
58     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59         f.write_str(match *self {
60             TestKind::Test => "Testing",
61             TestKind::Bench => "Benchmarking",
62         })
63     }
64 }
65
66 fn try_run(builder: &Builder<'_>, cmd: &mut Command) -> bool {
67     if !builder.fail_fast {
68         if !builder.try_run(cmd) {
69             let mut failures = builder.delayed_failures.borrow_mut();
70             failures.push(format!("{:?}", cmd));
71             return false;
72         }
73     } else {
74         builder.run(cmd);
75     }
76     true
77 }
78
79 fn try_run_quiet(builder: &Builder<'_>, cmd: &mut Command) -> bool {
80     if !builder.fail_fast {
81         if !builder.try_run_quiet(cmd) {
82             let mut failures = builder.delayed_failures.borrow_mut();
83             failures.push(format!("{:?}", cmd));
84             return false;
85         }
86     } else {
87         builder.run_quiet(cmd);
88     }
89     true
90 }
91
92 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
93 pub struct Linkcheck {
94     host: TargetSelection,
95 }
96
97 impl Step for Linkcheck {
98     type Output = ();
99     const ONLY_HOSTS: bool = true;
100     const DEFAULT: bool = true;
101
102     /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
103     ///
104     /// This tool in `src/tools` will verify the validity of all our links in the
105     /// documentation to ensure we don't have a bunch of dead ones.
106     fn run(self, builder: &Builder<'_>) {
107         let host = self.host;
108         let hosts = &builder.hosts;
109         let targets = &builder.targets;
110
111         // if we have different hosts and targets, some things may be built for
112         // the host (e.g. rustc) and others for the target (e.g. std). The
113         // documentation built for each will contain broken links to
114         // docs built for the other platform (e.g. rustc linking to cargo)
115         if (hosts != targets) && !hosts.is_empty() && !targets.is_empty() {
116             panic!(
117                 "Linkcheck currently does not support builds with different hosts and targets.
118 You can skip linkcheck with --exclude src/tools/linkchecker"
119             );
120         }
121
122         builder.info(&format!("Linkcheck ({})", host));
123
124         // Test the linkchecker itself.
125         let bootstrap_host = builder.config.build;
126         let compiler = builder.compiler(0, bootstrap_host);
127         let cargo = tool::prepare_tool_cargo(
128             builder,
129             compiler,
130             Mode::ToolBootstrap,
131             bootstrap_host,
132             "test",
133             "src/tools/linkchecker",
134             SourceType::InTree,
135             &[],
136         );
137         try_run(builder, &mut cargo.into());
138
139         // Build all the default documentation.
140         builder.default_doc(&[]);
141
142         // Run the linkchecker.
143         let _time = util::timeit(&builder);
144         try_run(
145             builder,
146             builder.tool_cmd(Tool::Linkchecker).arg(builder.out.join(host.triple).join("doc")),
147         );
148     }
149
150     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
151         let builder = run.builder;
152         let run = run.path("src/tools/linkchecker");
153         run.default_condition(builder.config.docs)
154     }
155
156     fn make_run(run: RunConfig<'_>) {
157         run.builder.ensure(Linkcheck { host: run.target });
158     }
159 }
160
161 fn check_if_tidy_is_installed() -> bool {
162     Command::new("tidy")
163         .arg("--version")
164         .stdout(Stdio::null())
165         .status()
166         .map_or(false, |status| status.success())
167 }
168
169 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
170 pub struct HtmlCheck {
171     target: TargetSelection,
172 }
173
174 impl Step for HtmlCheck {
175     type Output = ();
176     const DEFAULT: bool = true;
177     const ONLY_HOSTS: bool = true;
178
179     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
180         let run = run.path("src/tools/html-checker");
181         run.lazy_default_condition(Box::new(check_if_tidy_is_installed))
182     }
183
184     fn make_run(run: RunConfig<'_>) {
185         run.builder.ensure(HtmlCheck { target: run.target });
186     }
187
188     fn run(self, builder: &Builder<'_>) {
189         if !check_if_tidy_is_installed() {
190             eprintln!("not running HTML-check tool because `tidy` is missing");
191             eprintln!(
192                 "Note that `tidy` is not the in-tree `src/tools/tidy` but needs to be installed"
193             );
194             panic!("Cannot run html-check tests");
195         }
196         // Ensure that a few different kinds of documentation are available.
197         builder.default_doc(&[]);
198         builder.ensure(crate::doc::Rustc { target: self.target, stage: builder.top_stage });
199
200         try_run(builder, builder.tool_cmd(Tool::HtmlChecker).arg(builder.doc_out(self.target)));
201     }
202 }
203
204 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
205 pub struct Cargotest {
206     stage: u32,
207     host: TargetSelection,
208 }
209
210 impl Step for Cargotest {
211     type Output = ();
212     const ONLY_HOSTS: bool = true;
213
214     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
215         run.path("src/tools/cargotest")
216     }
217
218     fn make_run(run: RunConfig<'_>) {
219         run.builder.ensure(Cargotest { stage: run.builder.top_stage, host: run.target });
220     }
221
222     /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
223     ///
224     /// This tool in `src/tools` will check out a few Rust projects and run `cargo
225     /// test` to ensure that we don't regress the test suites there.
226     fn run(self, builder: &Builder<'_>) {
227         let compiler = builder.compiler(self.stage, self.host);
228         builder.ensure(compile::Rustc { compiler, target: compiler.host });
229         let cargo = builder.ensure(tool::Cargo { compiler, target: compiler.host });
230
231         // Note that this is a short, cryptic, and not scoped directory name. This
232         // is currently to minimize the length of path on Windows where we otherwise
233         // quickly run into path name limit constraints.
234         let out_dir = builder.out.join("ct");
235         t!(fs::create_dir_all(&out_dir));
236
237         let _time = util::timeit(&builder);
238         let mut cmd = builder.tool_cmd(Tool::CargoTest);
239         try_run(
240             builder,
241             cmd.arg(&cargo)
242                 .arg(&out_dir)
243                 .args(builder.config.cmd.test_args())
244                 .env("RUSTC", builder.rustc(compiler))
245                 .env("RUSTDOC", builder.rustdoc(compiler)),
246         );
247     }
248 }
249
250 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
251 pub struct Cargo {
252     stage: u32,
253     host: TargetSelection,
254 }
255
256 impl Step for Cargo {
257     type Output = ();
258     const ONLY_HOSTS: bool = true;
259
260     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
261         run.path("src/tools/cargo")
262     }
263
264     fn make_run(run: RunConfig<'_>) {
265         run.builder.ensure(Cargo { stage: run.builder.top_stage, host: run.target });
266     }
267
268     /// Runs `cargo test` for `cargo` packaged with Rust.
269     fn run(self, builder: &Builder<'_>) {
270         let compiler = builder.compiler(self.stage, self.host);
271
272         builder.ensure(tool::Cargo { compiler, target: self.host });
273         let mut cargo = tool::prepare_tool_cargo(
274             builder,
275             compiler,
276             Mode::ToolRustc,
277             self.host,
278             "test",
279             "src/tools/cargo",
280             SourceType::Submodule,
281             &[],
282         );
283
284         if !builder.fail_fast {
285             cargo.arg("--no-fail-fast");
286         }
287         cargo.arg("--").args(builder.config.cmd.test_args());
288
289         // Don't run cross-compile tests, we may not have cross-compiled libstd libs
290         // available.
291         cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
292         // Disable a test that has issues with mingw.
293         cargo.env("CARGO_TEST_DISABLE_GIT_CLI", "1");
294         // Forcibly disable tests using nightly features since any changes to
295         // those features won't be able to land.
296         cargo.env("CARGO_TEST_DISABLE_NIGHTLY", "1");
297
298         cargo.env("PATH", &path_for_cargo(builder, compiler));
299
300         try_run(builder, &mut cargo.into());
301     }
302 }
303
304 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
305 pub struct Rls {
306     stage: u32,
307     host: TargetSelection,
308 }
309
310 impl Step for Rls {
311     type Output = ();
312     const ONLY_HOSTS: bool = true;
313
314     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
315         run.path("src/tools/rls")
316     }
317
318     fn make_run(run: RunConfig<'_>) {
319         run.builder.ensure(Rls { stage: run.builder.top_stage, host: run.target });
320     }
321
322     /// Runs `cargo test` for the rls.
323     fn run(self, builder: &Builder<'_>) {
324         let stage = self.stage;
325         let host = self.host;
326         let compiler = builder.compiler(stage, host);
327
328         let build_result =
329             builder.ensure(tool::Rls { compiler, target: self.host, extra_features: Vec::new() });
330         if build_result.is_none() {
331             eprintln!("failed to test rls: could not build");
332             return;
333         }
334
335         let mut cargo = tool::prepare_tool_cargo(
336             builder,
337             compiler,
338             Mode::ToolRustc,
339             host,
340             "test",
341             "src/tools/rls",
342             SourceType::Submodule,
343             &[],
344         );
345
346         cargo.add_rustc_lib_path(builder, compiler);
347         cargo.arg("--").args(builder.config.cmd.test_args());
348
349         if try_run(builder, &mut cargo.into()) {
350             builder.save_toolstate("rls", ToolState::TestPass);
351         }
352     }
353 }
354
355 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
356 pub struct Rustfmt {
357     stage: u32,
358     host: TargetSelection,
359 }
360
361 impl Step for Rustfmt {
362     type Output = ();
363     const ONLY_HOSTS: bool = true;
364
365     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
366         run.path("src/tools/rustfmt")
367     }
368
369     fn make_run(run: RunConfig<'_>) {
370         run.builder.ensure(Rustfmt { stage: run.builder.top_stage, host: run.target });
371     }
372
373     /// Runs `cargo test` for rustfmt.
374     fn run(self, builder: &Builder<'_>) {
375         let stage = self.stage;
376         let host = self.host;
377         let compiler = builder.compiler(stage, host);
378
379         builder
380             .ensure(tool::Rustfmt { compiler, target: self.host, extra_features: Vec::new() })
381             .expect("in-tree tool");
382
383         let mut cargo = tool::prepare_tool_cargo(
384             builder,
385             compiler,
386             Mode::ToolRustc,
387             host,
388             "test",
389             "src/tools/rustfmt",
390             SourceType::InTree,
391             &[],
392         );
393
394         let dir = testdir(builder, compiler.host);
395         t!(fs::create_dir_all(&dir));
396         cargo.env("RUSTFMT_TEST_DIR", dir);
397
398         cargo.add_rustc_lib_path(builder, compiler);
399
400         builder.run(&mut cargo.into());
401     }
402 }
403
404 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
405 pub struct RustDemangler {
406     stage: u32,
407     host: TargetSelection,
408 }
409
410 impl Step for RustDemangler {
411     type Output = ();
412     const ONLY_HOSTS: bool = true;
413
414     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
415         run.path("src/tools/rust-demangler")
416     }
417
418     fn make_run(run: RunConfig<'_>) {
419         run.builder.ensure(RustDemangler { stage: run.builder.top_stage, host: run.target });
420     }
421
422     /// Runs `cargo test` for rust-demangler.
423     fn run(self, builder: &Builder<'_>) {
424         let stage = self.stage;
425         let host = self.host;
426         let compiler = builder.compiler(stage, host);
427
428         let rust_demangler = builder
429             .ensure(tool::RustDemangler { compiler, target: self.host, extra_features: Vec::new() })
430             .expect("in-tree tool");
431         let mut cargo = tool::prepare_tool_cargo(
432             builder,
433             compiler,
434             Mode::ToolRustc,
435             host,
436             "test",
437             "src/tools/rust-demangler",
438             SourceType::InTree,
439             &[],
440         );
441
442         let dir = testdir(builder, compiler.host);
443         t!(fs::create_dir_all(&dir));
444
445         cargo.env("RUST_DEMANGLER_DRIVER_PATH", rust_demangler);
446
447         cargo.arg("--").args(builder.config.cmd.test_args());
448
449         cargo.add_rustc_lib_path(builder, compiler);
450
451         builder.run(&mut cargo.into());
452     }
453 }
454
455 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
456 pub struct Miri {
457     stage: u32,
458     host: TargetSelection,
459 }
460
461 impl Step for Miri {
462     type Output = ();
463     const ONLY_HOSTS: bool = true;
464
465     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
466         run.path("src/tools/miri")
467     }
468
469     fn make_run(run: RunConfig<'_>) {
470         run.builder.ensure(Miri { stage: run.builder.top_stage, host: run.target });
471     }
472
473     /// Runs `cargo test` for miri.
474     fn run(self, builder: &Builder<'_>) {
475         let stage = self.stage;
476         let host = self.host;
477         let compiler = builder.compiler(stage, host);
478
479         let miri =
480             builder.ensure(tool::Miri { compiler, target: self.host, extra_features: Vec::new() });
481         let cargo_miri = builder.ensure(tool::CargoMiri {
482             compiler,
483             target: self.host,
484             extra_features: Vec::new(),
485         });
486         if let (Some(miri), Some(_cargo_miri)) = (miri, cargo_miri) {
487             let mut cargo =
488                 builder.cargo(compiler, Mode::ToolRustc, SourceType::Submodule, host, "install");
489             cargo.arg("xargo");
490             // Configure `cargo install` path. cargo adds a `bin/`.
491             cargo.env("CARGO_INSTALL_ROOT", &builder.out);
492
493             let mut cargo = Command::from(cargo);
494             if !try_run(builder, &mut cargo) {
495                 return;
496             }
497
498             // # Run `cargo miri setup`.
499             let mut cargo = tool::prepare_tool_cargo(
500                 builder,
501                 compiler,
502                 Mode::ToolRustc,
503                 host,
504                 "run",
505                 "src/tools/miri/cargo-miri",
506                 SourceType::Submodule,
507                 &[],
508             );
509             cargo.add_rustc_lib_path(builder, compiler);
510             cargo.arg("--").arg("miri").arg("setup");
511
512             // Tell `cargo miri setup` where to find the sources.
513             cargo.env("XARGO_RUST_SRC", builder.src.join("library"));
514             // Tell it where to find Miri.
515             cargo.env("MIRI", &miri);
516             // Debug things.
517             cargo.env("RUST_BACKTRACE", "1");
518             // Let cargo-miri know where xargo ended up.
519             cargo.env("XARGO_CHECK", builder.out.join("bin").join("xargo-check"));
520
521             let mut cargo = Command::from(cargo);
522             if !try_run(builder, &mut cargo) {
523                 return;
524             }
525
526             // # Determine where Miri put its sysroot.
527             // To this end, we run `cargo miri setup --print-sysroot` and capture the output.
528             // (We do this separately from the above so that when the setup actually
529             // happens we get some output.)
530             // We re-use the `cargo` from above.
531             cargo.arg("--print-sysroot");
532
533             // FIXME: Is there a way in which we can re-use the usual `run` helpers?
534             let miri_sysroot = if builder.config.dry_run {
535                 String::new()
536             } else {
537                 builder.verbose(&format!("running: {:?}", cargo));
538                 let out = cargo
539                     .output()
540                     .expect("We already ran `cargo miri setup` before and that worked");
541                 assert!(out.status.success(), "`cargo miri setup` returned with non-0 exit code");
542                 // Output is "<sysroot>\n".
543                 let stdout = String::from_utf8(out.stdout)
544                     .expect("`cargo miri setup` stdout is not valid UTF-8");
545                 let sysroot = stdout.trim_end();
546                 builder.verbose(&format!("`cargo miri setup --print-sysroot` said: {:?}", sysroot));
547                 sysroot.to_owned()
548             };
549
550             // # Run `cargo test`.
551             let mut cargo = tool::prepare_tool_cargo(
552                 builder,
553                 compiler,
554                 Mode::ToolRustc,
555                 host,
556                 "test",
557                 "src/tools/miri",
558                 SourceType::Submodule,
559                 &[],
560             );
561             cargo.add_rustc_lib_path(builder, compiler);
562
563             // miri tests need to know about the stage sysroot
564             cargo.env("MIRI_SYSROOT", miri_sysroot);
565             cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
566             cargo.env("MIRI", miri);
567
568             cargo.arg("--").args(builder.config.cmd.test_args());
569
570             let mut cargo = Command::from(cargo);
571             if !try_run(builder, &mut cargo) {
572                 return;
573             }
574
575             // # Run `cargo test` with `-Zmir-opt-level=4`.
576             cargo.env("MIRIFLAGS", "-O -Zmir-opt-level=4");
577             if !try_run(builder, &mut cargo) {
578                 return;
579             }
580
581             // # Done!
582             builder.save_toolstate("miri", ToolState::TestPass);
583         } else {
584             eprintln!("failed to test miri: could not build");
585         }
586     }
587 }
588
589 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
590 pub struct CompiletestTest {
591     host: TargetSelection,
592 }
593
594 impl Step for CompiletestTest {
595     type Output = ();
596
597     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
598         run.path("src/tools/compiletest")
599     }
600
601     fn make_run(run: RunConfig<'_>) {
602         run.builder.ensure(CompiletestTest { host: run.target });
603     }
604
605     /// Runs `cargo test` for compiletest.
606     fn run(self, builder: &Builder<'_>) {
607         let host = self.host;
608         let compiler = builder.compiler(0, host);
609
610         // We need `ToolStd` for the locally-built sysroot because
611         // compiletest uses unstable features of the `test` crate.
612         builder.ensure(compile::Std { compiler, target: host });
613         let cargo = tool::prepare_tool_cargo(
614             builder,
615             compiler,
616             Mode::ToolStd,
617             host,
618             "test",
619             "src/tools/compiletest",
620             SourceType::InTree,
621             &[],
622         );
623
624         try_run(builder, &mut cargo.into());
625     }
626 }
627
628 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
629 pub struct Clippy {
630     stage: u32,
631     host: TargetSelection,
632 }
633
634 impl Step for Clippy {
635     type Output = ();
636     const ONLY_HOSTS: bool = true;
637     const DEFAULT: bool = false;
638
639     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
640         run.path("src/tools/clippy")
641     }
642
643     fn make_run(run: RunConfig<'_>) {
644         run.builder.ensure(Clippy { stage: run.builder.top_stage, host: run.target });
645     }
646
647     /// Runs `cargo test` for clippy.
648     fn run(self, builder: &Builder<'_>) {
649         let stage = self.stage;
650         let host = self.host;
651         let compiler = builder.compiler(stage, host);
652
653         builder
654             .ensure(tool::Clippy { compiler, target: self.host, extra_features: Vec::new() })
655             .expect("in-tree tool");
656         let mut cargo = tool::prepare_tool_cargo(
657             builder,
658             compiler,
659             Mode::ToolRustc,
660             host,
661             "test",
662             "src/tools/clippy",
663             SourceType::InTree,
664             &[],
665         );
666
667         cargo.env("RUSTC_TEST_SUITE", builder.rustc(compiler));
668         cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
669         let host_libs = builder.stage_out(compiler, Mode::ToolRustc).join(builder.cargo_dir());
670         cargo.env("HOST_LIBS", host_libs);
671
672         cargo.arg("--").args(builder.config.cmd.test_args());
673
674         cargo.add_rustc_lib_path(builder, compiler);
675
676         if builder.try_run(&mut cargo.into()) {
677             // The tests succeeded; nothing to do.
678             return;
679         }
680
681         if !builder.config.cmd.bless() {
682             std::process::exit(1);
683         }
684
685         let mut cargo = builder.cargo(compiler, Mode::ToolRustc, SourceType::InTree, host, "run");
686         cargo.arg("-p").arg("clippy_dev");
687         // clippy_dev gets confused if it can't find `clippy/Cargo.toml`
688         cargo.current_dir(&builder.src.join("src").join("tools").join("clippy"));
689         if builder.config.rust_optimize {
690             cargo.env("PROFILE", "release");
691         } else {
692             cargo.env("PROFILE", "debug");
693         }
694         cargo.arg("--");
695         cargo.arg("bless");
696         builder.run(&mut cargo.into());
697     }
698 }
699
700 fn path_for_cargo(builder: &Builder<'_>, compiler: Compiler) -> OsString {
701     // Configure PATH to find the right rustc. NB. we have to use PATH
702     // and not RUSTC because the Cargo test suite has tests that will
703     // fail if rustc is not spelled `rustc`.
704     let path = builder.sysroot(compiler).join("bin");
705     let old_path = env::var_os("PATH").unwrap_or_default();
706     env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
707 }
708
709 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
710 pub struct RustdocTheme {
711     pub compiler: Compiler,
712 }
713
714 impl Step for RustdocTheme {
715     type Output = ();
716     const DEFAULT: bool = true;
717     const ONLY_HOSTS: bool = true;
718
719     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
720         run.path("src/tools/rustdoc-themes")
721     }
722
723     fn make_run(run: RunConfig<'_>) {
724         let compiler = run.builder.compiler(run.builder.top_stage, run.target);
725
726         run.builder.ensure(RustdocTheme { compiler });
727     }
728
729     fn run(self, builder: &Builder<'_>) {
730         let rustdoc = builder.bootstrap_out.join("rustdoc");
731         let mut cmd = builder.tool_cmd(Tool::RustdocTheme);
732         cmd.arg(rustdoc.to_str().unwrap())
733             .arg(builder.src.join("src/librustdoc/html/static/css/themes").to_str().unwrap())
734             .env("RUSTC_STAGE", self.compiler.stage.to_string())
735             .env("RUSTC_SYSROOT", builder.sysroot(self.compiler))
736             .env("RUSTDOC_LIBDIR", builder.sysroot_libdir(self.compiler, self.compiler.host))
737             .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
738             .env("RUSTDOC_REAL", builder.rustdoc(self.compiler))
739             .env("RUSTC_BOOTSTRAP", "1");
740         if let Some(linker) = builder.linker(self.compiler.host) {
741             cmd.env("RUSTDOC_LINKER", linker);
742         }
743         if builder.is_fuse_ld_lld(self.compiler.host) {
744             cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
745         }
746         try_run(builder, &mut cmd);
747     }
748 }
749
750 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
751 pub struct RustdocJSStd {
752     pub target: TargetSelection,
753 }
754
755 impl Step for RustdocJSStd {
756     type Output = ();
757     const DEFAULT: bool = true;
758     const ONLY_HOSTS: bool = true;
759
760     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
761         run.suite_path("src/test/rustdoc-js-std")
762     }
763
764     fn make_run(run: RunConfig<'_>) {
765         run.builder.ensure(RustdocJSStd { target: run.target });
766     }
767
768     fn run(self, builder: &Builder<'_>) {
769         if let Some(ref nodejs) = builder.config.nodejs {
770             let mut command = Command::new(nodejs);
771             command
772                 .arg(builder.src.join("src/tools/rustdoc-js/tester.js"))
773                 .arg("--crate-name")
774                 .arg("std")
775                 .arg("--resource-suffix")
776                 .arg(&builder.version)
777                 .arg("--doc-folder")
778                 .arg(builder.doc_out(self.target))
779                 .arg("--test-folder")
780                 .arg(builder.src.join("src/test/rustdoc-js-std"));
781             for path in &builder.paths {
782                 if let Some(p) =
783                     util::is_valid_test_suite_arg(path, "src/test/rustdoc-js-std", builder)
784                 {
785                     if !p.ends_with(".js") {
786                         eprintln!("A non-js file was given: `{}`", path.display());
787                         panic!("Cannot run rustdoc-js-std tests");
788                     }
789                     command.arg("--test-file").arg(path);
790                 }
791             }
792             builder.ensure(crate::doc::Std { target: self.target, stage: builder.top_stage });
793             builder.run(&mut command);
794         } else {
795             builder.info("No nodejs found, skipping \"src/test/rustdoc-js-std\" tests");
796         }
797     }
798 }
799
800 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
801 pub struct RustdocJSNotStd {
802     pub target: TargetSelection,
803     pub compiler: Compiler,
804 }
805
806 impl Step for RustdocJSNotStd {
807     type Output = ();
808     const DEFAULT: bool = true;
809     const ONLY_HOSTS: bool = true;
810
811     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
812         run.suite_path("src/test/rustdoc-js")
813     }
814
815     fn make_run(run: RunConfig<'_>) {
816         let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
817         run.builder.ensure(RustdocJSNotStd { target: run.target, compiler });
818     }
819
820     fn run(self, builder: &Builder<'_>) {
821         if builder.config.nodejs.is_some() {
822             builder.ensure(Compiletest {
823                 compiler: self.compiler,
824                 target: self.target,
825                 mode: "js-doc-test",
826                 suite: "rustdoc-js",
827                 path: "src/test/rustdoc-js",
828                 compare_mode: None,
829             });
830         } else {
831             builder.info("No nodejs found, skipping \"src/test/rustdoc-js\" tests");
832         }
833     }
834 }
835
836 fn get_browser_ui_test_version_inner(npm: &Path, global: bool) -> Option<String> {
837     let mut command = Command::new(&npm);
838     command.arg("list").arg("--parseable").arg("--long").arg("--depth=0");
839     if global {
840         command.arg("--global");
841     }
842     let lines = command
843         .output()
844         .map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
845         .unwrap_or(String::new());
846     lines.lines().find_map(|l| l.split(":browser-ui-test@").skip(1).next()).map(|v| v.to_owned())
847 }
848
849 fn get_browser_ui_test_version(npm: &Path) -> Option<String> {
850     get_browser_ui_test_version_inner(npm, false)
851         .or_else(|| get_browser_ui_test_version_inner(npm, true))
852 }
853
854 fn compare_browser_ui_test_version(installed_version: &str, src: &Path) {
855     match fs::read_to_string(
856         src.join("src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version"),
857     ) {
858         Ok(v) => {
859             if v.trim() != installed_version {
860                 eprintln!(
861                     "⚠️ Installed version of browser-ui-test (`{}`) is different than the \
862                      one used in the CI (`{}`)",
863                     installed_version, v
864                 );
865             }
866         }
867         Err(e) => eprintln!("Couldn't find the CI browser-ui-test version: {:?}", e),
868     }
869 }
870
871 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
872 pub struct RustdocGUI {
873     pub target: TargetSelection,
874     pub compiler: Compiler,
875 }
876
877 impl Step for RustdocGUI {
878     type Output = ();
879     const DEFAULT: bool = true;
880     const ONLY_HOSTS: bool = true;
881
882     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
883         let builder = run.builder;
884         let run = run.suite_path("src/test/rustdoc-gui");
885         run.lazy_default_condition(Box::new(move || {
886             builder.config.nodejs.is_some()
887                 && builder
888                     .config
889                     .npm
890                     .as_ref()
891                     .map(|p| get_browser_ui_test_version(p).is_some())
892                     .unwrap_or(false)
893         }))
894     }
895
896     fn make_run(run: RunConfig<'_>) {
897         let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
898         run.builder.ensure(RustdocGUI { target: run.target, compiler });
899     }
900
901     fn run(self, builder: &Builder<'_>) {
902         let nodejs = builder.config.nodejs.as_ref().expect("nodejs isn't available");
903         let npm = builder.config.npm.as_ref().expect("npm isn't available");
904
905         builder.ensure(compile::Std { compiler: self.compiler, target: self.target });
906
907         // The goal here is to check if the necessary packages are installed, and if not, we
908         // panic.
909         match get_browser_ui_test_version(&npm) {
910             Some(version) => {
911                 // We also check the version currently used in CI and emit a warning if it's not the
912                 // same one.
913                 compare_browser_ui_test_version(&version, &builder.build.src);
914             }
915             None => {
916                 eprintln!(
917                     "error: rustdoc-gui test suite cannot be run because npm `browser-ui-test` \
918                      dependency is missing",
919                 );
920                 eprintln!(
921                     "If you want to install the `{0}` dependency, run `npm install {0}`",
922                     "browser-ui-test",
923                 );
924                 panic!("Cannot run rustdoc-gui tests");
925             }
926         }
927
928         let out_dir = builder.test_out(self.target).join("rustdoc-gui");
929
930         // We remove existing folder to be sure there won't be artifacts remaining.
931         builder.clear_if_dirty(&out_dir, &builder.rustdoc(self.compiler));
932
933         let src_path = builder.build.src.join("src/test/rustdoc-gui/src");
934         // We generate docs for the libraries present in the rustdoc-gui's src folder.
935         for entry in src_path.read_dir().expect("read_dir call failed") {
936             if let Ok(entry) = entry {
937                 let path = entry.path();
938
939                 if !path.is_dir() {
940                     continue;
941                 }
942
943                 let mut cargo = Command::new(&builder.initial_cargo);
944                 cargo
945                     .arg("doc")
946                     .arg("--target-dir")
947                     .arg(&out_dir)
948                     .env("RUSTDOC", builder.rustdoc(self.compiler))
949                     .env("RUSTC", builder.rustc(self.compiler))
950                     .current_dir(path);
951                 // FIXME: implement a `// compile-flags` command or similar
952                 //        instead of hard-coding this test
953                 if entry.file_name() == "link_to_definition" {
954                     cargo.env("RUSTDOCFLAGS", "-Zunstable-options --generate-link-to-definition");
955                 }
956                 builder.run(&mut cargo);
957             }
958         }
959
960         // We now run GUI tests.
961         let mut command = Command::new(&nodejs);
962         command
963             .arg(builder.build.src.join("src/tools/rustdoc-gui/tester.js"))
964             .arg("--jobs")
965             .arg(&builder.jobs().to_string())
966             .arg("--doc-folder")
967             .arg(out_dir.join("doc"))
968             .arg("--tests-folder")
969             .arg(builder.build.src.join("src/test/rustdoc-gui"));
970         for path in &builder.paths {
971             if let Some(p) = util::is_valid_test_suite_arg(path, "src/test/rustdoc-gui", builder) {
972                 if !p.ends_with(".goml") {
973                     eprintln!("A non-goml file was given: `{}`", path.display());
974                     panic!("Cannot run rustdoc-gui tests");
975                 }
976                 if let Some(name) = path.file_name().and_then(|f| f.to_str()) {
977                     command.arg("--file").arg(name);
978                 }
979             }
980         }
981         for test_arg in builder.config.cmd.test_args() {
982             command.arg(test_arg);
983         }
984         builder.run(&mut command);
985     }
986 }
987
988 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
989 pub struct Tidy;
990
991 impl Step for Tidy {
992     type Output = ();
993     const DEFAULT: bool = true;
994     const ONLY_HOSTS: bool = true;
995
996     /// Runs the `tidy` tool.
997     ///
998     /// This tool in `src/tools` checks up on various bits and pieces of style and
999     /// otherwise just implements a few lint-like checks that are specific to the
1000     /// compiler itself.
1001     ///
1002     /// Once tidy passes, this step also runs `fmt --check` if tests are being run
1003     /// for the `dev` or `nightly` channels.
1004     fn run(self, builder: &Builder<'_>) {
1005         let mut cmd = builder.tool_cmd(Tool::Tidy);
1006         cmd.arg(&builder.src);
1007         cmd.arg(&builder.initial_cargo);
1008         cmd.arg(&builder.out);
1009         cmd.arg(builder.jobs().to_string());
1010         if builder.is_verbose() {
1011             cmd.arg("--verbose");
1012         }
1013
1014         builder.info("tidy check");
1015         try_run(builder, &mut cmd);
1016
1017         if builder.config.channel == "dev" || builder.config.channel == "nightly" {
1018             builder.info("fmt check");
1019             if builder.config.initial_rustfmt.is_none() {
1020                 let inferred_rustfmt_dir = builder.config.initial_rustc.parent().unwrap();
1021                 eprintln!(
1022                     "\
1023 error: no `rustfmt` binary found in {PATH}
1024 info: `rust.channel` is currently set to \"{CHAN}\"
1025 help: if you are testing a beta branch, set `rust.channel` to \"beta\" in the `config.toml` file
1026 help: to skip test's attempt to check tidiness, pass `--exclude src/tools/tidy` to `x.py test`",
1027                     PATH = inferred_rustfmt_dir.display(),
1028                     CHAN = builder.config.channel,
1029                 );
1030                 std::process::exit(1);
1031             }
1032             crate::format::format(&builder.build, !builder.config.cmd.bless(), &[]);
1033         }
1034     }
1035
1036     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1037         run.path("src/tools/tidy")
1038     }
1039
1040     fn make_run(run: RunConfig<'_>) {
1041         run.builder.ensure(Tidy);
1042     }
1043 }
1044
1045 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1046 pub struct ExpandYamlAnchors;
1047
1048 impl Step for ExpandYamlAnchors {
1049     type Output = ();
1050     const ONLY_HOSTS: bool = true;
1051
1052     /// Ensure the `generate-ci-config` tool was run locally.
1053     ///
1054     /// The tool in `src/tools` reads the CI definition in `src/ci/builders.yml` and generates the
1055     /// appropriate configuration for all our CI providers. This step ensures the tool was called
1056     /// by the user before committing CI changes.
1057     fn run(self, builder: &Builder<'_>) {
1058         builder.info("Ensuring the YAML anchors in the GitHub Actions config were expanded");
1059         try_run(
1060             builder,
1061             &mut builder.tool_cmd(Tool::ExpandYamlAnchors).arg("check").arg(&builder.src),
1062         );
1063     }
1064
1065     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1066         run.path("src/tools/expand-yaml-anchors")
1067     }
1068
1069     fn make_run(run: RunConfig<'_>) {
1070         run.builder.ensure(ExpandYamlAnchors);
1071     }
1072 }
1073
1074 fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
1075     builder.out.join(host.triple).join("test")
1076 }
1077
1078 macro_rules! default_test {
1079     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
1080         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: false });
1081     };
1082 }
1083
1084 macro_rules! default_test_with_compare_mode {
1085     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr,
1086                    compare_mode: $compare_mode:expr }) => {
1087         test_with_compare_mode!($name {
1088             path: $path,
1089             mode: $mode,
1090             suite: $suite,
1091             default: true,
1092             host: false,
1093             compare_mode: $compare_mode
1094         });
1095     };
1096 }
1097
1098 macro_rules! host_test {
1099     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
1100         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: true });
1101     };
1102 }
1103
1104 macro_rules! test {
1105     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1106                    host: $host:expr }) => {
1107         test_definitions!($name {
1108             path: $path,
1109             mode: $mode,
1110             suite: $suite,
1111             default: $default,
1112             host: $host,
1113             compare_mode: None
1114         });
1115     };
1116 }
1117
1118 macro_rules! test_with_compare_mode {
1119     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1120                    host: $host:expr, compare_mode: $compare_mode:expr }) => {
1121         test_definitions!($name {
1122             path: $path,
1123             mode: $mode,
1124             suite: $suite,
1125             default: $default,
1126             host: $host,
1127             compare_mode: Some($compare_mode)
1128         });
1129     };
1130 }
1131
1132 macro_rules! test_definitions {
1133     ($name:ident {
1134         path: $path:expr,
1135         mode: $mode:expr,
1136         suite: $suite:expr,
1137         default: $default:expr,
1138         host: $host:expr,
1139         compare_mode: $compare_mode:expr
1140     }) => {
1141         #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1142         pub struct $name {
1143             pub compiler: Compiler,
1144             pub target: TargetSelection,
1145         }
1146
1147         impl Step for $name {
1148             type Output = ();
1149             const DEFAULT: bool = $default;
1150             const ONLY_HOSTS: bool = $host;
1151
1152             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1153                 run.suite_path($path)
1154             }
1155
1156             fn make_run(run: RunConfig<'_>) {
1157                 let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1158
1159                 run.builder.ensure($name { compiler, target: run.target });
1160             }
1161
1162             fn run(self, builder: &Builder<'_>) {
1163                 builder.ensure(Compiletest {
1164                     compiler: self.compiler,
1165                     target: self.target,
1166                     mode: $mode,
1167                     suite: $suite,
1168                     path: $path,
1169                     compare_mode: $compare_mode,
1170                 })
1171             }
1172         }
1173     };
1174 }
1175
1176 default_test_with_compare_mode!(Ui {
1177     path: "src/test/ui",
1178     mode: "ui",
1179     suite: "ui",
1180     compare_mode: "nll"
1181 });
1182
1183 default_test!(RunPassValgrind {
1184     path: "src/test/run-pass-valgrind",
1185     mode: "run-pass-valgrind",
1186     suite: "run-pass-valgrind"
1187 });
1188
1189 default_test!(MirOpt { path: "src/test/mir-opt", mode: "mir-opt", suite: "mir-opt" });
1190
1191 default_test!(Codegen { path: "src/test/codegen", mode: "codegen", suite: "codegen" });
1192
1193 default_test!(CodegenUnits {
1194     path: "src/test/codegen-units",
1195     mode: "codegen-units",
1196     suite: "codegen-units"
1197 });
1198
1199 default_test!(Incremental {
1200     path: "src/test/incremental",
1201     mode: "incremental",
1202     suite: "incremental"
1203 });
1204
1205 default_test_with_compare_mode!(Debuginfo {
1206     path: "src/test/debuginfo",
1207     mode: "debuginfo",
1208     suite: "debuginfo",
1209     compare_mode: "split-dwarf"
1210 });
1211
1212 host_test!(UiFullDeps { path: "src/test/ui-fulldeps", mode: "ui", suite: "ui-fulldeps" });
1213
1214 host_test!(Rustdoc { path: "src/test/rustdoc", mode: "rustdoc", suite: "rustdoc" });
1215 host_test!(RustdocUi { path: "src/test/rustdoc-ui", mode: "ui", suite: "rustdoc-ui" });
1216
1217 host_test!(RustdocJson {
1218     path: "src/test/rustdoc-json",
1219     mode: "rustdoc-json",
1220     suite: "rustdoc-json"
1221 });
1222
1223 host_test!(Pretty { path: "src/test/pretty", mode: "pretty", suite: "pretty" });
1224
1225 default_test!(RunMake { path: "src/test/run-make", mode: "run-make", suite: "run-make" });
1226
1227 host_test!(RunMakeFullDeps {
1228     path: "src/test/run-make-fulldeps",
1229     mode: "run-make",
1230     suite: "run-make-fulldeps"
1231 });
1232
1233 default_test!(Assembly { path: "src/test/assembly", mode: "assembly", suite: "assembly" });
1234
1235 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1236 struct Compiletest {
1237     compiler: Compiler,
1238     target: TargetSelection,
1239     mode: &'static str,
1240     suite: &'static str,
1241     path: &'static str,
1242     compare_mode: Option<&'static str>,
1243 }
1244
1245 impl Step for Compiletest {
1246     type Output = ();
1247
1248     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1249         run.never()
1250     }
1251
1252     /// Executes the `compiletest` tool to run a suite of tests.
1253     ///
1254     /// Compiles all tests with `compiler` for `target` with the specified
1255     /// compiletest `mode` and `suite` arguments. For example `mode` can be
1256     /// "run-pass" or `suite` can be something like `debuginfo`.
1257     fn run(self, builder: &Builder<'_>) {
1258         if builder.top_stage == 0 && env::var("COMPILETEST_FORCE_STAGE0").is_err() {
1259             eprintln!("\
1260 error: `--stage 0` runs compiletest on the beta compiler, not your local changes, and will almost always cause tests to fail
1261 help: to test the compiler, use `--stage 1` instead
1262 help: to test the standard library, use `--stage 0 library/std` instead
1263 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`."
1264             );
1265             std::process::exit(1);
1266         }
1267
1268         let compiler = self.compiler;
1269         let target = self.target;
1270         let mode = self.mode;
1271         let suite = self.suite;
1272
1273         // Path for test suite
1274         let suite_path = self.path;
1275
1276         // Skip codegen tests if they aren't enabled in configuration.
1277         if !builder.config.codegen_tests && suite == "codegen" {
1278             return;
1279         }
1280
1281         if suite == "debuginfo" {
1282             builder
1283                 .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target });
1284         }
1285
1286         if suite.ends_with("fulldeps") {
1287             builder.ensure(compile::Rustc { compiler, target });
1288         }
1289
1290         builder.ensure(compile::Std { compiler, target });
1291         // ensure that `libproc_macro` is available on the host.
1292         builder.ensure(compile::Std { compiler, target: compiler.host });
1293
1294         // Also provide `rust_test_helpers` for the host.
1295         builder.ensure(native::TestHelpers { target: compiler.host });
1296
1297         // As well as the target, except for plain wasm32, which can't build it
1298         if !target.contains("wasm") || target.contains("emscripten") {
1299             builder.ensure(native::TestHelpers { target });
1300         }
1301
1302         builder.ensure(RemoteCopyLibs { compiler, target });
1303
1304         let mut cmd = builder.tool_cmd(Tool::Compiletest);
1305
1306         // compiletest currently has... a lot of arguments, so let's just pass all
1307         // of them!
1308
1309         cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
1310         cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
1311         cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1312
1313         let is_rustdoc = suite.ends_with("rustdoc-ui") || suite.ends_with("rustdoc-js");
1314
1315         // Avoid depending on rustdoc when we don't need it.
1316         if mode == "rustdoc"
1317             || mode == "run-make"
1318             || (mode == "ui" && is_rustdoc)
1319             || mode == "js-doc-test"
1320             || mode == "rustdoc-json"
1321         {
1322             cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler));
1323         }
1324
1325         if mode == "rustdoc-json" {
1326             // Use the beta compiler for jsondocck
1327             let json_compiler = compiler.with_stage(0);
1328             cmd.arg("--jsondocck-path")
1329                 .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target }));
1330         }
1331
1332         if mode == "run-make" && suite.ends_with("fulldeps") {
1333             let rust_demangler = builder
1334                 .ensure(tool::RustDemangler { compiler, target, extra_features: Vec::new() })
1335                 .expect("in-tree tool");
1336             cmd.arg("--rust-demangler-path").arg(rust_demangler);
1337         }
1338
1339         cmd.arg("--src-base").arg(builder.src.join("src/test").join(suite));
1340         cmd.arg("--build-base").arg(testdir(builder, compiler.host).join(suite));
1341         cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
1342         cmd.arg("--suite").arg(suite);
1343         cmd.arg("--mode").arg(mode);
1344         cmd.arg("--target").arg(target.rustc_target_arg());
1345         cmd.arg("--host").arg(&*compiler.host.triple);
1346         cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.build));
1347
1348         if builder.config.cmd.bless() {
1349             cmd.arg("--bless");
1350         }
1351
1352         if builder.config.cmd.force_rerun() {
1353             cmd.arg("--force-rerun");
1354         }
1355
1356         let compare_mode =
1357             builder.config.cmd.compare_mode().or_else(|| {
1358                 if builder.config.test_compare_mode { self.compare_mode } else { None }
1359             });
1360
1361         if let Some(ref pass) = builder.config.cmd.pass() {
1362             cmd.arg("--pass");
1363             cmd.arg(pass);
1364         }
1365
1366         if let Some(ref run) = builder.config.cmd.run() {
1367             cmd.arg("--run");
1368             cmd.arg(run);
1369         }
1370
1371         if let Some(ref nodejs) = builder.config.nodejs {
1372             cmd.arg("--nodejs").arg(nodejs);
1373         }
1374         if let Some(ref npm) = builder.config.npm {
1375             cmd.arg("--npm").arg(npm);
1376         }
1377
1378         let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
1379         if !is_rustdoc {
1380             if builder.config.rust_optimize_tests {
1381                 flags.push("-O".to_string());
1382             }
1383         }
1384         flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests));
1385         flags.push(builder.config.cmd.rustc_args().join(" "));
1386
1387         if let Some(linker) = builder.linker(target) {
1388             cmd.arg("--linker").arg(linker);
1389         }
1390
1391         let mut hostflags = flags.clone();
1392         hostflags.push(format!("-Lnative={}", builder.test_helpers_out(compiler.host).display()));
1393         hostflags.extend(builder.lld_flags(compiler.host));
1394         cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
1395
1396         let mut targetflags = flags;
1397         targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
1398         targetflags.extend(builder.lld_flags(target));
1399         cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
1400
1401         cmd.arg("--python").arg(builder.python());
1402
1403         if let Some(ref gdb) = builder.config.gdb {
1404             cmd.arg("--gdb").arg(gdb);
1405         }
1406
1407         let run = |cmd: &mut Command| {
1408             cmd.output().map(|output| {
1409                 String::from_utf8_lossy(&output.stdout)
1410                     .lines()
1411                     .next()
1412                     .unwrap_or_else(|| panic!("{:?} failed {:?}", cmd, output))
1413                     .to_string()
1414             })
1415         };
1416         let lldb_exe = "lldb";
1417         let lldb_version = Command::new(lldb_exe)
1418             .arg("--version")
1419             .output()
1420             .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
1421             .ok();
1422         if let Some(ref vers) = lldb_version {
1423             cmd.arg("--lldb-version").arg(vers);
1424             let lldb_python_dir = run(Command::new(lldb_exe).arg("-P")).ok();
1425             if let Some(ref dir) = lldb_python_dir {
1426                 cmd.arg("--lldb-python-dir").arg(dir);
1427             }
1428         }
1429
1430         if util::forcing_clang_based_tests() {
1431             let clang_exe = builder.llvm_out(target).join("bin").join("clang");
1432             cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
1433         }
1434
1435         // Get paths from cmd args
1436         let paths = match &builder.config.cmd {
1437             Subcommand::Test { ref paths, .. } => &paths[..],
1438             _ => &[],
1439         };
1440
1441         // Get test-args by striping suite path
1442         let mut test_args: Vec<&str> = paths
1443             .iter()
1444             .filter_map(|p| util::is_valid_test_suite_arg(p, suite_path, builder))
1445             .collect();
1446
1447         test_args.append(&mut builder.config.cmd.test_args());
1448
1449         cmd.args(&test_args);
1450
1451         if builder.is_verbose() {
1452             cmd.arg("--verbose");
1453         }
1454
1455         if !builder.config.verbose_tests {
1456             cmd.arg("--quiet");
1457         }
1458
1459         let mut llvm_components_passed = false;
1460         let mut copts_passed = false;
1461         if builder.config.llvm_enabled() {
1462             let llvm_config = builder.ensure(native::Llvm { target: builder.config.build });
1463             if !builder.config.dry_run {
1464                 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1465                 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1466                 // Remove trailing newline from llvm-config output.
1467                 cmd.arg("--llvm-version")
1468                     .arg(llvm_version.trim())
1469                     .arg("--llvm-components")
1470                     .arg(llvm_components.trim());
1471                 llvm_components_passed = true;
1472             }
1473             if !builder.is_rust_llvm(target) {
1474                 cmd.arg("--system-llvm");
1475             }
1476
1477             // Tests that use compiler libraries may inherit the `-lLLVM` link
1478             // requirement, but the `-L` library path is not propagated across
1479             // separate compilations. We can add LLVM's library path to the
1480             // platform-specific environment variable as a workaround.
1481             if !builder.config.dry_run && suite.ends_with("fulldeps") {
1482                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1483                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cmd);
1484             }
1485
1486             // Only pass correct values for these flags for the `run-make` suite as it
1487             // requires that a C++ compiler was configured which isn't always the case.
1488             if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1489                 // The llvm/bin directory contains many useful cross-platform
1490                 // tools. Pass the path to run-make tests so they can use them.
1491                 let llvm_bin_path = llvm_config
1492                     .parent()
1493                     .expect("Expected llvm-config to be contained in directory");
1494                 assert!(llvm_bin_path.is_dir());
1495                 cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
1496
1497                 // If LLD is available, add it to the PATH
1498                 if builder.config.lld_enabled {
1499                     let lld_install_root =
1500                         builder.ensure(native::Lld { target: builder.config.build });
1501
1502                     let lld_bin_path = lld_install_root.join("bin");
1503
1504                     let old_path = env::var_os("PATH").unwrap_or_default();
1505                     let new_path = env::join_paths(
1506                         std::iter::once(lld_bin_path).chain(env::split_paths(&old_path)),
1507                     )
1508                     .expect("Could not add LLD bin path to PATH");
1509                     cmd.env("PATH", new_path);
1510                 }
1511             }
1512         }
1513
1514         // Only pass correct values for these flags for the `run-make` suite as it
1515         // requires that a C++ compiler was configured which isn't always the case.
1516         if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1517             cmd.arg("--cc")
1518                 .arg(builder.cc(target))
1519                 .arg("--cxx")
1520                 .arg(builder.cxx(target).unwrap())
1521                 .arg("--cflags")
1522                 .arg(builder.cflags(target, GitRepo::Rustc, CLang::C).join(" "))
1523                 .arg("--cxxflags")
1524                 .arg(builder.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" "));
1525             copts_passed = true;
1526             if let Some(ar) = builder.ar(target) {
1527                 cmd.arg("--ar").arg(ar);
1528             }
1529         }
1530
1531         if !llvm_components_passed {
1532             cmd.arg("--llvm-components").arg("");
1533         }
1534         if !copts_passed {
1535             cmd.arg("--cc")
1536                 .arg("")
1537                 .arg("--cxx")
1538                 .arg("")
1539                 .arg("--cflags")
1540                 .arg("")
1541                 .arg("--cxxflags")
1542                 .arg("");
1543         }
1544
1545         if builder.remote_tested(target) {
1546             cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
1547         }
1548
1549         // Running a C compiler on MSVC requires a few env vars to be set, to be
1550         // sure to set them here.
1551         //
1552         // Note that if we encounter `PATH` we make sure to append to our own `PATH`
1553         // rather than stomp over it.
1554         if target.contains("msvc") {
1555             for &(ref k, ref v) in builder.cc[&target].env() {
1556                 if k != "PATH" {
1557                     cmd.env(k, v);
1558                 }
1559             }
1560         }
1561         cmd.env("RUSTC_BOOTSTRAP", "1");
1562         // Override the rustc version used in symbol hashes to reduce the amount of normalization
1563         // needed when diffing test output.
1564         cmd.env("RUSTC_FORCE_RUSTC_VERSION", "compiletest");
1565         cmd.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
1566         builder.add_rust_test_threads(&mut cmd);
1567
1568         if builder.config.sanitizers_enabled(target) {
1569             cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
1570         }
1571
1572         if builder.config.profiler_enabled(target) {
1573             cmd.env("RUSTC_PROFILER_SUPPORT", "1");
1574         }
1575
1576         cmd.env("RUST_TEST_TMPDIR", builder.tempdir());
1577
1578         cmd.arg("--adb-path").arg("adb");
1579         cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
1580         if target.contains("android") {
1581             // Assume that cc for this target comes from the android sysroot
1582             cmd.arg("--android-cross-path")
1583                 .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1584         } else {
1585             cmd.arg("--android-cross-path").arg("");
1586         }
1587
1588         if builder.config.cmd.rustfix_coverage() {
1589             cmd.arg("--rustfix-coverage");
1590         }
1591
1592         cmd.env("BOOTSTRAP_CARGO", &builder.initial_cargo);
1593
1594         cmd.arg("--channel").arg(&builder.config.channel);
1595
1596         builder.ci_env.force_coloring_in_ci(&mut cmd);
1597
1598         builder.info(&format!(
1599             "Check compiletest suite={} mode={} ({} -> {})",
1600             suite, mode, &compiler.host, target
1601         ));
1602         let _time = util::timeit(&builder);
1603         try_run(builder, &mut cmd);
1604
1605         if let Some(compare_mode) = compare_mode {
1606             cmd.arg("--compare-mode").arg(compare_mode);
1607             builder.info(&format!(
1608                 "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
1609                 suite, mode, compare_mode, &compiler.host, target
1610             ));
1611             let _time = util::timeit(&builder);
1612             try_run(builder, &mut cmd);
1613         }
1614     }
1615 }
1616
1617 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1618 struct BookTest {
1619     compiler: Compiler,
1620     path: PathBuf,
1621     name: &'static str,
1622     is_ext_doc: bool,
1623 }
1624
1625 impl Step for BookTest {
1626     type Output = ();
1627     const ONLY_HOSTS: bool = true;
1628
1629     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1630         run.never()
1631     }
1632
1633     /// Runs the documentation tests for a book in `src/doc`.
1634     ///
1635     /// This uses the `rustdoc` that sits next to `compiler`.
1636     fn run(self, builder: &Builder<'_>) {
1637         // External docs are different from local because:
1638         // - Some books need pre-processing by mdbook before being tested.
1639         // - They need to save their state to toolstate.
1640         // - They are only tested on the "checktools" builders.
1641         //
1642         // The local docs are tested by default, and we don't want to pay the
1643         // cost of building mdbook, so they use `rustdoc --test` directly.
1644         // Also, the unstable book is special because SUMMARY.md is generated,
1645         // so it is easier to just run `rustdoc` on its files.
1646         if self.is_ext_doc {
1647             self.run_ext_doc(builder);
1648         } else {
1649             self.run_local_doc(builder);
1650         }
1651     }
1652 }
1653
1654 impl BookTest {
1655     /// This runs the equivalent of `mdbook test` (via the rustbook wrapper)
1656     /// which in turn runs `rustdoc --test` on each file in the book.
1657     fn run_ext_doc(self, builder: &Builder<'_>) {
1658         let compiler = self.compiler;
1659
1660         builder.ensure(compile::Std { compiler, target: compiler.host });
1661
1662         // mdbook just executes a binary named "rustdoc", so we need to update
1663         // PATH so that it points to our rustdoc.
1664         let mut rustdoc_path = builder.rustdoc(compiler);
1665         rustdoc_path.pop();
1666         let old_path = env::var_os("PATH").unwrap_or_default();
1667         let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path)))
1668             .expect("could not add rustdoc to PATH");
1669
1670         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1671         let path = builder.src.join(&self.path);
1672         rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
1673         builder.add_rust_test_threads(&mut rustbook_cmd);
1674         builder.info(&format!("Testing rustbook {}", self.path.display()));
1675         let _time = util::timeit(&builder);
1676         let toolstate = if try_run(builder, &mut rustbook_cmd) {
1677             ToolState::TestPass
1678         } else {
1679             ToolState::TestFail
1680         };
1681         builder.save_toolstate(self.name, toolstate);
1682     }
1683
1684     /// This runs `rustdoc --test` on all `.md` files in the path.
1685     fn run_local_doc(self, builder: &Builder<'_>) {
1686         let compiler = self.compiler;
1687
1688         builder.ensure(compile::Std { compiler, target: compiler.host });
1689
1690         // Do a breadth-first traversal of the `src/doc` directory and just run
1691         // tests for all files that end in `*.md`
1692         let mut stack = vec![builder.src.join(self.path)];
1693         let _time = util::timeit(&builder);
1694         let mut files = Vec::new();
1695         while let Some(p) = stack.pop() {
1696             if p.is_dir() {
1697                 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
1698                 continue;
1699             }
1700
1701             if p.extension().and_then(|s| s.to_str()) != Some("md") {
1702                 continue;
1703             }
1704
1705             files.push(p);
1706         }
1707
1708         files.sort();
1709
1710         for file in files {
1711             markdown_test(builder, compiler, &file);
1712         }
1713     }
1714 }
1715
1716 macro_rules! test_book {
1717     ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => {
1718         $(
1719             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1720             pub struct $name {
1721                 compiler: Compiler,
1722             }
1723
1724             impl Step for $name {
1725                 type Output = ();
1726                 const DEFAULT: bool = $default;
1727                 const ONLY_HOSTS: bool = true;
1728
1729                 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1730                     run.path($path)
1731                 }
1732
1733                 fn make_run(run: RunConfig<'_>) {
1734                     run.builder.ensure($name {
1735                         compiler: run.builder.compiler(run.builder.top_stage, run.target),
1736                     });
1737                 }
1738
1739                 fn run(self, builder: &Builder<'_>) {
1740                     builder.ensure(BookTest {
1741                         compiler: self.compiler,
1742                         path: PathBuf::from($path),
1743                         name: $book_name,
1744                         is_ext_doc: !$default,
1745                     });
1746                 }
1747             }
1748         )+
1749     }
1750 }
1751
1752 test_book!(
1753     Nomicon, "src/doc/nomicon", "nomicon", default=false;
1754     Reference, "src/doc/reference", "reference", default=false;
1755     RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
1756     RustcBook, "src/doc/rustc", "rustc", default=true;
1757     RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1758     EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
1759     TheBook, "src/doc/book", "book", default=false;
1760     UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
1761     EditionGuide, "src/doc/edition-guide", "edition-guide", default=false;
1762 );
1763
1764 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1765 pub struct ErrorIndex {
1766     compiler: Compiler,
1767 }
1768
1769 impl Step for ErrorIndex {
1770     type Output = ();
1771     const DEFAULT: bool = true;
1772     const ONLY_HOSTS: bool = true;
1773
1774     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1775         run.path("src/tools/error_index_generator")
1776     }
1777
1778     fn make_run(run: RunConfig<'_>) {
1779         // error_index_generator depends on librustdoc. Use the compiler that
1780         // is normally used to build rustdoc for other tests (like compiletest
1781         // tests in src/test/rustdoc) so that it shares the same artifacts.
1782         let compiler = run.builder.compiler(run.builder.top_stage, run.builder.config.build);
1783         run.builder.ensure(ErrorIndex { compiler });
1784     }
1785
1786     /// Runs the error index generator tool to execute the tests located in the error
1787     /// index.
1788     ///
1789     /// The `error_index_generator` tool lives in `src/tools` and is used to
1790     /// generate a markdown file from the error indexes of the code base which is
1791     /// then passed to `rustdoc --test`.
1792     fn run(self, builder: &Builder<'_>) {
1793         let compiler = self.compiler;
1794
1795         let dir = testdir(builder, compiler.host);
1796         t!(fs::create_dir_all(&dir));
1797         let output = dir.join("error-index.md");
1798
1799         let mut tool = tool::ErrorIndex::command(builder);
1800         tool.arg("markdown").arg(&output);
1801
1802         builder.info(&format!("Testing error-index stage{}", compiler.stage));
1803         let _time = util::timeit(&builder);
1804         builder.run_quiet(&mut tool);
1805         // The tests themselves need to link to std, so make sure it is
1806         // available.
1807         builder.ensure(compile::Std { compiler, target: compiler.host });
1808         markdown_test(builder, compiler, &output);
1809     }
1810 }
1811
1812 fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
1813     if let Ok(contents) = fs::read_to_string(markdown) {
1814         if !contents.contains("```") {
1815             return true;
1816         }
1817     }
1818
1819     builder.info(&format!("doc tests for: {}", markdown.display()));
1820     let mut cmd = builder.rustdoc_cmd(compiler);
1821     builder.add_rust_test_threads(&mut cmd);
1822     // allow for unstable options such as new editions
1823     cmd.arg("-Z");
1824     cmd.arg("unstable-options");
1825     cmd.arg("--test");
1826     cmd.arg(markdown);
1827     cmd.env("RUSTC_BOOTSTRAP", "1");
1828
1829     let test_args = builder.config.cmd.test_args().join(" ");
1830     cmd.arg("--test-args").arg(test_args);
1831
1832     if builder.config.verbose_tests {
1833         try_run(builder, &mut cmd)
1834     } else {
1835         try_run_quiet(builder, &mut cmd)
1836     }
1837 }
1838
1839 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1840 pub struct RustcGuide;
1841
1842 impl Step for RustcGuide {
1843     type Output = ();
1844     const DEFAULT: bool = false;
1845     const ONLY_HOSTS: bool = true;
1846
1847     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1848         run.path("src/doc/rustc-dev-guide")
1849     }
1850
1851     fn make_run(run: RunConfig<'_>) {
1852         run.builder.ensure(RustcGuide);
1853     }
1854
1855     fn run(self, builder: &Builder<'_>) {
1856         let relative_path = Path::new("src").join("doc").join("rustc-dev-guide");
1857         builder.update_submodule(&relative_path);
1858
1859         let src = builder.src.join(relative_path);
1860         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1861         let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) {
1862             ToolState::TestPass
1863         } else {
1864             ToolState::TestFail
1865         };
1866         builder.save_toolstate("rustc-dev-guide", toolstate);
1867     }
1868 }
1869
1870 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1871 pub struct CrateLibrustc {
1872     compiler: Compiler,
1873     target: TargetSelection,
1874     test_kind: TestKind,
1875     krate: Interned<String>,
1876 }
1877
1878 impl Step for CrateLibrustc {
1879     type Output = ();
1880     const DEFAULT: bool = true;
1881     const ONLY_HOSTS: bool = true;
1882
1883     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1884         run.krate("rustc-main")
1885     }
1886
1887     fn make_run(run: RunConfig<'_>) {
1888         let builder = run.builder;
1889         let host = run.build_triple();
1890         let compiler = builder.compiler_for(builder.top_stage, host, host);
1891         let krate = builder.crate_paths[&run.path];
1892         let test_kind = builder.kind.into();
1893
1894         builder.ensure(CrateLibrustc { compiler, target: run.target, test_kind, krate });
1895     }
1896
1897     fn run(self, builder: &Builder<'_>) {
1898         builder.ensure(Crate {
1899             compiler: self.compiler,
1900             target: self.target,
1901             mode: Mode::Rustc,
1902             test_kind: self.test_kind,
1903             krate: self.krate,
1904         });
1905     }
1906 }
1907
1908 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1909 pub struct Crate {
1910     pub compiler: Compiler,
1911     pub target: TargetSelection,
1912     pub mode: Mode,
1913     pub test_kind: TestKind,
1914     pub krate: Interned<String>,
1915 }
1916
1917 impl Step for Crate {
1918     type Output = ();
1919     const DEFAULT: bool = true;
1920
1921     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1922         run.krate("test")
1923     }
1924
1925     fn make_run(run: RunConfig<'_>) {
1926         let builder = run.builder;
1927         let host = run.build_triple();
1928         let compiler = builder.compiler_for(builder.top_stage, host, host);
1929         let test_kind = builder.kind.into();
1930         let krate = builder.crate_paths[&run.path];
1931
1932         builder.ensure(Crate { compiler, target: run.target, mode: Mode::Std, test_kind, krate });
1933     }
1934
1935     /// Runs all unit tests plus documentation tests for a given crate defined
1936     /// by a `Cargo.toml` (single manifest)
1937     ///
1938     /// This is what runs tests for crates like the standard library, compiler, etc.
1939     /// It essentially is the driver for running `cargo test`.
1940     ///
1941     /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
1942     /// arguments, and those arguments are discovered from `cargo metadata`.
1943     fn run(self, builder: &Builder<'_>) {
1944         let compiler = self.compiler;
1945         let target = self.target;
1946         let mode = self.mode;
1947         let test_kind = self.test_kind;
1948         let krate = self.krate;
1949
1950         builder.ensure(compile::Std { compiler, target });
1951         builder.ensure(RemoteCopyLibs { compiler, target });
1952
1953         // If we're not doing a full bootstrap but we're testing a stage2
1954         // version of libstd, then what we're actually testing is the libstd
1955         // produced in stage1. Reflect that here by updating the compiler that
1956         // we're working with automatically.
1957         let compiler = builder.compiler_for(compiler.stage, compiler.host, target);
1958
1959         let mut cargo =
1960             builder.cargo(compiler, mode, SourceType::InTree, target, test_kind.subcommand());
1961         match mode {
1962             Mode::Std => {
1963                 compile::std_cargo(builder, target, compiler.stage, &mut cargo);
1964             }
1965             Mode::Rustc => {
1966                 compile::rustc_cargo(builder, &mut cargo, target);
1967             }
1968             _ => panic!("can only test libraries"),
1969         };
1970
1971         // Build up the base `cargo test` command.
1972         //
1973         // Pass in some standard flags then iterate over the graph we've discovered
1974         // in `cargo metadata` with the maps above and figure out what `-p`
1975         // arguments need to get passed.
1976         if test_kind.subcommand() == "test" && !builder.fail_fast {
1977             cargo.arg("--no-fail-fast");
1978         }
1979         match builder.doc_tests {
1980             DocTests::Only => {
1981                 cargo.arg("--doc");
1982             }
1983             DocTests::No => {
1984                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
1985             }
1986             DocTests::Yes => {}
1987         }
1988
1989         cargo.arg("-p").arg(krate);
1990
1991         // The tests are going to run with the *target* libraries, so we need to
1992         // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
1993         //
1994         // Note that to run the compiler we need to run with the *host* libraries,
1995         // but our wrapper scripts arrange for that to be the case anyway.
1996         let mut dylib_path = dylib_path();
1997         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1998         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1999
2000         cargo.arg("--");
2001         cargo.args(&builder.config.cmd.test_args());
2002
2003         if !builder.config.verbose_tests {
2004             cargo.arg("--quiet");
2005         }
2006
2007         if target.contains("emscripten") {
2008             cargo.env(
2009                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2010                 builder.config.nodejs.as_ref().expect("nodejs not configured"),
2011             );
2012         } else if target.starts_with("wasm32") {
2013             let node = builder.config.nodejs.as_ref().expect("nodejs not configured");
2014             let runner =
2015                 format!("{} {}/src/etc/wasm32-shim.js", node.display(), builder.src.display());
2016             cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), &runner);
2017         } else if builder.remote_tested(target) {
2018             cargo.env(
2019                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
2020                 format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
2021             );
2022         }
2023
2024         builder.info(&format!(
2025             "{} {} stage{} ({} -> {})",
2026             test_kind, krate, compiler.stage, &compiler.host, target
2027         ));
2028         let _time = util::timeit(&builder);
2029         try_run(builder, &mut cargo.into());
2030     }
2031 }
2032
2033 /// Rustdoc is special in various ways, which is why this step is different from `Crate`.
2034 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2035 pub struct CrateRustdoc {
2036     host: TargetSelection,
2037     test_kind: TestKind,
2038 }
2039
2040 impl Step for CrateRustdoc {
2041     type Output = ();
2042     const DEFAULT: bool = true;
2043     const ONLY_HOSTS: bool = true;
2044
2045     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2046         run.paths(&["src/librustdoc", "src/tools/rustdoc"])
2047     }
2048
2049     fn make_run(run: RunConfig<'_>) {
2050         let builder = run.builder;
2051
2052         let test_kind = builder.kind.into();
2053
2054         builder.ensure(CrateRustdoc { host: run.target, test_kind });
2055     }
2056
2057     fn run(self, builder: &Builder<'_>) {
2058         let test_kind = self.test_kind;
2059         let target = self.host;
2060
2061         let compiler = if builder.config.download_rustc {
2062             builder.compiler(builder.top_stage, target)
2063         } else {
2064             // Use the previous stage compiler to reuse the artifacts that are
2065             // created when running compiletest for src/test/rustdoc. If this used
2066             // `compiler`, then it would cause rustdoc to be built *again*, which
2067             // isn't really necessary.
2068             builder.compiler_for(builder.top_stage, target, target)
2069         };
2070         builder.ensure(compile::Rustc { compiler, target });
2071
2072         let mut cargo = tool::prepare_tool_cargo(
2073             builder,
2074             compiler,
2075             Mode::ToolRustc,
2076             target,
2077             test_kind.subcommand(),
2078             "src/tools/rustdoc",
2079             SourceType::InTree,
2080             &[],
2081         );
2082         if test_kind.subcommand() == "test" && !builder.fail_fast {
2083             cargo.arg("--no-fail-fast");
2084         }
2085         match builder.doc_tests {
2086             DocTests::Only => {
2087                 cargo.arg("--doc");
2088             }
2089             DocTests::No => {
2090                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2091             }
2092             DocTests::Yes => {}
2093         }
2094
2095         cargo.arg("-p").arg("rustdoc:0.0.0");
2096
2097         cargo.arg("--");
2098         cargo.args(&builder.config.cmd.test_args());
2099
2100         if self.host.contains("musl") {
2101             cargo.arg("'-Ctarget-feature=-crt-static'");
2102         }
2103
2104         // This is needed for running doctests on librustdoc. This is a bit of
2105         // an unfortunate interaction with how bootstrap works and how cargo
2106         // sets up the dylib path, and the fact that the doctest (in
2107         // html/markdown.rs) links to rustc-private libs. For stage1, the
2108         // compiler host dylibs (in stage1/lib) are not the same as the target
2109         // dylibs (in stage1/lib/rustlib/...). This is different from a normal
2110         // rust distribution where they are the same.
2111         //
2112         // On the cargo side, normal tests use `target_process` which handles
2113         // setting up the dylib for a *target* (stage1/lib/rustlib/... in this
2114         // case). However, for doctests it uses `rustdoc_process` which only
2115         // sets up the dylib path for the *host* (stage1/lib), which is the
2116         // wrong directory.
2117         //
2118         // Recall that we special-cased `compiler_for(top_stage)` above, so we always use stage1.
2119         //
2120         // It should be considered to just stop running doctests on
2121         // librustdoc. There is only one test, and it doesn't look too
2122         // important. There might be other ways to avoid this, but it seems
2123         // pretty convoluted.
2124         //
2125         // See also https://github.com/rust-lang/rust/issues/13983 where the
2126         // host vs target dylibs for rustdoc are consistently tricky to deal
2127         // with.
2128         //
2129         // Note that this set the host libdir for `download_rustc`, which uses a normal rust distribution.
2130         let libdir = if builder.config.download_rustc {
2131             builder.rustc_libdir(compiler)
2132         } else {
2133             builder.sysroot_libdir(compiler, target).to_path_buf()
2134         };
2135         let mut dylib_path = dylib_path();
2136         dylib_path.insert(0, PathBuf::from(&*libdir));
2137         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
2138
2139         if !builder.config.verbose_tests {
2140             cargo.arg("--quiet");
2141         }
2142
2143         builder.info(&format!(
2144             "{} rustdoc stage{} ({} -> {})",
2145             test_kind, compiler.stage, &compiler.host, target
2146         ));
2147         let _time = util::timeit(&builder);
2148
2149         try_run(builder, &mut cargo.into());
2150     }
2151 }
2152
2153 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2154 pub struct CrateRustdocJsonTypes {
2155     host: TargetSelection,
2156     test_kind: TestKind,
2157 }
2158
2159 impl Step for CrateRustdocJsonTypes {
2160     type Output = ();
2161     const DEFAULT: bool = true;
2162     const ONLY_HOSTS: bool = true;
2163
2164     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2165         run.path("src/rustdoc-json-types")
2166     }
2167
2168     fn make_run(run: RunConfig<'_>) {
2169         let builder = run.builder;
2170
2171         let test_kind = builder.kind.into();
2172
2173         builder.ensure(CrateRustdocJsonTypes { host: run.target, test_kind });
2174     }
2175
2176     fn run(self, builder: &Builder<'_>) {
2177         let test_kind = self.test_kind;
2178         let target = self.host;
2179
2180         // Use the previous stage compiler to reuse the artifacts that are
2181         // created when running compiletest for src/test/rustdoc. If this used
2182         // `compiler`, then it would cause rustdoc to be built *again*, which
2183         // isn't really necessary.
2184         let compiler = builder.compiler_for(builder.top_stage, target, target);
2185         builder.ensure(compile::Rustc { compiler, target });
2186
2187         let mut cargo = tool::prepare_tool_cargo(
2188             builder,
2189             compiler,
2190             Mode::ToolRustc,
2191             target,
2192             test_kind.subcommand(),
2193             "src/rustdoc-json-types",
2194             SourceType::InTree,
2195             &[],
2196         );
2197         if test_kind.subcommand() == "test" && !builder.fail_fast {
2198             cargo.arg("--no-fail-fast");
2199         }
2200
2201         cargo.arg("-p").arg("rustdoc-json-types");
2202
2203         cargo.arg("--");
2204         cargo.args(&builder.config.cmd.test_args());
2205
2206         if self.host.contains("musl") {
2207             cargo.arg("'-Ctarget-feature=-crt-static'");
2208         }
2209
2210         if !builder.config.verbose_tests {
2211             cargo.arg("--quiet");
2212         }
2213
2214         builder.info(&format!(
2215             "{} rustdoc-json-types stage{} ({} -> {})",
2216             test_kind, compiler.stage, &compiler.host, target
2217         ));
2218         let _time = util::timeit(&builder);
2219
2220         try_run(builder, &mut cargo.into());
2221     }
2222 }
2223
2224 /// Some test suites are run inside emulators or on remote devices, and most
2225 /// of our test binaries are linked dynamically which means we need to ship
2226 /// the standard library and such to the emulator ahead of time. This step
2227 /// represents this and is a dependency of all test suites.
2228 ///
2229 /// Most of the time this is a no-op. For some steps such as shipping data to
2230 /// QEMU we have to build our own tools so we've got conditional dependencies
2231 /// on those programs as well. Note that the remote test client is built for
2232 /// the build target (us) and the server is built for the target.
2233 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2234 pub struct RemoteCopyLibs {
2235     compiler: Compiler,
2236     target: TargetSelection,
2237 }
2238
2239 impl Step for RemoteCopyLibs {
2240     type Output = ();
2241
2242     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2243         run.never()
2244     }
2245
2246     fn run(self, builder: &Builder<'_>) {
2247         let compiler = self.compiler;
2248         let target = self.target;
2249         if !builder.remote_tested(target) {
2250             return;
2251         }
2252
2253         builder.ensure(compile::Std { compiler, target });
2254
2255         builder.info(&format!("REMOTE copy libs to emulator ({})", target));
2256
2257         let server = builder.ensure(tool::RemoteTestServer { compiler, target });
2258
2259         // Spawn the emulator and wait for it to come online
2260         let tool = builder.tool_exe(Tool::RemoteTestClient);
2261         let mut cmd = Command::new(&tool);
2262         cmd.arg("spawn-emulator").arg(target.triple).arg(&server).arg(builder.tempdir());
2263         if let Some(rootfs) = builder.qemu_rootfs(target) {
2264             cmd.arg(rootfs);
2265         }
2266         builder.run(&mut cmd);
2267
2268         // Push all our dylibs to the emulator
2269         for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
2270             let f = t!(f);
2271             let name = f.file_name().into_string().unwrap();
2272             if util::is_dylib(&name) {
2273                 builder.run(Command::new(&tool).arg("push").arg(f.path()));
2274             }
2275         }
2276     }
2277 }
2278
2279 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2280 pub struct Distcheck;
2281
2282 impl Step for Distcheck {
2283     type Output = ();
2284
2285     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2286         run.alias("distcheck")
2287     }
2288
2289     fn make_run(run: RunConfig<'_>) {
2290         run.builder.ensure(Distcheck);
2291     }
2292
2293     /// Runs "distcheck", a 'make check' from a tarball
2294     fn run(self, builder: &Builder<'_>) {
2295         builder.info("Distcheck");
2296         let dir = builder.tempdir().join("distcheck");
2297         let _ = fs::remove_dir_all(&dir);
2298         t!(fs::create_dir_all(&dir));
2299
2300         // Guarantee that these are built before we begin running.
2301         builder.ensure(dist::PlainSourceTarball);
2302         builder.ensure(dist::Src);
2303
2304         let mut cmd = Command::new("tar");
2305         cmd.arg("-xf")
2306             .arg(builder.ensure(dist::PlainSourceTarball).tarball())
2307             .arg("--strip-components=1")
2308             .current_dir(&dir);
2309         builder.run(&mut cmd);
2310         builder.run(
2311             Command::new("./configure")
2312                 .args(&builder.config.configure_args)
2313                 .arg("--enable-vendor")
2314                 .current_dir(&dir),
2315         );
2316         builder.run(
2317             Command::new(util::make(&builder.config.build.triple)).arg("check").current_dir(&dir),
2318         );
2319
2320         // Now make sure that rust-src has all of libstd's dependencies
2321         builder.info("Distcheck rust-src");
2322         let dir = builder.tempdir().join("distcheck-src");
2323         let _ = fs::remove_dir_all(&dir);
2324         t!(fs::create_dir_all(&dir));
2325
2326         let mut cmd = Command::new("tar");
2327         cmd.arg("-xf")
2328             .arg(builder.ensure(dist::Src).tarball())
2329             .arg("--strip-components=1")
2330             .current_dir(&dir);
2331         builder.run(&mut cmd);
2332
2333         let toml = dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
2334         builder.run(
2335             Command::new(&builder.initial_cargo)
2336                 .arg("generate-lockfile")
2337                 .arg("--manifest-path")
2338                 .arg(&toml)
2339                 .current_dir(&dir),
2340         );
2341     }
2342 }
2343
2344 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2345 pub struct Bootstrap;
2346
2347 impl Step for Bootstrap {
2348     type Output = ();
2349     const DEFAULT: bool = true;
2350     const ONLY_HOSTS: bool = true;
2351
2352     /// Tests the build system itself.
2353     fn run(self, builder: &Builder<'_>) {
2354         let mut check_bootstrap = Command::new(&builder.python());
2355         check_bootstrap.arg("bootstrap_test.py").current_dir(builder.src.join("src/bootstrap/"));
2356         try_run(builder, &mut check_bootstrap);
2357
2358         let mut cmd = Command::new(&builder.initial_cargo);
2359         cmd.arg("test")
2360             .current_dir(builder.src.join("src/bootstrap"))
2361             .env("RUSTFLAGS", "-Cdebuginfo=2")
2362             .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
2363             .env("RUSTC_BOOTSTRAP", "1")
2364             .env("RUSTDOC", builder.rustdoc(builder.compiler(0, builder.build.build)))
2365             .env("RUSTC", &builder.initial_rustc);
2366         if let Some(flags) = option_env!("RUSTFLAGS") {
2367             // Use the same rustc flags for testing as for "normal" compilation,
2368             // so that Cargo doesn’t recompile the entire dependency graph every time:
2369             // https://github.com/rust-lang/rust/issues/49215
2370             cmd.env("RUSTFLAGS", flags);
2371         }
2372         if !builder.fail_fast {
2373             cmd.arg("--no-fail-fast");
2374         }
2375         match builder.doc_tests {
2376             DocTests::Only => {
2377                 cmd.arg("--doc");
2378             }
2379             DocTests::No => {
2380                 cmd.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
2381             }
2382             DocTests::Yes => {}
2383         }
2384
2385         cmd.arg("--").args(&builder.config.cmd.test_args());
2386         // rustbuild tests are racy on directory creation so just run them one at a time.
2387         // Since there's not many this shouldn't be a problem.
2388         cmd.arg("--test-threads=1");
2389         try_run(builder, &mut cmd);
2390     }
2391
2392     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2393         run.path("src/bootstrap")
2394     }
2395
2396     fn make_run(run: RunConfig<'_>) {
2397         run.builder.ensure(Bootstrap);
2398     }
2399 }
2400
2401 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2402 pub struct TierCheck {
2403     pub compiler: Compiler,
2404 }
2405
2406 impl Step for TierCheck {
2407     type Output = ();
2408     const DEFAULT: bool = true;
2409     const ONLY_HOSTS: bool = true;
2410
2411     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2412         run.path("src/tools/tier-check")
2413     }
2414
2415     fn make_run(run: RunConfig<'_>) {
2416         let compiler =
2417             run.builder.compiler_for(run.builder.top_stage, run.builder.build.build, run.target);
2418         run.builder.ensure(TierCheck { compiler });
2419     }
2420
2421     /// Tests the Platform Support page in the rustc book.
2422     fn run(self, builder: &Builder<'_>) {
2423         builder.ensure(compile::Std { compiler: self.compiler, target: self.compiler.host });
2424         let mut cargo = tool::prepare_tool_cargo(
2425             builder,
2426             self.compiler,
2427             Mode::ToolStd,
2428             self.compiler.host,
2429             "run",
2430             "src/tools/tier-check",
2431             SourceType::InTree,
2432             &[],
2433         );
2434         cargo.arg(builder.src.join("src/doc/rustc/src/platform-support.md"));
2435         cargo.arg(&builder.rustc(self.compiler));
2436         if builder.is_verbose() {
2437             cargo.arg("--verbose");
2438         }
2439
2440         builder.info("platform support check");
2441         try_run(builder, &mut cargo.into());
2442     }
2443 }
2444
2445 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2446 pub struct LintDocs {
2447     pub compiler: Compiler,
2448     pub target: TargetSelection,
2449 }
2450
2451 impl Step for LintDocs {
2452     type Output = ();
2453     const DEFAULT: bool = true;
2454     const ONLY_HOSTS: bool = true;
2455
2456     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2457         run.path("src/tools/lint-docs")
2458     }
2459
2460     fn make_run(run: RunConfig<'_>) {
2461         run.builder.ensure(LintDocs {
2462             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
2463             target: run.target,
2464         });
2465     }
2466
2467     /// Tests that the lint examples in the rustc book generate the correct
2468     /// lints and have the expected format.
2469     fn run(self, builder: &Builder<'_>) {
2470         builder.ensure(crate::doc::RustcBook {
2471             compiler: self.compiler,
2472             target: self.target,
2473             validate: true,
2474         });
2475     }
2476 }