]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/missing_const_for_fn.rs
caa516acd24d13192250f68acec3c8770187bd45
[rust.git] / clippy_lints / src / missing_const_for_fn.rs
1 use rustc::hir;
2 use rustc::hir::{Body, FnDecl, Constness};
3 use rustc::hir::intravisit::FnKind;
4 // use rustc::mir::*;
5 use syntax::ast::{NodeId, Attribute};
6 use syntax_pos::Span;
7 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc::{declare_tool_lint, lint_array};
9 use rustc_mir::transform::qualify_min_const_fn::is_min_const_fn;
10 use crate::utils::{span_lint, is_entrypoint_fn};
11
12 /// **What it does:**
13 ///
14 /// Suggests the use of `const` in functions and methods where possible
15 ///
16 /// **Why is this bad?**
17 /// Not using `const` is a missed optimization. Instead of having the function execute at runtime,
18 /// when using `const`, it's evaluated at compiletime.
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 { 0 }
30 /// fn b() -> i32 { a() }
31 /// ```
32 ///
33 /// When running Clippy, the lint will only suggest to make `a` const, because `b` at this time
34 /// can't be const as it calls a non-const function. Making `a` const and running Clippy again,
35 /// will suggest to make `b` const, too.
36 ///
37 /// **Example:**
38 ///
39 /// ```rust
40 /// fn new() -> Self {
41 ///     Self {
42 ///         random_number: 42
43 ///     }
44 /// }
45 /// ```
46 ///
47 /// Could be a const fn:
48 ///
49 /// ```rust
50 /// const fn new() -> Self {
51 ///     Self {
52 ///         random_number: 42
53 ///     }
54 /// }
55 /// ```
56 declare_clippy_lint! {
57     pub MISSING_CONST_FOR_FN,
58     nursery,
59     "Lint functions definitions that could be made `const fn`"
60 }
61
62 #[derive(Clone)]
63 pub struct MissingConstForFn;
64
65 impl LintPass for MissingConstForFn {
66     fn get_lints(&self) -> LintArray {
67         lint_array!(MISSING_CONST_FOR_FN)
68     }
69
70     fn name(&self) -> &'static str {
71         "MissingConstForFn"
72     }
73 }
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         node_id: NodeId
84     ) {
85         let def_id = cx.tcx.hir().local_def_id(node_id);
86         let mir = cx.tcx.optimized_mir(def_id);
87         if let Err((span, err) = is_min_const_fn(cx.tcx, def_id, &mir) {
88             cx.tcx.sess.span_err(span, &err);
89         } else {
90             match kind {
91                 FnKind::ItemFn(name, _generics, header, _vis, attrs) => {
92                     if !can_be_const_fn(&name.as_str(), header, attrs) {
93                         return;
94                     }
95                 },
96                 FnKind::Method(ident, sig, _vis, attrs) => {
97                     let header = sig.header;
98                     let name = ident.name.as_str();
99                     if !can_be_const_fn(&name, header, attrs) {
100                         return;
101                     }
102                 },
103                 _ => return
104             }
105             span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a const_fn");
106         }
107     }
108 }
109
110 fn can_be_const_fn(name: &str, header: hir::FnHeader, attrs: &[Attribute]) -> bool {
111     // Main and custom entrypoints can't be `const`
112     if is_entrypoint_fn(name, attrs) { return false }
113
114     // We don't have to lint on something that's already `const`
115     if header.constness == Constness::Const { return false }
116     true
117 }