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