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