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