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