]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/test.rs
Auto merge of #86164 - FabianWolff:issue-86053, r=davidtwco
[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.add_rustc_lib_path(builder, compiler);
453             cargo.arg("--").arg("miri").arg("setup");
454
455             // Tell `cargo miri setup` where to find the sources.
456             cargo.env("XARGO_RUST_SRC", builder.src.join("library"));
457             // Tell it where to find Miri.
458             cargo.env("MIRI", &miri);
459             // Debug things.
460             cargo.env("RUST_BACKTRACE", "1");
461             // Let cargo-miri know where xargo ended up.
462             cargo.env("XARGO_CHECK", builder.out.join("bin").join("xargo-check"));
463
464             let mut cargo = Command::from(cargo);
465             if !try_run(builder, &mut cargo) {
466                 return;
467             }
468
469             // # Determine where Miri put its sysroot.
470             // To this end, we run `cargo miri setup --print-sysroot` and capture the output.
471             // (We do this separately from the above so that when the setup actually
472             // happens we get some output.)
473             // We re-use the `cargo` from above.
474             cargo.arg("--print-sysroot");
475
476             // FIXME: Is there a way in which we can re-use the usual `run` helpers?
477             let miri_sysroot = if builder.config.dry_run {
478                 String::new()
479             } else {
480                 builder.verbose(&format!("running: {:?}", cargo));
481                 let out = cargo
482                     .output()
483                     .expect("We already ran `cargo miri setup` before and that worked");
484                 assert!(out.status.success(), "`cargo miri setup` returned with non-0 exit code");
485                 // Output is "<sysroot>\n".
486                 let stdout = String::from_utf8(out.stdout)
487                     .expect("`cargo miri setup` stdout is not valid UTF-8");
488                 let sysroot = stdout.trim_end();
489                 builder.verbose(&format!("`cargo miri setup --print-sysroot` said: {:?}", sysroot));
490                 sysroot.to_owned()
491             };
492
493             // # Run `cargo test`.
494             let mut cargo = tool::prepare_tool_cargo(
495                 builder,
496                 compiler,
497                 Mode::ToolRustc,
498                 host,
499                 "test",
500                 "src/tools/miri",
501                 SourceType::Submodule,
502                 &[],
503             );
504             cargo.add_rustc_lib_path(builder, compiler);
505
506             // miri tests need to know about the stage sysroot
507             cargo.env("MIRI_SYSROOT", miri_sysroot);
508             cargo.env("RUSTC_LIB_PATH", builder.rustc_libdir(compiler));
509             cargo.env("MIRI", miri);
510
511             cargo.arg("--").args(builder.config.cmd.test_args());
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.suite_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         for path in &builder.paths {
874             if let Some(name) = path.file_name().and_then(|f| f.to_str()) {
875                 if name.ends_with(".goml") {
876                     command.arg("--file").arg(name);
877                 }
878             }
879         }
880         builder.run(&mut command);
881     }
882 }
883
884 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
885 pub struct Tidy;
886
887 impl Step for Tidy {
888     type Output = ();
889     const DEFAULT: bool = true;
890     const ONLY_HOSTS: bool = true;
891
892     /// Runs the `tidy` tool.
893     ///
894     /// This tool in `src/tools` checks up on various bits and pieces of style and
895     /// otherwise just implements a few lint-like checks that are specific to the
896     /// compiler itself.
897     ///
898     /// Once tidy passes, this step also runs `fmt --check` if tests are being run
899     /// for the `dev` or `nightly` channels.
900     fn run(self, builder: &Builder<'_>) {
901         let mut cmd = builder.tool_cmd(Tool::Tidy);
902         cmd.arg(&builder.src);
903         cmd.arg(&builder.initial_cargo);
904         cmd.arg(&builder.out);
905         cmd.arg(builder.jobs().to_string());
906         if builder.is_verbose() {
907             cmd.arg("--verbose");
908         }
909
910         builder.info("tidy check");
911         try_run(builder, &mut cmd);
912
913         if builder.config.channel == "dev" || builder.config.channel == "nightly" {
914             builder.info("fmt check");
915             if builder.config.initial_rustfmt.is_none() {
916                 let inferred_rustfmt_dir = builder.config.initial_rustc.parent().unwrap();
917                 eprintln!(
918                     "\
919 error: no `rustfmt` binary found in {PATH}
920 info: `rust.channel` is currently set to \"{CHAN}\"
921 help: if you are testing a beta branch, set `rust.channel` to \"beta\" in the `config.toml` file
922 help: to skip test's attempt to check tidiness, pass `--exclude src/tools/tidy` to `x.py test`",
923                     PATH = inferred_rustfmt_dir.display(),
924                     CHAN = builder.config.channel,
925                 );
926                 std::process::exit(1);
927             }
928             crate::format::format(&builder.build, !builder.config.cmd.bless(), &[]);
929         }
930     }
931
932     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
933         run.path("src/tools/tidy")
934     }
935
936     fn make_run(run: RunConfig<'_>) {
937         run.builder.ensure(Tidy);
938     }
939 }
940
941 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
942 pub struct ExpandYamlAnchors;
943
944 impl Step for ExpandYamlAnchors {
945     type Output = ();
946     const ONLY_HOSTS: bool = true;
947
948     /// Ensure the `generate-ci-config` tool was run locally.
949     ///
950     /// The tool in `src/tools` reads the CI definition in `src/ci/builders.yml` and generates the
951     /// appropriate configuration for all our CI providers. This step ensures the tool was called
952     /// by the user before committing CI changes.
953     fn run(self, builder: &Builder<'_>) {
954         builder.info("Ensuring the YAML anchors in the GitHub Actions config were expanded");
955         try_run(
956             builder,
957             &mut builder.tool_cmd(Tool::ExpandYamlAnchors).arg("check").arg(&builder.src),
958         );
959     }
960
961     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
962         run.path("src/tools/expand-yaml-anchors")
963     }
964
965     fn make_run(run: RunConfig<'_>) {
966         run.builder.ensure(ExpandYamlAnchors);
967     }
968 }
969
970 fn testdir(builder: &Builder<'_>, host: TargetSelection) -> PathBuf {
971     builder.out.join(host.triple).join("test")
972 }
973
974 macro_rules! default_test {
975     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
976         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: false });
977     };
978 }
979
980 macro_rules! default_test_with_compare_mode {
981     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr,
982                    compare_mode: $compare_mode:expr }) => {
983         test_with_compare_mode!($name {
984             path: $path,
985             mode: $mode,
986             suite: $suite,
987             default: true,
988             host: false,
989             compare_mode: $compare_mode
990         });
991     };
992 }
993
994 macro_rules! host_test {
995     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr }) => {
996         test!($name { path: $path, mode: $mode, suite: $suite, default: true, host: true });
997     };
998 }
999
1000 macro_rules! test {
1001     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1002                    host: $host:expr }) => {
1003         test_definitions!($name {
1004             path: $path,
1005             mode: $mode,
1006             suite: $suite,
1007             default: $default,
1008             host: $host,
1009             compare_mode: None
1010         });
1011     };
1012 }
1013
1014 macro_rules! test_with_compare_mode {
1015     ($name:ident { path: $path:expr, mode: $mode:expr, suite: $suite:expr, default: $default:expr,
1016                    host: $host:expr, compare_mode: $compare_mode:expr }) => {
1017         test_definitions!($name {
1018             path: $path,
1019             mode: $mode,
1020             suite: $suite,
1021             default: $default,
1022             host: $host,
1023             compare_mode: Some($compare_mode)
1024         });
1025     };
1026 }
1027
1028 macro_rules! test_definitions {
1029     ($name:ident {
1030         path: $path:expr,
1031         mode: $mode:expr,
1032         suite: $suite:expr,
1033         default: $default:expr,
1034         host: $host:expr,
1035         compare_mode: $compare_mode:expr
1036     }) => {
1037         #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1038         pub struct $name {
1039             pub compiler: Compiler,
1040             pub target: TargetSelection,
1041         }
1042
1043         impl Step for $name {
1044             type Output = ();
1045             const DEFAULT: bool = $default;
1046             const ONLY_HOSTS: bool = $host;
1047
1048             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1049                 run.suite_path($path)
1050             }
1051
1052             fn make_run(run: RunConfig<'_>) {
1053                 let compiler = run.builder.compiler(run.builder.top_stage, run.build_triple());
1054
1055                 run.builder.ensure($name { compiler, target: run.target });
1056             }
1057
1058             fn run(self, builder: &Builder<'_>) {
1059                 builder.ensure(Compiletest {
1060                     compiler: self.compiler,
1061                     target: self.target,
1062                     mode: $mode,
1063                     suite: $suite,
1064                     path: $path,
1065                     compare_mode: $compare_mode,
1066                 })
1067             }
1068         }
1069     };
1070 }
1071
1072 default_test_with_compare_mode!(Ui {
1073     path: "src/test/ui",
1074     mode: "ui",
1075     suite: "ui",
1076     compare_mode: "nll"
1077 });
1078
1079 default_test!(RunPassValgrind {
1080     path: "src/test/run-pass-valgrind",
1081     mode: "run-pass-valgrind",
1082     suite: "run-pass-valgrind"
1083 });
1084
1085 default_test!(MirOpt { path: "src/test/mir-opt", mode: "mir-opt", suite: "mir-opt" });
1086
1087 default_test!(Codegen { path: "src/test/codegen", mode: "codegen", suite: "codegen" });
1088
1089 default_test!(CodegenUnits {
1090     path: "src/test/codegen-units",
1091     mode: "codegen-units",
1092     suite: "codegen-units"
1093 });
1094
1095 default_test!(Incremental {
1096     path: "src/test/incremental",
1097     mode: "incremental",
1098     suite: "incremental"
1099 });
1100
1101 default_test_with_compare_mode!(Debuginfo {
1102     path: "src/test/debuginfo",
1103     mode: "debuginfo",
1104     suite: "debuginfo",
1105     compare_mode: "split-dwarf"
1106 });
1107
1108 host_test!(UiFullDeps { path: "src/test/ui-fulldeps", mode: "ui", suite: "ui-fulldeps" });
1109
1110 host_test!(Rustdoc { path: "src/test/rustdoc", mode: "rustdoc", suite: "rustdoc" });
1111 host_test!(RustdocUi { path: "src/test/rustdoc-ui", mode: "ui", suite: "rustdoc-ui" });
1112
1113 host_test!(RustdocJson {
1114     path: "src/test/rustdoc-json",
1115     mode: "rustdoc-json",
1116     suite: "rustdoc-json"
1117 });
1118
1119 host_test!(Pretty { path: "src/test/pretty", mode: "pretty", suite: "pretty" });
1120
1121 default_test!(RunMake { path: "src/test/run-make", mode: "run-make", suite: "run-make" });
1122
1123 host_test!(RunMakeFullDeps {
1124     path: "src/test/run-make-fulldeps",
1125     mode: "run-make",
1126     suite: "run-make-fulldeps"
1127 });
1128
1129 default_test!(Assembly { path: "src/test/assembly", mode: "assembly", suite: "assembly" });
1130
1131 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1132 struct Compiletest {
1133     compiler: Compiler,
1134     target: TargetSelection,
1135     mode: &'static str,
1136     suite: &'static str,
1137     path: &'static str,
1138     compare_mode: Option<&'static str>,
1139 }
1140
1141 impl Step for Compiletest {
1142     type Output = ();
1143
1144     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1145         run.never()
1146     }
1147
1148     /// Executes the `compiletest` tool to run a suite of tests.
1149     ///
1150     /// Compiles all tests with `compiler` for `target` with the specified
1151     /// compiletest `mode` and `suite` arguments. For example `mode` can be
1152     /// "run-pass" or `suite` can be something like `debuginfo`.
1153     fn run(self, builder: &Builder<'_>) {
1154         if builder.top_stage == 0 && env::var("COMPILETEST_FORCE_STAGE0").is_err() {
1155             eprintln!("\
1156 error: `--stage 0` runs compiletest on the beta compiler, not your local changes, and will almost always cause tests to fail
1157 help: to test the compiler, use `--stage 1` instead
1158 help: to test the standard library, use `--stage 0 library/std` instead
1159 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`."
1160             );
1161             std::process::exit(1);
1162         }
1163
1164         let compiler = self.compiler;
1165         let target = self.target;
1166         let mode = self.mode;
1167         let suite = self.suite;
1168
1169         // Path for test suite
1170         let suite_path = self.path;
1171
1172         // Skip codegen tests if they aren't enabled in configuration.
1173         if !builder.config.codegen_tests && suite == "codegen" {
1174             return;
1175         }
1176
1177         if suite == "debuginfo" {
1178             builder
1179                 .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target });
1180         }
1181
1182         if suite.ends_with("fulldeps") {
1183             builder.ensure(compile::Rustc { compiler, target });
1184         }
1185
1186         builder.ensure(compile::Std { compiler, target });
1187         // ensure that `libproc_macro` is available on the host.
1188         builder.ensure(compile::Std { compiler, target: compiler.host });
1189
1190         // Also provide `rust_test_helpers` for the host.
1191         builder.ensure(native::TestHelpers { target: compiler.host });
1192
1193         // As well as the target, except for plain wasm32, which can't build it
1194         if !target.contains("wasm32") || target.contains("emscripten") {
1195             builder.ensure(native::TestHelpers { target });
1196         }
1197
1198         builder.ensure(RemoteCopyLibs { compiler, target });
1199
1200         let mut cmd = builder.tool_cmd(Tool::Compiletest);
1201
1202         // compiletest currently has... a lot of arguments, so let's just pass all
1203         // of them!
1204
1205         cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
1206         cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
1207         cmd.arg("--rustc-path").arg(builder.rustc(compiler));
1208
1209         let is_rustdoc = suite.ends_with("rustdoc-ui") || suite.ends_with("rustdoc-js");
1210
1211         // Avoid depending on rustdoc when we don't need it.
1212         if mode == "rustdoc"
1213             || mode == "run-make"
1214             || (mode == "ui" && is_rustdoc)
1215             || mode == "js-doc-test"
1216             || mode == "rustdoc-json"
1217         {
1218             cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler));
1219         }
1220
1221         if mode == "rustdoc-json" {
1222             // Use the beta compiler for jsondocck
1223             let json_compiler = compiler.with_stage(0);
1224             cmd.arg("--jsondocck-path")
1225                 .arg(builder.ensure(tool::JsonDocCk { compiler: json_compiler, target }));
1226         }
1227
1228         if mode == "run-make" && suite.ends_with("fulldeps") {
1229             let rust_demangler = builder
1230                 .ensure(tool::RustDemangler { compiler, target, extra_features: Vec::new() })
1231                 .expect("in-tree tool");
1232             cmd.arg("--rust-demangler-path").arg(rust_demangler);
1233         }
1234
1235         cmd.arg("--src-base").arg(builder.src.join("src/test").join(suite));
1236         cmd.arg("--build-base").arg(testdir(builder, compiler.host).join(suite));
1237         cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
1238         cmd.arg("--suite").arg(suite);
1239         cmd.arg("--mode").arg(mode);
1240         cmd.arg("--target").arg(target.rustc_target_arg());
1241         cmd.arg("--host").arg(&*compiler.host.triple);
1242         cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.build));
1243
1244         if builder.config.cmd.bless() {
1245             cmd.arg("--bless");
1246         }
1247
1248         let compare_mode =
1249             builder.config.cmd.compare_mode().or_else(|| {
1250                 if builder.config.test_compare_mode { self.compare_mode } else { None }
1251             });
1252
1253         if let Some(ref pass) = builder.config.cmd.pass() {
1254             cmd.arg("--pass");
1255             cmd.arg(pass);
1256         }
1257
1258         if let Some(ref run) = builder.config.cmd.run() {
1259             cmd.arg("--run");
1260             cmd.arg(run);
1261         }
1262
1263         if let Some(ref nodejs) = builder.config.nodejs {
1264             cmd.arg("--nodejs").arg(nodejs);
1265         }
1266         if let Some(ref npm) = builder.config.npm {
1267             cmd.arg("--npm").arg(npm);
1268         }
1269
1270         let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] };
1271         if !is_rustdoc {
1272             if builder.config.rust_optimize_tests {
1273                 flags.push("-O".to_string());
1274             }
1275         }
1276         flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests));
1277         flags.push(builder.config.cmd.rustc_args().join(" "));
1278
1279         if let Some(linker) = builder.linker(target) {
1280             cmd.arg("--linker").arg(linker);
1281         }
1282
1283         let mut hostflags = flags.clone();
1284         hostflags.push(format!("-Lnative={}", builder.test_helpers_out(compiler.host).display()));
1285         hostflags.extend(builder.lld_flags(compiler.host));
1286         cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
1287
1288         let mut targetflags = flags;
1289         targetflags.push(format!("-Lnative={}", builder.test_helpers_out(target).display()));
1290         targetflags.extend(builder.lld_flags(target));
1291         cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
1292
1293         cmd.arg("--docck-python").arg(builder.python());
1294
1295         if builder.config.build.ends_with("apple-darwin") {
1296             // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1297             // LLDB plugin's compiled module which only works with the system python
1298             // (namely not Homebrew-installed python)
1299             cmd.arg("--lldb-python").arg("/usr/bin/python3");
1300         } else {
1301             cmd.arg("--lldb-python").arg(builder.python());
1302         }
1303
1304         if let Some(ref gdb) = builder.config.gdb {
1305             cmd.arg("--gdb").arg(gdb);
1306         }
1307
1308         let run = |cmd: &mut Command| {
1309             cmd.output().map(|output| {
1310                 String::from_utf8_lossy(&output.stdout)
1311                     .lines()
1312                     .next()
1313                     .unwrap_or_else(|| panic!("{:?} failed {:?}", cmd, output))
1314                     .to_string()
1315             })
1316         };
1317         let lldb_exe = "lldb";
1318         let lldb_version = Command::new(lldb_exe)
1319             .arg("--version")
1320             .output()
1321             .map(|output| String::from_utf8_lossy(&output.stdout).to_string())
1322             .ok();
1323         if let Some(ref vers) = lldb_version {
1324             cmd.arg("--lldb-version").arg(vers);
1325             let lldb_python_dir = run(Command::new(lldb_exe).arg("-P")).ok();
1326             if let Some(ref dir) = lldb_python_dir {
1327                 cmd.arg("--lldb-python-dir").arg(dir);
1328             }
1329         }
1330
1331         if util::forcing_clang_based_tests() {
1332             let clang_exe = builder.llvm_out(target).join("bin").join("clang");
1333             cmd.arg("--run-clang-based-tests-with").arg(clang_exe);
1334         }
1335
1336         // Get paths from cmd args
1337         let paths = match &builder.config.cmd {
1338             Subcommand::Test { ref paths, .. } => &paths[..],
1339             _ => &[],
1340         };
1341
1342         // Get test-args by striping suite path
1343         let mut test_args: Vec<&str> = paths
1344             .iter()
1345             .map(|p| match p.strip_prefix(".") {
1346                 Ok(path) => path,
1347                 Err(_) => p,
1348             })
1349             .filter(|p| p.starts_with(suite_path))
1350             .filter(|p| {
1351                 let exists = p.is_dir() || p.is_file();
1352                 if !exists {
1353                     if let Some(p) = p.to_str() {
1354                         builder.info(&format!(
1355                             "Warning: Skipping \"{}\": not a regular file or directory",
1356                             p
1357                         ));
1358                     }
1359                 }
1360                 exists
1361             })
1362             .filter_map(|p| {
1363                 // Since test suite paths are themselves directories, if we don't
1364                 // specify a directory or file, we'll get an empty string here
1365                 // (the result of the test suite directory without its suite prefix).
1366                 // Therefore, we need to filter these out, as only the first --test-args
1367                 // flag is respected, so providing an empty --test-args conflicts with
1368                 // any following it.
1369                 match p.strip_prefix(suite_path).ok().and_then(|p| p.to_str()) {
1370                     Some(s) if !s.is_empty() => Some(s),
1371                     _ => None,
1372                 }
1373             })
1374             .collect();
1375
1376         test_args.append(&mut builder.config.cmd.test_args());
1377
1378         cmd.args(&test_args);
1379
1380         if builder.is_verbose() {
1381             cmd.arg("--verbose");
1382         }
1383
1384         if !builder.config.verbose_tests {
1385             cmd.arg("--quiet");
1386         }
1387
1388         let mut llvm_components_passed = false;
1389         let mut copts_passed = false;
1390         if builder.config.llvm_enabled() {
1391             let llvm_config = builder.ensure(native::Llvm { target: builder.config.build });
1392             if !builder.config.dry_run {
1393                 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
1394                 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
1395                 // Remove trailing newline from llvm-config output.
1396                 cmd.arg("--llvm-version")
1397                     .arg(llvm_version.trim())
1398                     .arg("--llvm-components")
1399                     .arg(llvm_components.trim());
1400                 llvm_components_passed = true;
1401             }
1402             if !builder.is_rust_llvm(target) {
1403                 cmd.arg("--system-llvm");
1404             }
1405
1406             // Tests that use compiler libraries may inherit the `-lLLVM` link
1407             // requirement, but the `-L` library path is not propagated across
1408             // separate compilations. We can add LLVM's library path to the
1409             // platform-specific environment variable as a workaround.
1410             if !builder.config.dry_run && suite.ends_with("fulldeps") {
1411                 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1412                 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cmd);
1413             }
1414
1415             // Only pass correct values for these flags for the `run-make` suite as it
1416             // requires that a C++ compiler was configured which isn't always the case.
1417             if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1418                 // The llvm/bin directory contains many useful cross-platform
1419                 // tools. Pass the path to run-make tests so they can use them.
1420                 let llvm_bin_path = llvm_config
1421                     .parent()
1422                     .expect("Expected llvm-config to be contained in directory");
1423                 assert!(llvm_bin_path.is_dir());
1424                 cmd.arg("--llvm-bin-dir").arg(llvm_bin_path);
1425
1426                 // If LLD is available, add it to the PATH
1427                 if builder.config.lld_enabled {
1428                     let lld_install_root =
1429                         builder.ensure(native::Lld { target: builder.config.build });
1430
1431                     let lld_bin_path = lld_install_root.join("bin");
1432
1433                     let old_path = env::var_os("PATH").unwrap_or_default();
1434                     let new_path = env::join_paths(
1435                         std::iter::once(lld_bin_path).chain(env::split_paths(&old_path)),
1436                     )
1437                     .expect("Could not add LLD bin path to PATH");
1438                     cmd.env("PATH", new_path);
1439                 }
1440             }
1441         }
1442
1443         // Only pass correct values for these flags for the `run-make` suite as it
1444         // requires that a C++ compiler was configured which isn't always the case.
1445         if !builder.config.dry_run && matches!(suite, "run-make" | "run-make-fulldeps") {
1446             cmd.arg("--cc")
1447                 .arg(builder.cc(target))
1448                 .arg("--cxx")
1449                 .arg(builder.cxx(target).unwrap())
1450                 .arg("--cflags")
1451                 .arg(builder.cflags(target, GitRepo::Rustc).join(" "));
1452             copts_passed = true;
1453             if let Some(ar) = builder.ar(target) {
1454                 cmd.arg("--ar").arg(ar);
1455             }
1456         }
1457
1458         if !llvm_components_passed {
1459             cmd.arg("--llvm-components").arg("");
1460         }
1461         if !copts_passed {
1462             cmd.arg("--cc").arg("").arg("--cxx").arg("").arg("--cflags").arg("");
1463         }
1464
1465         if builder.remote_tested(target) {
1466             cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
1467         }
1468
1469         // Running a C compiler on MSVC requires a few env vars to be set, to be
1470         // sure to set them here.
1471         //
1472         // Note that if we encounter `PATH` we make sure to append to our own `PATH`
1473         // rather than stomp over it.
1474         if target.contains("msvc") {
1475             for &(ref k, ref v) in builder.cc[&target].env() {
1476                 if k != "PATH" {
1477                     cmd.env(k, v);
1478                 }
1479             }
1480         }
1481         cmd.env("RUSTC_BOOTSTRAP", "1");
1482         cmd.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel());
1483         builder.add_rust_test_threads(&mut cmd);
1484
1485         if builder.config.sanitizers_enabled(target) {
1486             cmd.env("RUSTC_SANITIZER_SUPPORT", "1");
1487         }
1488
1489         if builder.config.profiler_enabled(target) {
1490             cmd.env("RUSTC_PROFILER_SUPPORT", "1");
1491         }
1492
1493         let tmp = builder.out.join("tmp");
1494         std::fs::create_dir_all(&tmp).unwrap();
1495         cmd.env("RUST_TEST_TMPDIR", tmp);
1496
1497         cmd.arg("--adb-path").arg("adb");
1498         cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
1499         if target.contains("android") {
1500             // Assume that cc for this target comes from the android sysroot
1501             cmd.arg("--android-cross-path")
1502                 .arg(builder.cc(target).parent().unwrap().parent().unwrap());
1503         } else {
1504             cmd.arg("--android-cross-path").arg("");
1505         }
1506
1507         if builder.config.cmd.rustfix_coverage() {
1508             cmd.arg("--rustfix-coverage");
1509         }
1510
1511         cmd.env("BOOTSTRAP_CARGO", &builder.initial_cargo);
1512
1513         cmd.arg("--channel").arg(&builder.config.channel);
1514
1515         builder.ci_env.force_coloring_in_ci(&mut cmd);
1516
1517         builder.info(&format!(
1518             "Check compiletest suite={} mode={} ({} -> {})",
1519             suite, mode, &compiler.host, target
1520         ));
1521         let _time = util::timeit(&builder);
1522         try_run(builder, &mut cmd);
1523
1524         if let Some(compare_mode) = compare_mode {
1525             cmd.arg("--compare-mode").arg(compare_mode);
1526             builder.info(&format!(
1527                 "Check compiletest suite={} mode={} compare_mode={} ({} -> {})",
1528                 suite, mode, compare_mode, &compiler.host, target
1529             ));
1530             let _time = util::timeit(&builder);
1531             try_run(builder, &mut cmd);
1532         }
1533     }
1534 }
1535
1536 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1537 struct BookTest {
1538     compiler: Compiler,
1539     path: PathBuf,
1540     name: &'static str,
1541     is_ext_doc: bool,
1542 }
1543
1544 impl Step for BookTest {
1545     type Output = ();
1546     const ONLY_HOSTS: bool = true;
1547
1548     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1549         run.never()
1550     }
1551
1552     /// Runs the documentation tests for a book in `src/doc`.
1553     ///
1554     /// This uses the `rustdoc` that sits next to `compiler`.
1555     fn run(self, builder: &Builder<'_>) {
1556         // External docs are different from local because:
1557         // - Some books need pre-processing by mdbook before being tested.
1558         // - They need to save their state to toolstate.
1559         // - They are only tested on the "checktools" builders.
1560         //
1561         // The local docs are tested by default, and we don't want to pay the
1562         // cost of building mdbook, so they use `rustdoc --test` directly.
1563         // Also, the unstable book is special because SUMMARY.md is generated,
1564         // so it is easier to just run `rustdoc` on its files.
1565         if self.is_ext_doc {
1566             self.run_ext_doc(builder);
1567         } else {
1568             self.run_local_doc(builder);
1569         }
1570     }
1571 }
1572
1573 impl BookTest {
1574     /// This runs the equivalent of `mdbook test` (via the rustbook wrapper)
1575     /// which in turn runs `rustdoc --test` on each file in the book.
1576     fn run_ext_doc(self, builder: &Builder<'_>) {
1577         let compiler = self.compiler;
1578
1579         builder.ensure(compile::Std { compiler, target: compiler.host });
1580
1581         // mdbook just executes a binary named "rustdoc", so we need to update
1582         // PATH so that it points to our rustdoc.
1583         let mut rustdoc_path = builder.rustdoc(compiler);
1584         rustdoc_path.pop();
1585         let old_path = env::var_os("PATH").unwrap_or_default();
1586         let new_path = env::join_paths(iter::once(rustdoc_path).chain(env::split_paths(&old_path)))
1587             .expect("could not add rustdoc to PATH");
1588
1589         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1590         let path = builder.src.join(&self.path);
1591         rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
1592         builder.add_rust_test_threads(&mut rustbook_cmd);
1593         builder.info(&format!("Testing rustbook {}", self.path.display()));
1594         let _time = util::timeit(&builder);
1595         let toolstate = if try_run(builder, &mut rustbook_cmd) {
1596             ToolState::TestPass
1597         } else {
1598             ToolState::TestFail
1599         };
1600         builder.save_toolstate(self.name, toolstate);
1601     }
1602
1603     /// This runs `rustdoc --test` on all `.md` files in the path.
1604     fn run_local_doc(self, builder: &Builder<'_>) {
1605         let compiler = self.compiler;
1606
1607         builder.ensure(compile::Std { compiler, target: compiler.host });
1608
1609         // Do a breadth-first traversal of the `src/doc` directory and just run
1610         // tests for all files that end in `*.md`
1611         let mut stack = vec![builder.src.join(self.path)];
1612         let _time = util::timeit(&builder);
1613         let mut files = Vec::new();
1614         while let Some(p) = stack.pop() {
1615             if p.is_dir() {
1616                 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
1617                 continue;
1618             }
1619
1620             if p.extension().and_then(|s| s.to_str()) != Some("md") {
1621                 continue;
1622             }
1623
1624             files.push(p);
1625         }
1626
1627         files.sort();
1628
1629         for file in files {
1630             markdown_test(builder, compiler, &file);
1631         }
1632     }
1633 }
1634
1635 macro_rules! test_book {
1636     ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => {
1637         $(
1638             #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1639             pub struct $name {
1640                 compiler: Compiler,
1641             }
1642
1643             impl Step for $name {
1644                 type Output = ();
1645                 const DEFAULT: bool = $default;
1646                 const ONLY_HOSTS: bool = true;
1647
1648                 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1649                     run.path($path)
1650                 }
1651
1652                 fn make_run(run: RunConfig<'_>) {
1653                     run.builder.ensure($name {
1654                         compiler: run.builder.compiler(run.builder.top_stage, run.target),
1655                     });
1656                 }
1657
1658                 fn run(self, builder: &Builder<'_>) {
1659                     builder.ensure(BookTest {
1660                         compiler: self.compiler,
1661                         path: PathBuf::from($path),
1662                         name: $book_name,
1663                         is_ext_doc: !$default,
1664                     });
1665                 }
1666             }
1667         )+
1668     }
1669 }
1670
1671 test_book!(
1672     Nomicon, "src/doc/nomicon", "nomicon", default=false;
1673     Reference, "src/doc/reference", "reference", default=false;
1674     RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
1675     RustcBook, "src/doc/rustc", "rustc", default=true;
1676     RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
1677     EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
1678     TheBook, "src/doc/book", "book", default=false;
1679     UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
1680     EditionGuide, "src/doc/edition-guide", "edition-guide", default=false;
1681 );
1682
1683 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1684 pub struct ErrorIndex {
1685     compiler: Compiler,
1686 }
1687
1688 impl Step for ErrorIndex {
1689     type Output = ();
1690     const DEFAULT: bool = true;
1691     const ONLY_HOSTS: bool = true;
1692
1693     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1694         run.path("src/tools/error_index_generator")
1695     }
1696
1697     fn make_run(run: RunConfig<'_>) {
1698         // error_index_generator depends on librustdoc. Use the compiler that
1699         // is normally used to build rustdoc for other tests (like compiletest
1700         // tests in src/test/rustdoc) so that it shares the same artifacts.
1701         let compiler = run.builder.compiler(run.builder.top_stage, run.builder.config.build);
1702         run.builder.ensure(ErrorIndex { compiler });
1703     }
1704
1705     /// Runs the error index generator tool to execute the tests located in the error
1706     /// index.
1707     ///
1708     /// The `error_index_generator` tool lives in `src/tools` and is used to
1709     /// generate a markdown file from the error indexes of the code base which is
1710     /// then passed to `rustdoc --test`.
1711     fn run(self, builder: &Builder<'_>) {
1712         let compiler = self.compiler;
1713
1714         let dir = testdir(builder, compiler.host);
1715         t!(fs::create_dir_all(&dir));
1716         let output = dir.join("error-index.md");
1717
1718         let mut tool = tool::ErrorIndex::command(builder);
1719         tool.arg("markdown").arg(&output);
1720
1721         builder.info(&format!("Testing error-index stage{}", compiler.stage));
1722         let _time = util::timeit(&builder);
1723         builder.run_quiet(&mut tool);
1724         // The tests themselves need to link to std, so make sure it is
1725         // available.
1726         builder.ensure(compile::Std { compiler, target: compiler.host });
1727         markdown_test(builder, compiler, &output);
1728     }
1729 }
1730
1731 fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> bool {
1732     if let Ok(contents) = fs::read_to_string(markdown) {
1733         if !contents.contains("```") {
1734             return true;
1735         }
1736     }
1737
1738     builder.info(&format!("doc tests for: {}", markdown.display()));
1739     let mut cmd = builder.rustdoc_cmd(compiler);
1740     builder.add_rust_test_threads(&mut cmd);
1741     // allow for unstable options such as new editions
1742     cmd.arg("-Z");
1743     cmd.arg("unstable-options");
1744     cmd.arg("--test");
1745     cmd.arg(markdown);
1746     cmd.env("RUSTC_BOOTSTRAP", "1");
1747
1748     let test_args = builder.config.cmd.test_args().join(" ");
1749     cmd.arg("--test-args").arg(test_args);
1750
1751     if builder.config.verbose_tests {
1752         try_run(builder, &mut cmd)
1753     } else {
1754         try_run_quiet(builder, &mut cmd)
1755     }
1756 }
1757
1758 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1759 pub struct RustcGuide;
1760
1761 impl Step for RustcGuide {
1762     type Output = ();
1763     const DEFAULT: bool = false;
1764     const ONLY_HOSTS: bool = true;
1765
1766     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1767         run.path("src/doc/rustc-dev-guide")
1768     }
1769
1770     fn make_run(run: RunConfig<'_>) {
1771         run.builder.ensure(RustcGuide);
1772     }
1773
1774     fn run(self, builder: &Builder<'_>) {
1775         let src = builder.src.join("src/doc/rustc-dev-guide");
1776         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
1777         let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)) {
1778             ToolState::TestPass
1779         } else {
1780             ToolState::TestFail
1781         };
1782         builder.save_toolstate("rustc-dev-guide", toolstate);
1783     }
1784 }
1785
1786 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1787 pub struct CrateLibrustc {
1788     compiler: Compiler,
1789     target: TargetSelection,
1790     test_kind: TestKind,
1791     krate: Interned<String>,
1792 }
1793
1794 impl Step for CrateLibrustc {
1795     type Output = ();
1796     const DEFAULT: bool = true;
1797     const ONLY_HOSTS: bool = true;
1798
1799     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1800         run.krate("rustc-main")
1801     }
1802
1803     fn make_run(run: RunConfig<'_>) {
1804         let builder = run.builder;
1805         let compiler = builder.compiler(builder.top_stage, run.build_triple());
1806
1807         for krate in builder.in_tree_crates("rustc-main", Some(run.target)) {
1808             if krate.path.ends_with(&run.path) {
1809                 let test_kind = builder.kind.into();
1810
1811                 builder.ensure(CrateLibrustc {
1812                     compiler,
1813                     target: run.target,
1814                     test_kind,
1815                     krate: krate.name,
1816                 });
1817             }
1818         }
1819     }
1820
1821     fn run(self, builder: &Builder<'_>) {
1822         builder.ensure(Crate {
1823             compiler: self.compiler,
1824             target: self.target,
1825             mode: Mode::Rustc,
1826             test_kind: self.test_kind,
1827             krate: self.krate,
1828         });
1829     }
1830 }
1831
1832 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1833 pub struct Crate {
1834     pub compiler: Compiler,
1835     pub target: TargetSelection,
1836     pub mode: Mode,
1837     pub test_kind: TestKind,
1838     pub krate: Interned<String>,
1839 }
1840
1841 impl Step for Crate {
1842     type Output = ();
1843     const DEFAULT: bool = true;
1844
1845     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1846         run.krate("test")
1847     }
1848
1849     fn make_run(run: RunConfig<'_>) {
1850         let builder = run.builder;
1851         let compiler = builder.compiler(builder.top_stage, run.build_triple());
1852
1853         let make = |mode: Mode, krate: &CargoCrate| {
1854             let test_kind = builder.kind.into();
1855
1856             builder.ensure(Crate {
1857                 compiler,
1858                 target: run.target,
1859                 mode,
1860                 test_kind,
1861                 krate: krate.name,
1862             });
1863         };
1864
1865         for krate in builder.in_tree_crates("test", Some(run.target)) {
1866             if krate.path.ends_with(&run.path) {
1867                 make(Mode::Std, krate);
1868             }
1869         }
1870     }
1871
1872     /// Runs all unit tests plus documentation tests for a given crate defined
1873     /// by a `Cargo.toml` (single manifest)
1874     ///
1875     /// This is what runs tests for crates like the standard library, compiler, etc.
1876     /// It essentially is the driver for running `cargo test`.
1877     ///
1878     /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
1879     /// arguments, and those arguments are discovered from `cargo metadata`.
1880     fn run(self, builder: &Builder<'_>) {
1881         let compiler = self.compiler;
1882         let target = self.target;
1883         let mode = self.mode;
1884         let test_kind = self.test_kind;
1885         let krate = self.krate;
1886
1887         builder.ensure(compile::Std { compiler, target });
1888         builder.ensure(RemoteCopyLibs { compiler, target });
1889
1890         // If we're not doing a full bootstrap but we're testing a stage2
1891         // version of libstd, then what we're actually testing is the libstd
1892         // produced in stage1. Reflect that here by updating the compiler that
1893         // we're working with automatically.
1894         let compiler = builder.compiler_for(compiler.stage, compiler.host, target);
1895
1896         let mut cargo =
1897             builder.cargo(compiler, mode, SourceType::InTree, target, test_kind.subcommand());
1898         match mode {
1899             Mode::Std => {
1900                 compile::std_cargo(builder, target, compiler.stage, &mut cargo);
1901             }
1902             Mode::Rustc => {
1903                 builder.ensure(compile::Rustc { compiler, target });
1904                 compile::rustc_cargo(builder, &mut cargo, target);
1905             }
1906             _ => panic!("can only test libraries"),
1907         };
1908
1909         // Build up the base `cargo test` command.
1910         //
1911         // Pass in some standard flags then iterate over the graph we've discovered
1912         // in `cargo metadata` with the maps above and figure out what `-p`
1913         // arguments need to get passed.
1914         if test_kind.subcommand() == "test" && !builder.fail_fast {
1915             cargo.arg("--no-fail-fast");
1916         }
1917         match builder.doc_tests {
1918             DocTests::Only => {
1919                 cargo.arg("--doc");
1920             }
1921             DocTests::No => {
1922                 cargo.args(&["--lib", "--bins", "--examples", "--tests", "--benches"]);
1923             }
1924             DocTests::Yes => {}
1925         }
1926
1927         cargo.arg("-p").arg(krate);
1928
1929         // The tests are going to run with the *target* libraries, so we need to
1930         // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
1931         //
1932         // Note that to run the compiler we need to run with the *host* libraries,
1933         // but our wrapper scripts arrange for that to be the case anyway.
1934         let mut dylib_path = dylib_path();
1935         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1936         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1937
1938         cargo.arg("--");
1939         cargo.args(&builder.config.cmd.test_args());
1940
1941         if !builder.config.verbose_tests {
1942             cargo.arg("--quiet");
1943         }
1944
1945         if target.contains("emscripten") {
1946             cargo.env(
1947                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
1948                 builder.config.nodejs.as_ref().expect("nodejs not configured"),
1949             );
1950         } else if target.starts_with("wasm32") {
1951             let node = builder.config.nodejs.as_ref().expect("nodejs not configured");
1952             let runner =
1953                 format!("{} {}/src/etc/wasm32-shim.js", node.display(), builder.src.display());
1954             cargo.env(format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)), &runner);
1955         } else if builder.remote_tested(target) {
1956             cargo.env(
1957                 format!("CARGO_TARGET_{}_RUNNER", envify(&target.triple)),
1958                 format!("{} run 0", builder.tool_exe(Tool::RemoteTestClient).display()),
1959             );
1960         }
1961
1962         builder.info(&format!(
1963             "{} {} stage{} ({} -> {})",
1964             test_kind, krate, compiler.stage, &compiler.host, target
1965         ));
1966         let _time = util::timeit(&builder);
1967         try_run(builder, &mut cargo.into());
1968     }
1969 }
1970
1971 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1972 pub struct CrateRustdoc {
1973     host: TargetSelection,
1974     test_kind: TestKind,
1975 }
1976
1977 impl Step for CrateRustdoc {
1978     type Output = ();
1979     const DEFAULT: bool = true;
1980     const ONLY_HOSTS: bool = true;
1981
1982     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1983         run.paths(&["src/librustdoc", "src/tools/rustdoc"])
1984     }
1985
1986     fn make_run(run: RunConfig<'_>) {
1987         let builder = run.builder;
1988
1989         let test_kind = builder.kind.into();
1990
1991         builder.ensure(CrateRustdoc { host: run.target, test_kind });
1992     }
1993
1994     fn run(self, builder: &Builder<'_>) {
1995         let test_kind = self.test_kind;
1996         let target = self.host;
1997
1998         // Use the previous stage compiler to reuse the artifacts that are
1999         // created when running compiletest for src/test/rustdoc. If this used
2000         // `compiler`, then it would cause rustdoc to be built *again*, which
2001         // isn't really necessary.
2002         let compiler = builder.compiler_for(builder.top_stage, target, target);
2003         builder.ensure(compile::Rustc { compiler, target });
2004
2005         let mut cargo = tool::prepare_tool_cargo(
2006             builder,
2007             compiler,
2008             Mode::ToolRustc,
2009             target,
2010             test_kind.subcommand(),
2011             "src/tools/rustdoc",
2012             SourceType::InTree,
2013             &[],
2014         );
2015         if test_kind.subcommand() == "test" && !builder.fail_fast {
2016             cargo.arg("--no-fail-fast");
2017         }
2018
2019         cargo.arg("-p").arg("rustdoc:0.0.0");
2020
2021         cargo.arg("--");
2022         cargo.args(&builder.config.cmd.test_args());
2023
2024         if self.host.contains("musl") {
2025             cargo.arg("'-Ctarget-feature=-crt-static'");
2026         }
2027
2028         // This is needed for running doctests on librustdoc. This is a bit of
2029         // an unfortunate interaction with how bootstrap works and how cargo
2030         // sets up the dylib path, and the fact that the doctest (in
2031         // html/markdown.rs) links to rustc-private libs. For stage1, the
2032         // compiler host dylibs (in stage1/lib) are not the same as the target
2033         // dylibs (in stage1/lib/rustlib/...). This is different from a normal
2034         // rust distribution where they are the same.
2035         //
2036         // On the cargo side, normal tests use `target_process` which handles
2037         // setting up the dylib for a *target* (stage1/lib/rustlib/... in this
2038         // case). However, for doctests it uses `rustdoc_process` which only
2039         // sets up the dylib path for the *host* (stage1/lib), which is the
2040         // wrong directory.
2041         //
2042         // It should be considered to just stop running doctests on
2043         // librustdoc. There is only one test, and it doesn't look too
2044         // important. There might be other ways to avoid this, but it seems
2045         // pretty convoluted.
2046         //
2047         // See also https://github.com/rust-lang/rust/issues/13983 where the
2048         // host vs target dylibs for rustdoc are consistently tricky to deal
2049         // with.
2050         let mut dylib_path = dylib_path();
2051         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
2052         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
2053
2054         if !builder.config.verbose_tests {
2055             cargo.arg("--quiet");
2056         }
2057
2058         builder.info(&format!(
2059             "{} rustdoc stage{} ({} -> {})",
2060             test_kind, compiler.stage, &compiler.host, target
2061         ));
2062         let _time = util::timeit(&builder);
2063
2064         try_run(builder, &mut cargo.into());
2065     }
2066 }
2067
2068 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2069 pub struct CrateRustdocJsonTypes {
2070     host: TargetSelection,
2071     test_kind: TestKind,
2072 }
2073
2074 impl Step for CrateRustdocJsonTypes {
2075     type Output = ();
2076     const DEFAULT: bool = true;
2077     const ONLY_HOSTS: bool = true;
2078
2079     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2080         run.path("src/rustdoc-json-types")
2081     }
2082
2083     fn make_run(run: RunConfig<'_>) {
2084         let builder = run.builder;
2085
2086         let test_kind = builder.kind.into();
2087
2088         builder.ensure(CrateRustdocJsonTypes { host: run.target, test_kind });
2089     }
2090
2091     fn run(self, builder: &Builder<'_>) {
2092         let test_kind = self.test_kind;
2093         let target = self.host;
2094
2095         // Use the previous stage compiler to reuse the artifacts that are
2096         // created when running compiletest for src/test/rustdoc. If this used
2097         // `compiler`, then it would cause rustdoc to be built *again*, which
2098         // isn't really necessary.
2099         let compiler = builder.compiler_for(builder.top_stage, target, target);
2100         builder.ensure(compile::Rustc { compiler, target });
2101
2102         let mut cargo = tool::prepare_tool_cargo(
2103             builder,
2104             compiler,
2105             Mode::ToolRustc,
2106             target,
2107             test_kind.subcommand(),
2108             "src/rustdoc-json-types",
2109             SourceType::InTree,
2110             &[],
2111         );
2112         if test_kind.subcommand() == "test" && !builder.fail_fast {
2113             cargo.arg("--no-fail-fast");
2114         }
2115
2116         cargo.arg("-p").arg("rustdoc-json-types");
2117
2118         cargo.arg("--");
2119         cargo.args(&builder.config.cmd.test_args());
2120
2121         if self.host.contains("musl") {
2122             cargo.arg("'-Ctarget-feature=-crt-static'");
2123         }
2124
2125         if !builder.config.verbose_tests {
2126             cargo.arg("--quiet");
2127         }
2128
2129         builder.info(&format!(
2130             "{} rustdoc-json-types stage{} ({} -> {})",
2131             test_kind, compiler.stage, &compiler.host, target
2132         ));
2133         let _time = util::timeit(&builder);
2134
2135         try_run(builder, &mut cargo.into());
2136     }
2137 }
2138
2139 /// Some test suites are run inside emulators or on remote devices, and most
2140 /// of our test binaries are linked dynamically which means we need to ship
2141 /// the standard library and such to the emulator ahead of time. This step
2142 /// represents this and is a dependency of all test suites.
2143 ///
2144 /// Most of the time this is a no-op. For some steps such as shipping data to
2145 /// QEMU we have to build our own tools so we've got conditional dependencies
2146 /// on those programs as well. Note that the remote test client is built for
2147 /// the build target (us) and the server is built for the target.
2148 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2149 pub struct RemoteCopyLibs {
2150     compiler: Compiler,
2151     target: TargetSelection,
2152 }
2153
2154 impl Step for RemoteCopyLibs {
2155     type Output = ();
2156
2157     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2158         run.never()
2159     }
2160
2161     fn run(self, builder: &Builder<'_>) {
2162         let compiler = self.compiler;
2163         let target = self.target;
2164         if !builder.remote_tested(target) {
2165             return;
2166         }
2167
2168         builder.ensure(compile::Std { compiler, target });
2169
2170         builder.info(&format!("REMOTE copy libs to emulator ({})", target));
2171         t!(fs::create_dir_all(builder.out.join("tmp")));
2172
2173         let server = builder.ensure(tool::RemoteTestServer { compiler, target });
2174
2175         // Spawn the emulator and wait for it to come online
2176         let tool = builder.tool_exe(Tool::RemoteTestClient);
2177         let mut cmd = Command::new(&tool);
2178         cmd.arg("spawn-emulator").arg(target.triple).arg(&server).arg(builder.out.join("tmp"));
2179         if let Some(rootfs) = builder.qemu_rootfs(target) {
2180             cmd.arg(rootfs);
2181         }
2182         builder.run(&mut cmd);
2183
2184         // Push all our dylibs to the emulator
2185         for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
2186             let f = t!(f);
2187             let name = f.file_name().into_string().unwrap();
2188             if util::is_dylib(&name) {
2189                 builder.run(Command::new(&tool).arg("push").arg(f.path()));
2190             }
2191         }
2192     }
2193 }
2194
2195 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2196 pub struct Distcheck;
2197
2198 impl Step for Distcheck {
2199     type Output = ();
2200
2201     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2202         run.path("distcheck")
2203     }
2204
2205     fn make_run(run: RunConfig<'_>) {
2206         run.builder.ensure(Distcheck);
2207     }
2208
2209     /// Runs "distcheck", a 'make check' from a tarball
2210     fn run(self, builder: &Builder<'_>) {
2211         builder.info("Distcheck");
2212         let dir = builder.out.join("tmp").join("distcheck");
2213         let _ = fs::remove_dir_all(&dir);
2214         t!(fs::create_dir_all(&dir));
2215
2216         // Guarantee that these are built before we begin running.
2217         builder.ensure(dist::PlainSourceTarball);
2218         builder.ensure(dist::Src);
2219
2220         let mut cmd = Command::new("tar");
2221         cmd.arg("-xf")
2222             .arg(builder.ensure(dist::PlainSourceTarball).tarball())
2223             .arg("--strip-components=1")
2224             .current_dir(&dir);
2225         builder.run(&mut cmd);
2226         builder.run(
2227             Command::new("./configure")
2228                 .args(&builder.config.configure_args)
2229                 .arg("--enable-vendor")
2230                 .current_dir(&dir),
2231         );
2232         builder.run(
2233             Command::new(build_helper::make(&builder.config.build.triple))
2234                 .arg("check")
2235                 .current_dir(&dir),
2236         );
2237
2238         // Now make sure that rust-src has all of libstd's dependencies
2239         builder.info("Distcheck rust-src");
2240         let dir = builder.out.join("tmp").join("distcheck-src");
2241         let _ = fs::remove_dir_all(&dir);
2242         t!(fs::create_dir_all(&dir));
2243
2244         let mut cmd = Command::new("tar");
2245         cmd.arg("-xf")
2246             .arg(builder.ensure(dist::Src).tarball())
2247             .arg("--strip-components=1")
2248             .current_dir(&dir);
2249         builder.run(&mut cmd);
2250
2251         let toml = dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml");
2252         builder.run(
2253             Command::new(&builder.initial_cargo)
2254                 .arg("generate-lockfile")
2255                 .arg("--manifest-path")
2256                 .arg(&toml)
2257                 .current_dir(&dir),
2258         );
2259     }
2260 }
2261
2262 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2263 pub struct Bootstrap;
2264
2265 impl Step for Bootstrap {
2266     type Output = ();
2267     const DEFAULT: bool = true;
2268     const ONLY_HOSTS: bool = true;
2269
2270     /// Tests the build system itself.
2271     fn run(self, builder: &Builder<'_>) {
2272         let mut cmd = Command::new(&builder.initial_cargo);
2273         cmd.arg("test")
2274             .current_dir(builder.src.join("src/bootstrap"))
2275             .env("RUSTFLAGS", "-Cdebuginfo=2")
2276             .env("CARGO_TARGET_DIR", builder.out.join("bootstrap"))
2277             .env("BOOTSTRAP_OUTPUT_DIRECTORY", &builder.config.out)
2278             .env("BOOTSTRAP_INITIAL_CARGO", &builder.config.initial_cargo)
2279             .env("RUSTC_BOOTSTRAP", "1")
2280             .env("RUSTC", &builder.initial_rustc);
2281         if let Some(flags) = option_env!("RUSTFLAGS") {
2282             // Use the same rustc flags for testing as for "normal" compilation,
2283             // so that Cargo doesn’t recompile the entire dependency graph every time:
2284             // https://github.com/rust-lang/rust/issues/49215
2285             cmd.env("RUSTFLAGS", flags);
2286         }
2287         if !builder.fail_fast {
2288             cmd.arg("--no-fail-fast");
2289         }
2290         cmd.arg("--").args(&builder.config.cmd.test_args());
2291         // rustbuild tests are racy on directory creation so just run them one at a time.
2292         // Since there's not many this shouldn't be a problem.
2293         cmd.arg("--test-threads=1");
2294         try_run(builder, &mut cmd);
2295     }
2296
2297     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2298         run.path("src/bootstrap")
2299     }
2300
2301     fn make_run(run: RunConfig<'_>) {
2302         run.builder.ensure(Bootstrap);
2303     }
2304 }
2305
2306 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2307 pub struct TierCheck {
2308     pub compiler: Compiler,
2309 }
2310
2311 impl Step for TierCheck {
2312     type Output = ();
2313     const DEFAULT: bool = true;
2314     const ONLY_HOSTS: bool = true;
2315
2316     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2317         run.path("src/tools/tier-check")
2318     }
2319
2320     fn make_run(run: RunConfig<'_>) {
2321         let compiler =
2322             run.builder.compiler_for(run.builder.top_stage, run.builder.build.build, run.target);
2323         run.builder.ensure(TierCheck { compiler });
2324     }
2325
2326     /// Tests the Platform Support page in the rustc book.
2327     fn run(self, builder: &Builder<'_>) {
2328         builder.ensure(compile::Std { compiler: self.compiler, target: self.compiler.host });
2329         let mut cargo = tool::prepare_tool_cargo(
2330             builder,
2331             self.compiler,
2332             Mode::ToolStd,
2333             self.compiler.host,
2334             "run",
2335             "src/tools/tier-check",
2336             SourceType::InTree,
2337             &[],
2338         );
2339         cargo.arg(builder.src.join("src/doc/rustc/src/platform-support.md"));
2340         cargo.arg(&builder.rustc(self.compiler));
2341         if builder.is_verbose() {
2342             cargo.arg("--verbose");
2343         }
2344
2345         builder.info("platform support check");
2346         try_run(builder, &mut cargo.into());
2347     }
2348 }
2349
2350 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2351 pub struct LintDocs {
2352     pub compiler: Compiler,
2353     pub target: TargetSelection,
2354 }
2355
2356 impl Step for LintDocs {
2357     type Output = ();
2358     const DEFAULT: bool = true;
2359     const ONLY_HOSTS: bool = true;
2360
2361     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
2362         run.path("src/tools/lint-docs")
2363     }
2364
2365     fn make_run(run: RunConfig<'_>) {
2366         run.builder.ensure(LintDocs {
2367             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
2368             target: run.target,
2369         });
2370     }
2371
2372     /// Tests that the lint examples in the rustc book generate the correct
2373     /// lints and have the expected format.
2374     fn run(self, builder: &Builder<'_>) {
2375         builder.ensure(crate::doc::RustcBook {
2376             compiler: self.compiler,
2377             target: self.target,
2378             validate: true,
2379         });
2380     }
2381 }