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