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