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