]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/missing_const_for_fn.rs
Rollup merge of #84484 - jyn514:check-tools, r=Mark-Simulacrum
[rust.git] / clippy_lints / src / missing_const_for_fn.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::qualify_min_const_fn::is_min_const_fn;
3 use clippy_utils::ty::has_drop;
4 use clippy_utils::{fn_has_unsatisfiable_preds, is_entrypoint_fn, meets_msrv, msrvs, trait_ref_of_method};
5 use rustc_hir as hir;
6 use rustc_hir::intravisit::FnKind;
7 use rustc_hir::{Body, Constness, FnDecl, GenericParamKind, HirId};
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_semver::RustcVersion;
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::Span;
13 use rustc_typeck::hir_ty_to_ty;
14
15 declare_clippy_lint! {
16     /// **What it does:**
17     ///
18     /// Suggests the use of `const` in functions and methods where possible.
19     ///
20     /// **Why is this bad?**
21     ///
22     /// Not having the function const prevents callers of the function from being const as well.
23     ///
24     /// **Known problems:**
25     ///
26     /// Const functions are currently still being worked on, with some features only being available
27     /// on nightly. This lint does not consider all edge cases currently and the suggestions may be
28     /// incorrect if you are using this lint on stable.
29     ///
30     /// Also, the lint only runs one pass over the code. Consider these two non-const functions:
31     ///
32     /// ```rust
33     /// fn a() -> i32 {
34     ///     0
35     /// }
36     /// fn b() -> i32 {
37     ///     a()
38     /// }
39     /// ```
40     ///
41     /// When running Clippy, the lint will only suggest to make `a` const, because `b` at this time
42     /// can't be const as it calls a non-const function. Making `a` const and running Clippy again,
43     /// will suggest to make `b` const, too.
44     ///
45     /// **Example:**
46     ///
47     /// ```rust
48     /// # struct Foo {
49     /// #     random_number: usize,
50     /// # }
51     /// # impl Foo {
52     /// fn new() -> Self {
53     ///     Self { random_number: 42 }
54     /// }
55     /// # }
56     /// ```
57     ///
58     /// Could be a const fn:
59     ///
60     /// ```rust
61     /// # struct Foo {
62     /// #     random_number: usize,
63     /// # }
64     /// # impl Foo {
65     /// const fn new() -> Self {
66     ///     Self { random_number: 42 }
67     /// }
68     /// # }
69     /// ```
70     pub MISSING_CONST_FOR_FN,
71     nursery,
72     "Lint functions definitions that could be made `const fn`"
73 }
74
75 impl_lint_pass!(MissingConstForFn => [MISSING_CONST_FOR_FN]);
76
77 pub struct MissingConstForFn {
78     msrv: Option<RustcVersion>,
79 }
80
81 impl MissingConstForFn {
82     #[must_use]
83     pub fn new(msrv: Option<RustcVersion>) -> Self {
84         Self { msrv }
85     }
86 }
87
88 impl<'tcx> LateLintPass<'tcx> for MissingConstForFn {
89     fn check_fn(
90         &mut self,
91         cx: &LateContext<'_>,
92         kind: FnKind<'_>,
93         _: &FnDecl<'_>,
94         _: &Body<'_>,
95         span: Span,
96         hir_id: HirId,
97     ) {
98         if !meets_msrv(self.msrv.as_ref(), &msrvs::CONST_IF_MATCH) {
99             return;
100         }
101
102         let def_id = cx.tcx.hir().local_def_id(hir_id);
103
104         if in_external_macro(cx.tcx.sess, span) || is_entrypoint_fn(cx, def_id.to_def_id()) {
105             return;
106         }
107
108         // Building MIR for `fn`s with unsatisfiable preds results in ICE.
109         if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
110             return;
111         }
112
113         // Perform some preliminary checks that rule out constness on the Clippy side. This way we
114         // can skip the actual const check and return early.
115         match kind {
116             FnKind::ItemFn(_, generics, header, ..) => {
117                 let has_const_generic_params = generics
118                     .params
119                     .iter()
120                     .any(|param| matches!(param.kind, GenericParamKind::Const { .. }));
121
122                 if already_const(header) || has_const_generic_params {
123                     return;
124                 }
125             },
126             FnKind::Method(_, sig, ..) => {
127                 if trait_ref_of_method(cx, hir_id).is_some()
128                     || already_const(sig.header)
129                     || method_accepts_dropable(cx, sig.decl.inputs)
130                 {
131                     return;
132                 }
133             },
134             FnKind::Closure => return,
135         }
136
137         let mir = cx.tcx.optimized_mir(def_id);
138
139         if let Err((span, err)) = is_min_const_fn(cx.tcx, mir, self.msrv.as_ref()) {
140             if cx.tcx.is_const_fn_raw(def_id.to_def_id()) {
141                 cx.tcx.sess.span_err(span, &err);
142             }
143         } else {
144             span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a `const fn`");
145         }
146     }
147     extract_msrv_attr!(LateContext);
148 }
149
150 /// Returns true if any of the method parameters is a type that implements `Drop`. The method
151 /// can't be made const then, because `drop` can't be const-evaluated.
152 fn method_accepts_dropable(cx: &LateContext<'_>, param_tys: &[hir::Ty<'_>]) -> bool {
153     // If any of the params are droppable, return true
154     param_tys.iter().any(|hir_ty| {
155         let ty_ty = hir_ty_to_ty(cx.tcx, hir_ty);
156         has_drop(cx, ty_ty)
157     })
158 }
159
160 // We don't have to lint on something that's already `const`
161 #[must_use]
162 fn already_const(header: hir::FnHeader) -> bool {
163     header.constness == Constness::Const
164 }