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