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