]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs
Rollup merge of #92802 - compiler-errors:deduplicate-stack-trace, r=oli-obk
[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};
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     #[clippy::version = "1.34.0"]
67     pub MISSING_CONST_FOR_FN,
68     nursery,
69     "Lint functions definitions that could be made `const fn`"
70 }
71
72 impl_lint_pass!(MissingConstForFn => [MISSING_CONST_FOR_FN]);
73
74 pub struct MissingConstForFn {
75     msrv: Option<RustcVersion>,
76 }
77
78 impl MissingConstForFn {
79     #[must_use]
80     pub fn new(msrv: Option<RustcVersion>) -> Self {
81         Self { msrv }
82     }
83 }
84
85 impl<'tcx> LateLintPass<'tcx> for MissingConstForFn {
86     fn check_fn(
87         &mut self,
88         cx: &LateContext<'_>,
89         kind: FnKind<'_>,
90         _: &FnDecl<'_>,
91         _: &Body<'_>,
92         span: Span,
93         hir_id: HirId,
94     ) {
95         if !meets_msrv(self.msrv.as_ref(), &msrvs::CONST_IF_MATCH) {
96             return;
97         }
98
99         let def_id = cx.tcx.hir().local_def_id(hir_id);
100
101         if in_external_macro(cx.tcx.sess, span) || is_entrypoint_fn(cx, def_id.to_def_id()) {
102             return;
103         }
104
105         // Building MIR for `fn`s with unsatisfiable preds results in ICE.
106         if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
107             return;
108         }
109
110         // Perform some preliminary checks that rule out constness on the Clippy side. This way we
111         // can skip the actual const check and return early.
112         match kind {
113             FnKind::ItemFn(_, generics, header, ..) => {
114                 let has_const_generic_params = generics
115                     .params
116                     .iter()
117                     .any(|param| matches!(param.kind, GenericParamKind::Const { .. }));
118
119                 if already_const(header) || has_const_generic_params {
120                     return;
121                 }
122             },
123             FnKind::Method(_, sig, ..) => {
124                 if trait_ref_of_method(cx, def_id).is_some()
125                     || already_const(sig.header)
126                     || method_accepts_dropable(cx, sig.decl.inputs)
127                 {
128                     return;
129                 }
130             },
131             FnKind::Closure => return,
132         }
133
134         let mir = cx.tcx.optimized_mir(def_id);
135
136         if let Err((span, err)) = is_min_const_fn(cx.tcx, mir, self.msrv.as_ref()) {
137             if cx.tcx.is_const_fn_raw(def_id.to_def_id()) {
138                 cx.tcx.sess.span_err(span, &err);
139             }
140         } else {
141             span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a `const fn`");
142         }
143     }
144     extract_msrv_attr!(LateContext);
145 }
146
147 /// Returns true if any of the method parameters is a type that implements `Drop`. The method
148 /// can't be made const then, because `drop` can't be const-evaluated.
149 fn method_accepts_dropable(cx: &LateContext<'_>, param_tys: &[hir::Ty<'_>]) -> bool {
150     // If any of the params are droppable, return true
151     param_tys.iter().any(|hir_ty| {
152         let ty_ty = hir_ty_to_ty(cx.tcx, hir_ty);
153         has_drop(cx, ty_ty)
154     })
155 }
156
157 // We don't have to lint on something that's already `const`
158 #[must_use]
159 fn already_const(header: hir::FnHeader) -> bool {
160     header.constness == Constness::Const
161 }