bootstrap/core/build_steps/
clippy.rs

1//! Implementation of running clippy on the compiler, standard library and various tools.
2//!
3//! This serves a double purpose:
4//! - The first is to run Clippy itself on in-tree code, in order to test and dogfood it.
5//! - The second is to actually lint the in-tree codebase on CI, with a hard-coded set of rules,
6//!   which is performed by the `x clippy ci` command.
7//!
8//! In order to prepare a build compiler for running clippy, use the
9//! [prepare_compiler_for_check] function. That prepares a
10//! compiler and a standard library
11//! for running Clippy. The second part (actually building Clippy) is performed inside
12//! [Builder::cargo_clippy_cmd]. It would be nice if this was more explicit, and we actually had
13//! to pass a prebuilt Clippy from the outside when running `cargo clippy`, but that would be
14//! (as usual) a massive undertaking/refactoring.
15
16use build_helper::exit;
17
18use super::compile::{run_cargo, rustc_cargo, std_cargo};
19use super::tool::{SourceType, prepare_tool_cargo};
20use crate::builder::{Builder, ShouldRun};
21use crate::core::build_steps::check::{CompilerForCheck, prepare_compiler_for_check};
22use crate::core::build_steps::compile::std_crates_for_run_make;
23use crate::core::builder;
24use crate::core::builder::{Alias, Kind, RunConfig, Step, StepMetadata, crate_description};
25use crate::utils::build_stamp::{self, BuildStamp};
26use crate::{Compiler, Mode, Subcommand, TargetSelection};
27
28/// Disable the most spammy clippy lints
29const IGNORED_RULES_FOR_STD_AND_RUSTC: &[&str] = &[
30    "many_single_char_names", // there are a lot in stdarch
31    "collapsible_if",
32    "type_complexity",
33    "missing_safety_doc", // almost 3K warnings
34    "too_many_arguments",
35    "needless_lifetimes", // people want to keep the lifetimes
36    "wrong_self_convention",
37    "approx_constant", // libcore is what defines those
38];
39
40fn lint_args(builder: &Builder<'_>, config: &LintConfig, ignored_rules: &[&str]) -> Vec<String> {
41    fn strings<'a>(arr: &'a [&str]) -> impl Iterator<Item = String> + 'a {
42        arr.iter().copied().map(String::from)
43    }
44
45    let Subcommand::Clippy { fix, allow_dirty, allow_staged, .. } = &builder.config.cmd else {
46        unreachable!("clippy::lint_args can only be called from `clippy` subcommands.");
47    };
48
49    let mut args = vec![];
50    if *fix {
51        #[rustfmt::skip]
52            args.extend(strings(&[
53                "--fix", "-Zunstable-options",
54                // FIXME: currently, `--fix` gives an error while checking tests for libtest,
55                // possibly because libtest is not yet built in the sysroot.
56                // As a workaround, avoid checking tests and benches when passed --fix.
57                "--lib", "--bins", "--examples",
58            ]));
59
60        if *allow_dirty {
61            args.push("--allow-dirty".to_owned());
62        }
63
64        if *allow_staged {
65            args.push("--allow-staged".to_owned());
66        }
67    }
68
69    args.extend(strings(&["--"]));
70
71    if config.deny.is_empty() && config.forbid.is_empty() {
72        args.extend(strings(&["--cap-lints", "warn"]));
73    }
74
75    let all_args = std::env::args().collect::<Vec<_>>();
76    args.extend(get_clippy_rules_in_order(&all_args, config));
77
78    args.extend(ignored_rules.iter().map(|lint| format!("-Aclippy::{lint}")));
79    args.extend(builder.config.free_args.clone());
80    args
81}
82
83/// We need to keep the order of the given clippy lint rules before passing them.
84/// Since clap doesn't offer any useful interface for this purpose out of the box,
85/// we have to handle it manually.
86pub fn get_clippy_rules_in_order(all_args: &[String], config: &LintConfig) -> Vec<String> {
87    let mut result = vec![];
88
89    for (prefix, item) in
90        [("-A", &config.allow), ("-D", &config.deny), ("-W", &config.warn), ("-F", &config.forbid)]
91    {
92        item.iter().for_each(|v| {
93            let rule = format!("{prefix}{v}");
94            // Arguments added by bootstrap in LintConfig won't show up in the all_args list, so
95            // put them at the end of the command line.
96            let position = all_args.iter().position(|t| t == &rule || t == v).unwrap_or(usize::MAX);
97            result.push((position, rule));
98        });
99    }
100
101    result.sort_by_key(|&(position, _)| position);
102    result.into_iter().map(|v| v.1).collect()
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Hash)]
106pub struct LintConfig {
107    pub allow: Vec<String>,
108    pub warn: Vec<String>,
109    pub deny: Vec<String>,
110    pub forbid: Vec<String>,
111}
112
113impl LintConfig {
114    fn new(builder: &Builder<'_>) -> Self {
115        match builder.config.cmd.clone() {
116            Subcommand::Clippy { allow, deny, warn, forbid, .. } => {
117                Self { allow, warn, deny, forbid }
118            }
119            _ => unreachable!("LintConfig can only be called from `clippy` subcommands."),
120        }
121    }
122
123    fn merge(&self, other: &Self) -> Self {
124        let merged = |self_attr: &[String], other_attr: &[String]| -> Vec<String> {
125            self_attr.iter().cloned().chain(other_attr.iter().cloned()).collect()
126        };
127        // This is written this way to ensure we get a compiler error if we add a new field.
128        Self {
129            allow: merged(&self.allow, &other.allow),
130            warn: merged(&self.warn, &other.warn),
131            deny: merged(&self.deny, &other.deny),
132            forbid: merged(&self.forbid, &other.forbid),
133        }
134    }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Hash)]
138pub struct Std {
139    build_compiler: Compiler,
140    target: TargetSelection,
141    config: LintConfig,
142    /// Whether to lint only a subset of crates.
143    crates: Vec<String>,
144}
145
146impl Std {
147    fn new(
148        builder: &Builder<'_>,
149        target: TargetSelection,
150        config: LintConfig,
151        crates: Vec<String>,
152    ) -> Self {
153        Self {
154            build_compiler: builder.compiler(builder.top_stage, builder.host_target),
155            target,
156            config,
157            crates,
158        }
159    }
160
161    fn from_build_compiler(
162        build_compiler: Compiler,
163        target: TargetSelection,
164        config: LintConfig,
165        crates: Vec<String>,
166    ) -> Self {
167        Self { build_compiler, target, config, crates }
168    }
169}
170
171impl Step for Std {
172    type Output = ();
173    const DEFAULT: bool = true;
174
175    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
176        run.crate_or_deps("sysroot").path("library")
177    }
178
179    fn make_run(run: RunConfig<'_>) {
180        let crates = std_crates_for_run_make(&run);
181        let config = LintConfig::new(run.builder);
182        run.builder.ensure(Std::new(run.builder, run.target, config, crates));
183    }
184
185    fn run(self, builder: &Builder<'_>) {
186        let target = self.target;
187        let build_compiler = self.build_compiler;
188
189        let mut cargo = builder::Cargo::new(
190            builder,
191            build_compiler,
192            Mode::Std,
193            SourceType::InTree,
194            target,
195            Kind::Clippy,
196        );
197
198        std_cargo(builder, target, &mut cargo);
199
200        for krate in &*self.crates {
201            cargo.arg("-p").arg(krate);
202        }
203
204        let _guard = builder.msg(
205            Kind::Clippy,
206            format_args!("library{}", crate_description(&self.crates)),
207            Mode::Std,
208            build_compiler,
209            target,
210        );
211
212        run_cargo(
213            builder,
214            cargo,
215            lint_args(builder, &self.config, IGNORED_RULES_FOR_STD_AND_RUSTC),
216            &build_stamp::libstd_stamp(builder, build_compiler, target),
217            vec![],
218            true,
219            false,
220        );
221    }
222
223    fn metadata(&self) -> Option<StepMetadata> {
224        Some(StepMetadata::clippy("std", self.target).built_by(self.build_compiler))
225    }
226}
227
228/// Lints the compiler.
229///
230/// This will build Clippy with the `build_compiler` and use it to lint
231/// in-tree rustc.
232#[derive(Debug, Clone, PartialEq, Eq, Hash)]
233pub struct Rustc {
234    build_compiler: CompilerForCheck,
235    target: TargetSelection,
236    config: LintConfig,
237    /// Whether to lint only a subset of crates.
238    crates: Vec<String>,
239}
240
241impl Rustc {
242    fn new(
243        builder: &Builder<'_>,
244        target: TargetSelection,
245        config: LintConfig,
246        crates: Vec<String>,
247    ) -> Self {
248        Self {
249            build_compiler: prepare_compiler_for_check(builder, target, Mode::Rustc),
250            target,
251            config,
252            crates,
253        }
254    }
255}
256
257impl Step for Rustc {
258    type Output = ();
259    const IS_HOST: bool = true;
260    const DEFAULT: bool = true;
261
262    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
263        run.crate_or_deps("rustc-main").path("compiler")
264    }
265
266    fn make_run(run: RunConfig<'_>) {
267        let builder = run.builder;
268        let crates = run.make_run_crates(Alias::Compiler);
269        let config = LintConfig::new(run.builder);
270        run.builder.ensure(Rustc::new(builder, run.target, config, crates));
271    }
272
273    fn run(self, builder: &Builder<'_>) {
274        let build_compiler = self.build_compiler.build_compiler();
275        let target = self.target;
276
277        let mut cargo = builder::Cargo::new(
278            builder,
279            build_compiler,
280            Mode::Rustc,
281            SourceType::InTree,
282            target,
283            Kind::Clippy,
284        );
285
286        rustc_cargo(builder, &mut cargo, target, &build_compiler, &self.crates);
287        self.build_compiler.configure_cargo(&mut cargo);
288
289        // Explicitly pass -p for all compiler crates -- this will force cargo
290        // to also lint the tests/benches/examples for these crates, rather
291        // than just the leaf crate.
292        for krate in &*self.crates {
293            cargo.arg("-p").arg(krate);
294        }
295
296        let _guard = builder.msg(
297            Kind::Clippy,
298            format_args!("compiler{}", crate_description(&self.crates)),
299            Mode::Rustc,
300            build_compiler,
301            target,
302        );
303
304        run_cargo(
305            builder,
306            cargo,
307            lint_args(builder, &self.config, IGNORED_RULES_FOR_STD_AND_RUSTC),
308            &build_stamp::librustc_stamp(builder, build_compiler, target),
309            vec![],
310            true,
311            false,
312        );
313    }
314
315    fn metadata(&self) -> Option<StepMetadata> {
316        Some(
317            StepMetadata::clippy("rustc", self.target)
318                .built_by(self.build_compiler.build_compiler()),
319        )
320    }
321}
322
323#[derive(Debug, Clone, Hash, PartialEq, Eq)]
324pub struct CodegenGcc {
325    build_compiler: CompilerForCheck,
326    target: TargetSelection,
327    config: LintConfig,
328}
329
330impl CodegenGcc {
331    fn new(builder: &Builder<'_>, target: TargetSelection, config: LintConfig) -> Self {
332        Self {
333            build_compiler: prepare_compiler_for_check(builder, target, Mode::Codegen),
334            target,
335            config,
336        }
337    }
338}
339
340impl Step for CodegenGcc {
341    type Output = ();
342
343    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
344        run.alias("rustc_codegen_gcc")
345    }
346
347    fn make_run(run: RunConfig<'_>) {
348        let builder = run.builder;
349        let config = LintConfig::new(builder);
350        builder.ensure(CodegenGcc::new(builder, run.target, config));
351    }
352
353    fn run(self, builder: &Builder<'_>) -> Self::Output {
354        let build_compiler = self.build_compiler.build_compiler();
355        let target = self.target;
356
357        let mut cargo = prepare_tool_cargo(
358            builder,
359            build_compiler,
360            Mode::Codegen,
361            target,
362            Kind::Clippy,
363            "compiler/rustc_codegen_gcc",
364            SourceType::InTree,
365            &[],
366        );
367        self.build_compiler.configure_cargo(&mut cargo);
368
369        let _guard =
370            builder.msg(Kind::Clippy, "rustc_codegen_gcc", Mode::ToolRustc, build_compiler, target);
371
372        let stamp = BuildStamp::new(&builder.cargo_out(build_compiler, Mode::Codegen, target))
373            .with_prefix("rustc_codegen_gcc-check");
374
375        run_cargo(
376            builder,
377            cargo,
378            lint_args(builder, &self.config, &[]),
379            &stamp,
380            vec![],
381            true,
382            false,
383        );
384    }
385
386    fn metadata(&self) -> Option<StepMetadata> {
387        Some(
388            StepMetadata::clippy("rustc_codegen_gcc", self.target)
389                .built_by(self.build_compiler.build_compiler()),
390        )
391    }
392}
393
394macro_rules! lint_any {
395    ($(
396        $name:ident,
397        $path:expr,
398        $readable_name:expr,
399        $mode:expr
400        $(,lint_by_default = $lint_by_default:expr)*
401        ;
402    )+) => {
403        $(
404
405        #[derive(Debug, Clone, Hash, PartialEq, Eq)]
406        pub struct $name {
407            build_compiler: CompilerForCheck,
408            target: TargetSelection,
409            config: LintConfig,
410        }
411
412        impl Step for $name {
413            type Output = ();
414            const DEFAULT: bool = if false $(|| $lint_by_default)* { true } else { false };
415
416            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
417                run.path($path)
418            }
419
420            fn make_run(run: RunConfig<'_>) {
421                let config = LintConfig::new(run.builder);
422                run.builder.ensure($name {
423                    build_compiler: prepare_compiler_for_check(run.builder, run.target, $mode),
424                    target: run.target,
425                    config,
426                });
427            }
428
429            fn run(self, builder: &Builder<'_>) -> Self::Output {
430                let build_compiler = self.build_compiler.build_compiler();
431                let target = self.target;
432                let mut cargo = prepare_tool_cargo(
433                    builder,
434                    build_compiler,
435                    $mode,
436                    target,
437                    Kind::Clippy,
438                    $path,
439                    SourceType::InTree,
440                    &[],
441                );
442                self.build_compiler.configure_cargo(&mut cargo);
443
444                let _guard = builder.msg(
445                    Kind::Clippy,
446                    $readable_name,
447                    $mode,
448                    build_compiler,
449                    target,
450                );
451
452                let stringified_name = stringify!($name).to_lowercase();
453                let stamp = BuildStamp::new(&builder.cargo_out(build_compiler, $mode, target))
454                    .with_prefix(&format!("{}-check", stringified_name));
455
456                run_cargo(
457                    builder,
458                    cargo,
459                    lint_args(builder, &self.config, &[]),
460                    &stamp,
461                    vec![],
462                    true,
463                    false,
464                );
465            }
466
467            fn metadata(&self) -> Option<StepMetadata> {
468                Some(StepMetadata::clippy($readable_name, self.target).built_by(self.build_compiler.build_compiler()))
469            }
470        }
471        )+
472    }
473}
474
475// Note: we use ToolTarget instead of ToolBootstrap here, to allow linting in-tree host tools
476// using the in-tree Clippy. Because Mode::ToolBootstrap would always use stage 0 rustc/Clippy.
477lint_any!(
478    Bootstrap, "src/bootstrap", "bootstrap", Mode::ToolTarget;
479    BuildHelper, "src/build_helper", "build_helper", Mode::ToolTarget;
480    BuildManifest, "src/tools/build-manifest", "build-manifest", Mode::ToolTarget;
481    CargoMiri, "src/tools/miri/cargo-miri", "cargo-miri", Mode::ToolRustc;
482    Clippy, "src/tools/clippy", "clippy", Mode::ToolRustc;
483    CollectLicenseMetadata, "src/tools/collect-license-metadata", "collect-license-metadata", Mode::ToolTarget;
484    Compiletest, "src/tools/compiletest", "compiletest", Mode::ToolTarget;
485    CoverageDump, "src/tools/coverage-dump", "coverage-dump", Mode::ToolTarget;
486    Jsondocck, "src/tools/jsondocck", "jsondocck", Mode::ToolTarget;
487    Jsondoclint, "src/tools/jsondoclint", "jsondoclint", Mode::ToolTarget;
488    LintDocs, "src/tools/lint-docs", "lint-docs", Mode::ToolTarget;
489    LlvmBitcodeLinker, "src/tools/llvm-bitcode-linker", "llvm-bitcode-linker", Mode::ToolTarget;
490    Miri, "src/tools/miri", "miri", Mode::ToolRustc;
491    MiroptTestTools, "src/tools/miropt-test-tools", "miropt-test-tools", Mode::ToolTarget;
492    OptDist, "src/tools/opt-dist", "opt-dist", Mode::ToolTarget;
493    RemoteTestClient, "src/tools/remote-test-client", "remote-test-client", Mode::ToolTarget;
494    RemoteTestServer, "src/tools/remote-test-server", "remote-test-server", Mode::ToolTarget;
495    RustAnalyzer, "src/tools/rust-analyzer", "rust-analyzer", Mode::ToolRustc;
496    Rustdoc, "src/librustdoc", "clippy", Mode::ToolRustc;
497    Rustfmt, "src/tools/rustfmt", "rustfmt", Mode::ToolRustc;
498    RustInstaller, "src/tools/rust-installer", "rust-installer", Mode::ToolTarget;
499    Tidy, "src/tools/tidy", "tidy", Mode::ToolTarget;
500    TestFloatParse, "src/tools/test-float-parse", "test-float-parse", Mode::ToolStd;
501);
502
503/// Runs Clippy on in-tree sources of selected projects using in-tree CLippy.
504#[derive(Debug, Clone, PartialEq, Eq, Hash)]
505pub struct CI {
506    target: TargetSelection,
507    config: LintConfig,
508}
509
510impl Step for CI {
511    type Output = ();
512    const DEFAULT: bool = false;
513
514    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
515        run.alias("ci")
516    }
517
518    fn make_run(run: RunConfig<'_>) {
519        let config = LintConfig::new(run.builder);
520        run.builder.ensure(CI { target: run.target, config });
521    }
522
523    fn run(self, builder: &Builder<'_>) -> Self::Output {
524        if builder.top_stage != 2 {
525            eprintln!("ERROR: `x clippy ci` should always be executed with --stage 2");
526            exit!(1);
527        }
528
529        // We want to check in-tree source using in-tree clippy. However, if we naively did
530        // a stage 2 `x clippy ci`, it would *build* a stage 2 rustc, in order to lint stage 2
531        // std, which is wasteful.
532        // So we want to lint stage 2 [bootstrap/rustc/...], but only stage 1 std rustc_codegen_gcc.
533        // We thus construct the compilers in this step manually, to optimize the number of
534        // steps that get built.
535
536        builder.ensure(Bootstrap {
537            // This will be the stage 1 compiler
538            build_compiler: prepare_compiler_for_check(builder, self.target, Mode::ToolTarget),
539            target: self.target,
540            config: self.config.merge(&LintConfig {
541                allow: vec![],
542                warn: vec![],
543                deny: vec!["warnings".into()],
544                forbid: vec![],
545            }),
546        });
547
548        let library_clippy_cfg = LintConfig {
549            allow: vec!["clippy::all".into()],
550            warn: vec![],
551            deny: vec![
552                "clippy::correctness".into(),
553                "clippy::char_lit_as_u8".into(),
554                "clippy::four_forward_slashes".into(),
555                "clippy::needless_bool".into(),
556                "clippy::needless_bool_assign".into(),
557                "clippy::non_minimal_cfg".into(),
558                "clippy::print_literal".into(),
559                "clippy::same_item_push".into(),
560                "clippy::single_char_add_str".into(),
561                "clippy::to_string_in_format_args".into(),
562            ],
563            forbid: vec![],
564        };
565        builder.ensure(Std::from_build_compiler(
566            // This will be the stage 1 compiler, to avoid building rustc stage 2 just to lint std
567            builder.compiler(1, self.target),
568            self.target,
569            self.config.merge(&library_clippy_cfg),
570            vec![],
571        ));
572
573        let compiler_clippy_cfg = LintConfig {
574            allow: vec!["clippy::all".into()],
575            warn: vec![],
576            deny: vec![
577                "clippy::correctness".into(),
578                "clippy::char_lit_as_u8".into(),
579                "clippy::clone_on_ref_ptr".into(),
580                "clippy::format_in_format_args".into(),
581                "clippy::four_forward_slashes".into(),
582                "clippy::needless_bool".into(),
583                "clippy::needless_bool_assign".into(),
584                "clippy::non_minimal_cfg".into(),
585                "clippy::print_literal".into(),
586                "clippy::same_item_push".into(),
587                "clippy::single_char_add_str".into(),
588                "clippy::to_string_in_format_args".into(),
589            ],
590            forbid: vec![],
591        };
592        // This will lint stage 2 rustc using stage 1 Clippy
593        builder.ensure(Rustc::new(
594            builder,
595            self.target,
596            self.config.merge(&compiler_clippy_cfg),
597            vec![],
598        ));
599
600        let rustc_codegen_gcc = LintConfig {
601            allow: vec![],
602            warn: vec![],
603            deny: vec!["warnings".into()],
604            forbid: vec![],
605        };
606        // This will check stage 2 rustc
607        builder.ensure(CodegenGcc::new(
608            builder,
609            self.target,
610            self.config.merge(&rustc_codegen_gcc),
611        ));
612    }
613}