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