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