]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/check.rs
Rollup merge of #99803 - JohnTitor:update-lazy-docs, r=compiler-errors
[rust.git] / src / bootstrap / check.rs
1 //! Implementation of compiling the compiler and standard library, in "check"-based modes.
2
3 use crate::builder::{Builder, Kind, RunConfig, ShouldRun, Step};
4 use crate::cache::Interned;
5 use crate::compile::{add_to_sysroot, run_cargo, rustc_cargo, rustc_cargo_env, std_cargo};
6 use crate::config::TargetSelection;
7 use crate::tool::{prepare_tool_cargo, SourceType};
8 use crate::INTERNER;
9 use crate::{Compiler, Mode, Subcommand};
10 use std::path::{Path, PathBuf};
11
12 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
13 pub struct Std {
14     pub target: TargetSelection,
15 }
16
17 /// Returns args for the subcommand itself (not for cargo)
18 fn args(builder: &Builder<'_>) -> Vec<String> {
19     fn strings<'a>(arr: &'a [&str]) -> impl Iterator<Item = String> + 'a {
20         arr.iter().copied().map(String::from)
21     }
22
23     if let Subcommand::Clippy {
24         fix,
25         clippy_lint_allow,
26         clippy_lint_deny,
27         clippy_lint_warn,
28         clippy_lint_forbid,
29         ..
30     } = &builder.config.cmd
31     {
32         // disable the most spammy clippy lints
33         let ignored_lints = vec![
34             "many_single_char_names", // there are a lot in stdarch
35             "collapsible_if",
36             "type_complexity",
37             "missing_safety_doc", // almost 3K warnings
38             "too_many_arguments",
39             "needless_lifetimes", // people want to keep the lifetimes
40             "wrong_self_convention",
41         ];
42         let mut args = vec![];
43         if *fix {
44             #[rustfmt::skip]
45             args.extend(strings(&[
46                 "--fix", "-Zunstable-options",
47                 // FIXME: currently, `--fix` gives an error while checking tests for libtest,
48                 // possibly because libtest is not yet built in the sysroot.
49                 // As a workaround, avoid checking tests and benches when passed --fix.
50                 "--lib", "--bins", "--examples",
51             ]));
52         }
53         args.extend(strings(&["--", "--cap-lints", "warn"]));
54         args.extend(ignored_lints.iter().map(|lint| format!("-Aclippy::{}", lint)));
55         let mut clippy_lint_levels: Vec<String> = Vec::new();
56         clippy_lint_allow.iter().for_each(|v| clippy_lint_levels.push(format!("-A{}", v)));
57         clippy_lint_deny.iter().for_each(|v| clippy_lint_levels.push(format!("-D{}", v)));
58         clippy_lint_warn.iter().for_each(|v| clippy_lint_levels.push(format!("-W{}", v)));
59         clippy_lint_forbid.iter().for_each(|v| clippy_lint_levels.push(format!("-F{}", v)));
60         args.extend(clippy_lint_levels);
61         args
62     } else {
63         vec![]
64     }
65 }
66
67 fn cargo_subcommand(kind: Kind) -> &'static str {
68     match kind {
69         Kind::Check => "check",
70         Kind::Clippy => "clippy",
71         Kind::Fix => "fix",
72         _ => unreachable!(),
73     }
74 }
75
76 impl Step for Std {
77     type Output = ();
78     const DEFAULT: bool = true;
79
80     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
81         run.all_krates("test").path("library")
82     }
83
84     fn make_run(run: RunConfig<'_>) {
85         run.builder.ensure(Std { target: run.target });
86     }
87
88     fn run(self, builder: &Builder<'_>) {
89         builder.update_submodule(&Path::new("library").join("stdarch"));
90
91         let target = self.target;
92         let compiler = builder.compiler(builder.top_stage, builder.config.build);
93
94         let mut cargo = builder.cargo(
95             compiler,
96             Mode::Std,
97             SourceType::InTree,
98             target,
99             cargo_subcommand(builder.kind),
100         );
101         std_cargo(builder, target, compiler.stage, &mut cargo);
102
103         builder.info(&format!(
104             "Checking stage{} std artifacts ({} -> {})",
105             builder.top_stage, &compiler.host, target
106         ));
107         run_cargo(
108             builder,
109             cargo,
110             args(builder),
111             &libstd_stamp(builder, compiler, target),
112             vec![],
113             true,
114         );
115
116         // We skip populating the sysroot in non-zero stage because that'll lead
117         // to rlib/rmeta conflicts if std gets built during this session.
118         if compiler.stage == 0 {
119             let libdir = builder.sysroot_libdir(compiler, target);
120             let hostdir = builder.sysroot_libdir(compiler, compiler.host);
121             add_to_sysroot(&builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
122         }
123
124         // don't run on std twice with x.py clippy
125         if builder.kind == Kind::Clippy {
126             return;
127         }
128
129         // Then run cargo again, once we've put the rmeta files for the library
130         // crates into the sysroot. This is needed because e.g., core's tests
131         // depend on `libtest` -- Cargo presumes it will exist, but it doesn't
132         // since we initialize with an empty sysroot.
133         //
134         // Currently only the "libtest" tree of crates does this.
135         let mut cargo = builder.cargo(
136             compiler,
137             Mode::Std,
138             SourceType::InTree,
139             target,
140             cargo_subcommand(builder.kind),
141         );
142
143         cargo.arg("--all-targets");
144         std_cargo(builder, target, compiler.stage, &mut cargo);
145
146         // Explicitly pass -p for all dependencies krates -- this will force cargo
147         // to also check the tests/benches/examples for these crates, rather
148         // than just the leaf crate.
149         for krate in builder.in_tree_crates("test", Some(target)) {
150             cargo.arg("-p").arg(krate.name);
151         }
152
153         builder.info(&format!(
154             "Checking stage{} std test/bench/example targets ({} -> {})",
155             builder.top_stage, &compiler.host, target
156         ));
157         run_cargo(
158             builder,
159             cargo,
160             args(builder),
161             &libstd_test_stamp(builder, compiler, target),
162             vec![],
163             true,
164         );
165     }
166 }
167
168 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
169 pub struct Rustc {
170     pub target: TargetSelection,
171 }
172
173 impl Step for Rustc {
174     type Output = ();
175     const ONLY_HOSTS: bool = true;
176     const DEFAULT: bool = true;
177
178     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
179         run.all_krates("rustc-main").path("compiler")
180     }
181
182     fn make_run(run: RunConfig<'_>) {
183         run.builder.ensure(Rustc { target: run.target });
184     }
185
186     /// Builds the compiler.
187     ///
188     /// This will build the compiler for a particular stage of the build using
189     /// the `compiler` targeting the `target` architecture. The artifacts
190     /// created will also be linked into the sysroot directory.
191     fn run(self, builder: &Builder<'_>) {
192         let compiler = builder.compiler(builder.top_stage, builder.config.build);
193         let target = self.target;
194
195         if compiler.stage != 0 {
196             // If we're not in stage 0, then we won't have a std from the beta
197             // compiler around. That means we need to make sure there's one in
198             // the sysroot for the compiler to find. Otherwise, we're going to
199             // fail when building crates that need to generate code (e.g., build
200             // scripts and their dependencies).
201             builder.ensure(crate::compile::Std::new(compiler, compiler.host));
202             builder.ensure(crate::compile::Std::new(compiler, target));
203         } else {
204             builder.ensure(Std { target });
205         }
206
207         let mut cargo = builder.cargo(
208             compiler,
209             Mode::Rustc,
210             SourceType::InTree,
211             target,
212             cargo_subcommand(builder.kind),
213         );
214         rustc_cargo(builder, &mut cargo, target);
215
216         // For ./x.py clippy, don't run with --all-targets because
217         // linting tests and benchmarks can produce very noisy results
218         if builder.kind != Kind::Clippy {
219             cargo.arg("--all-targets");
220         }
221
222         // Explicitly pass -p for all compiler krates -- this will force cargo
223         // to also check the tests/benches/examples for these crates, rather
224         // than just the leaf crate.
225         for krate in builder.in_tree_crates("rustc-main", Some(target)) {
226             cargo.arg("-p").arg(krate.name);
227         }
228
229         builder.info(&format!(
230             "Checking stage{} compiler artifacts ({} -> {})",
231             builder.top_stage, &compiler.host, target
232         ));
233         run_cargo(
234             builder,
235             cargo,
236             args(builder),
237             &librustc_stamp(builder, compiler, target),
238             vec![],
239             true,
240         );
241
242         let libdir = builder.sysroot_libdir(compiler, target);
243         let hostdir = builder.sysroot_libdir(compiler, compiler.host);
244         add_to_sysroot(&builder, &libdir, &hostdir, &librustc_stamp(builder, compiler, target));
245     }
246 }
247
248 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
249 pub struct CodegenBackend {
250     pub target: TargetSelection,
251     pub backend: Interned<String>,
252 }
253
254 impl Step for CodegenBackend {
255     type Output = ();
256     const ONLY_HOSTS: bool = true;
257     const DEFAULT: bool = true;
258
259     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
260         run.paths(&["compiler/rustc_codegen_cranelift", "compiler/rustc_codegen_gcc"])
261     }
262
263     fn make_run(run: RunConfig<'_>) {
264         for &backend in &[INTERNER.intern_str("cranelift"), INTERNER.intern_str("gcc")] {
265             run.builder.ensure(CodegenBackend { target: run.target, backend });
266         }
267     }
268
269     fn run(self, builder: &Builder<'_>) {
270         let compiler = builder.compiler(builder.top_stage, builder.config.build);
271         let target = self.target;
272         let backend = self.backend;
273
274         builder.ensure(Rustc { target });
275
276         let mut cargo = builder.cargo(
277             compiler,
278             Mode::Codegen,
279             SourceType::InTree,
280             target,
281             cargo_subcommand(builder.kind),
282         );
283         cargo
284             .arg("--manifest-path")
285             .arg(builder.src.join(format!("compiler/rustc_codegen_{}/Cargo.toml", backend)));
286         rustc_cargo_env(builder, &mut cargo, target);
287
288         builder.info(&format!(
289             "Checking stage{} {} artifacts ({} -> {})",
290             builder.top_stage, backend, &compiler.host.triple, target.triple
291         ));
292
293         run_cargo(
294             builder,
295             cargo,
296             args(builder),
297             &codegen_backend_stamp(builder, compiler, target, backend),
298             vec![],
299             true,
300         );
301     }
302 }
303
304 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
305 pub struct RustAnalyzer {
306     pub target: TargetSelection,
307 }
308
309 impl Step for RustAnalyzer {
310     type Output = ();
311     const ONLY_HOSTS: bool = true;
312     const DEFAULT: bool = true;
313
314     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
315         run.path("src/tools/rust-analyzer")
316     }
317
318     fn make_run(run: RunConfig<'_>) {
319         run.builder.ensure(RustAnalyzer { target: run.target });
320     }
321
322     fn run(self, builder: &Builder<'_>) {
323         let compiler = builder.compiler(builder.top_stage, builder.config.build);
324         let target = self.target;
325
326         builder.ensure(Std { target });
327
328         let mut cargo = prepare_tool_cargo(
329             builder,
330             compiler,
331             Mode::ToolStd,
332             target,
333             cargo_subcommand(builder.kind),
334             "src/tools/rust-analyzer",
335             SourceType::InTree,
336             &["rust-analyzer/in-rust-tree".to_owned()],
337         );
338
339         cargo.rustflag(
340             "-Zallow-features=proc_macro_internals,proc_macro_diagnostic,proc_macro_span",
341         );
342
343         // For ./x.py clippy, don't check those targets because
344         // linting tests and benchmarks can produce very noisy results
345         if builder.kind != Kind::Clippy {
346             // can't use `--all-targets` because `--examples` doesn't work well
347             cargo.arg("--bins");
348             cargo.arg("--tests");
349             cargo.arg("--benches");
350         }
351
352         builder.info(&format!(
353             "Checking stage{} {} artifacts ({} -> {})",
354             compiler.stage, "rust-analyzer", &compiler.host.triple, target.triple
355         ));
356         run_cargo(builder, cargo, args(builder), &stamp(builder, compiler, target), vec![], true);
357
358         /// Cargo's output path in a given stage, compiled by a particular
359         /// compiler for the specified target.
360         fn stamp(builder: &Builder<'_>, compiler: Compiler, target: TargetSelection) -> PathBuf {
361             builder.cargo_out(compiler, Mode::ToolStd, target).join(".rust-analyzer-check.stamp")
362         }
363     }
364 }
365
366 macro_rules! tool_check_step {
367     ($name:ident, $path:literal, $($alias:literal, )* $source_type:path $(, $default:literal )?) => {
368         #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
369         pub struct $name {
370             pub target: TargetSelection,
371         }
372
373         impl Step for $name {
374             type Output = ();
375             const ONLY_HOSTS: bool = true;
376             // don't ever check out-of-tree tools by default, they'll fail when toolstate is broken
377             const DEFAULT: bool = matches!($source_type, SourceType::InTree) $( && $default )?;
378
379             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
380                 run.paths(&[ $path, $($alias),* ])
381             }
382
383             fn make_run(run: RunConfig<'_>) {
384                 run.builder.ensure($name { target: run.target });
385             }
386
387             fn run(self, builder: &Builder<'_>) {
388                 let compiler = builder.compiler(builder.top_stage, builder.config.build);
389                 let target = self.target;
390
391                 builder.ensure(Rustc { target });
392
393                 let mut cargo = prepare_tool_cargo(
394                     builder,
395                     compiler,
396                     Mode::ToolRustc,
397                     target,
398                     cargo_subcommand(builder.kind),
399                     $path,
400                     $source_type,
401                     &[],
402                 );
403
404                 // For ./x.py clippy, don't run with --all-targets because
405                 // linting tests and benchmarks can produce very noisy results
406                 if builder.kind != Kind::Clippy {
407                     cargo.arg("--all-targets");
408                 }
409
410                 // Enable internal lints for clippy and rustdoc
411                 // NOTE: this doesn't enable lints for any other tools unless they explicitly add `#![warn(rustc::internal)]`
412                 // See https://github.com/rust-lang/rust/pull/80573#issuecomment-754010776
413                 cargo.rustflag("-Zunstable-options");
414
415                 builder.info(&format!(
416                     "Checking stage{} {} artifacts ({} -> {})",
417                     builder.top_stage,
418                     stringify!($name).to_lowercase(),
419                     &compiler.host.triple,
420                     target.triple
421                 ));
422                 run_cargo(
423                     builder,
424                     cargo,
425                     args(builder),
426                     &stamp(builder, compiler, target),
427                     vec![],
428                     true,
429                 );
430
431                 /// Cargo's output path in a given stage, compiled by a particular
432                 /// compiler for the specified target.
433                 fn stamp(
434                     builder: &Builder<'_>,
435                     compiler: Compiler,
436                     target: TargetSelection,
437                 ) -> PathBuf {
438                     builder
439                         .cargo_out(compiler, Mode::ToolRustc, target)
440                         .join(format!(".{}-check.stamp", stringify!($name).to_lowercase()))
441                 }
442             }
443         }
444     };
445 }
446
447 tool_check_step!(Rustdoc, "src/tools/rustdoc", "src/librustdoc", SourceType::InTree);
448 // Clippy and Rustfmt are hybrids. They are external tools, but use a git subtree instead
449 // of a submodule. Since the SourceType only drives the deny-warnings
450 // behavior, treat it as in-tree so that any new warnings in clippy will be
451 // rejected.
452 tool_check_step!(Clippy, "src/tools/clippy", SourceType::InTree);
453 tool_check_step!(Miri, "src/tools/miri", SourceType::Submodule);
454 tool_check_step!(Rls, "src/tools/rls", SourceType::Submodule);
455 tool_check_step!(Rustfmt, "src/tools/rustfmt", SourceType::InTree);
456
457 tool_check_step!(Bootstrap, "src/bootstrap", SourceType::InTree, false);
458
459 /// Cargo's output path for the standard library in a given stage, compiled
460 /// by a particular compiler for the specified target.
461 fn libstd_stamp(builder: &Builder<'_>, compiler: Compiler, target: TargetSelection) -> PathBuf {
462     builder.cargo_out(compiler, Mode::Std, target).join(".libstd-check.stamp")
463 }
464
465 /// Cargo's output path for the standard library in a given stage, compiled
466 /// by a particular compiler for the specified target.
467 fn libstd_test_stamp(
468     builder: &Builder<'_>,
469     compiler: Compiler,
470     target: TargetSelection,
471 ) -> PathBuf {
472     builder.cargo_out(compiler, Mode::Std, target).join(".libstd-check-test.stamp")
473 }
474
475 /// Cargo's output path for librustc in a given stage, compiled by a particular
476 /// compiler for the specified target.
477 fn librustc_stamp(builder: &Builder<'_>, compiler: Compiler, target: TargetSelection) -> PathBuf {
478     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc-check.stamp")
479 }
480
481 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
482 /// compiler for the specified target and backend.
483 fn codegen_backend_stamp(
484     builder: &Builder<'_>,
485     compiler: Compiler,
486     target: TargetSelection,
487     backend: Interned<String>,
488 ) -> PathBuf {
489     builder
490         .cargo_out(compiler, Mode::Codegen, target)
491         .join(format!(".librustc_codegen_{}-check.stamp", backend))
492 }