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