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