]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/missing_const_for_fn.rs
Merge commit '7ea7cd165ad6705603852771bf82cc2fd6560db5' into clippyup2
[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_hir as hir;
3 use rustc_hir::intravisit::FnKind;
4 use rustc_hir::{Body, Constness, FnDecl, GenericParamKind, HirId};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::lint::in_external_macro;
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
12 declare_clippy_lint! {
13     /// **What it does:**
14     ///
15     /// Suggests the use of `const` in functions and methods where possible.
16     ///
17     /// **Why is this bad?**
18     ///
19     /// Not having the function const prevents callers of the function from being const as well.
20     ///
21     /// **Known problems:**
22     ///
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     ///
44     /// ```rust
45     /// # struct Foo {
46     /// #     random_number: usize,
47     /// # }
48     /// # impl Foo {
49     /// fn new() -> Self {
50     ///     Self { random_number: 42 }
51     /// }
52     /// # }
53     /// ```
54     ///
55     /// Could be a const fn:
56     ///
57     /// ```rust
58     /// # struct Foo {
59     /// #     random_number: usize,
60     /// # }
61     /// # impl Foo {
62     /// const fn new() -> Self {
63     ///     Self { random_number: 42 }
64     /// }
65     /// # }
66     /// ```
67     pub MISSING_CONST_FOR_FN,
68     nursery,
69     "Lint functions definitions that could be made `const fn`"
70 }
71
72 declare_lint_pass!(MissingConstForFn => [MISSING_CONST_FOR_FN]);
73
74 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingConstForFn {
75     fn check_fn(
76         &mut self,
77         cx: &LateContext<'_, '_>,
78         kind: FnKind<'_>,
79         _: &FnDecl<'_>,
80         _: &Body<'_>,
81         span: Span,
82         hir_id: HirId,
83     ) {
84         let def_id = cx.tcx.hir().local_def_id(hir_id);
85
86         if in_external_macro(cx.tcx.sess, span) || is_entrypoint_fn(cx, def_id.to_def_id()) {
87             return;
88         }
89
90         // Building MIR for `fn`s with unsatisfiable preds results in ICE.
91         if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
92             return;
93         }
94
95         // Perform some preliminary checks that rule out constness on the Clippy side. This way we
96         // can skip the actual const check and return early.
97         match kind {
98             FnKind::ItemFn(_, generics, header, ..) => {
99                 let has_const_generic_params = generics
100                     .params
101                     .iter()
102                     .any(|param| matches!(param.kind, GenericParamKind::Const{ .. }));
103
104                 if already_const(header) || has_const_generic_params {
105                     return;
106                 }
107             },
108             FnKind::Method(_, sig, ..) => {
109                 if trait_ref_of_method(cx, hir_id).is_some()
110                     || already_const(sig.header)
111                     || method_accepts_dropable(cx, sig.decl.inputs)
112                 {
113                     return;
114                 }
115             },
116             FnKind::Closure(..) => return,
117         }
118
119         let mir = cx.tcx.optimized_mir(def_id);
120
121         if let Err((span, err)) = is_min_const_fn(cx.tcx, def_id.to_def_id(), &mir) {
122             if rustc_mir::const_eval::is_min_const_fn(cx.tcx, def_id.to_def_id()) {
123                 cx.tcx.sess.span_err(span, &err);
124             }
125         } else {
126             span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a `const fn`");
127         }
128     }
129 }
130
131 /// Returns true if any of the method parameters is a type that implements `Drop`. The method
132 /// can't be made const then, because `drop` can't be const-evaluated.
133 fn method_accepts_dropable(cx: &LateContext<'_, '_>, param_tys: &[hir::Ty<'_>]) -> bool {
134     // If any of the params are dropable, return true
135     param_tys.iter().any(|hir_ty| {
136         let ty_ty = hir_ty_to_ty(cx.tcx, hir_ty);
137         has_drop(cx, ty_ty)
138     })
139 }
140
141 // We don't have to lint on something that's already `const`
142 #[must_use]
143 fn already_const(header: hir::FnHeader) -> bool {
144     header.constness == Constness::Const
145 }