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