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