]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/missing_const_for_fn.rs
Merge remote-tracking branch 'upstream/rust-1.39.0' into backport_merge
[rust.git] / clippy_lints / src / missing_const_for_fn.rs
1 use crate::utils::{has_drop, is_entrypoint_fn, span_lint, trait_ref_of_method};
2 use rustc::hir;
3 use rustc::hir::intravisit::FnKind;
4 use rustc::hir::{Body, Constness, FnDecl, HirId, HirVec};
5 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_mir::transform::qualify_min_const_fn::is_min_const_fn;
8 use rustc_typeck::hir_ty_to_ty;
9 use syntax_pos::Span;
10
11 declare_clippy_lint! {
12     /// **What it does:**
13     ///
14     /// Suggests the use of `const` in functions and methods where possible.
15     ///
16     /// **Why is this bad?**
17     ///
18     /// Not having the function const prevents callers of the function from being const as well.
19     ///
20     /// **Known problems:**
21     ///
22     /// Const functions are currently still being worked on, with some features only being available
23     /// on nightly. This lint does not consider all edge cases currently and the suggestions may be
24     /// incorrect if you are using this lint on stable.
25     ///
26     /// Also, the lint only runs one pass over the code. Consider these two non-const functions:
27     ///
28     /// ```rust
29     /// fn a() -> i32 {
30     ///     0
31     /// }
32     /// fn b() -> i32 {
33     ///     a()
34     /// }
35     /// ```
36     ///
37     /// When running Clippy, the lint will only suggest to make `a` const, because `b` at this time
38     /// can't be const as it calls a non-const function. Making `a` const and running Clippy again,
39     /// will suggest to make `b` const, too.
40     ///
41     /// **Example:**
42     ///
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 declare_lint_pass!(MissingConstForFn => [MISSING_CONST_FOR_FN]);
72
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingConstForFn {
74     fn check_fn(
75         &mut self,
76         cx: &LateContext<'_, '_>,
77         kind: FnKind<'_>,
78         _: &FnDecl,
79         _: &Body,
80         span: Span,
81         hir_id: HirId,
82     ) {
83         let def_id = cx.tcx.hir().local_def_id(hir_id);
84
85         if in_external_macro(cx.tcx.sess, span) || is_entrypoint_fn(cx, def_id) {
86             return;
87         }
88
89         // Perform some preliminary checks that rule out constness on the Clippy side. This way we
90         // can skip the actual const check and return early.
91         match kind {
92             FnKind::ItemFn(_, _, header, ..) => {
93                 if already_const(header) {
94                     return;
95                 }
96             },
97             FnKind::Method(_, sig, ..) => {
98                 if trait_ref_of_method(cx, hir_id).is_some()
99                     || already_const(sig.header)
100                     || method_accepts_dropable(cx, &sig.decl.inputs)
101                 {
102                     return;
103                 }
104             },
105             _ => return,
106         }
107
108         let mir = cx.tcx.optimized_mir(def_id);
109
110         if let Err((span, err)) = is_min_const_fn(cx.tcx, def_id, &mir) {
111             if cx.tcx.is_min_const_fn(def_id) {
112                 cx.tcx.sess.span_err(span, &err);
113             }
114         } else {
115             span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a const_fn");
116         }
117     }
118 }
119
120 /// Returns true if any of the method parameters is a type that implements `Drop`. The method
121 /// can't be made const then, because `drop` can't be const-evaluated.
122 fn method_accepts_dropable(cx: &LateContext<'_, '_>, param_tys: &HirVec<hir::Ty>) -> bool {
123     // If any of the params are dropable, return true
124     param_tys.iter().any(|hir_ty| {
125         let ty_ty = hir_ty_to_ty(cx.tcx, hir_ty);
126         has_drop(cx, ty_ty)
127     })
128 }
129
130 // We don't have to lint on something that's already `const`
131 #[must_use]
132 fn already_const(header: hir::FnHeader) -> bool {
133     header.constness == Constness::Const
134 }