]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/missing_const_for_fn.rs
cargo fmt
[rust.git] / clippy_lints / src / missing_const_for_fn.rs
1 use rustc::hir;
2 use rustc::hir::intravisit::FnKind;
3 use rustc::hir::{Body, Constness, FnDecl};
4 // use rustc::mir::*;
5 use crate::utils::{is_entrypoint_fn, span_lint};
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_mir::transform::qualify_min_const_fn::is_min_const_fn;
9 use syntax::ast::{Attribute, NodeId};
10 use syntax_pos::Span;
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 {
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 /// fn new() -> Self {
45 ///     Self { random_number: 42 }
46 /// }
47 /// ```
48 ///
49 /// Could be a const fn:
50 ///
51 /// ```rust
52 /// const fn new() -> Self {
53 ///     Self { random_number: 42 }
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         // Perform some preliminary checks that rule out constness on the Clippy side. This way we
86         // can skip the actual const check and return early.
87         match kind {
88             FnKind::ItemFn(name, _generics, header, _vis, attrs) => {
89                 if !can_be_const_fn(&name.as_str(), header, attrs) {
90                     return;
91                 }
92             },
93             FnKind::Method(ident, sig, _vis, attrs) => {
94                 let header = sig.header;
95                 let name = ident.name.as_str();
96                 if !can_be_const_fn(&name, header, attrs) {
97                     return;
98                 }
99             },
100             _ => return,
101         }
102
103         let def_id = cx.tcx.hir().local_def_id(node_id);
104         let mir = cx.tcx.optimized_mir(def_id);
105
106         if let Err((span, err)) = is_min_const_fn(cx.tcx, def_id, &mir) {
107             if cx.tcx.is_min_const_fn(def_id) {
108                 cx.tcx.sess.span_err(span, &err);
109             }
110         } else {
111             span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a const_fn");
112         }
113     }
114 }
115
116 fn can_be_const_fn(name: &str, header: hir::FnHeader, attrs: &[Attribute]) -> bool {
117     // Main and custom entrypoints can't be `const`
118     if is_entrypoint_fn(name, attrs) {
119         return false;
120     }
121
122     // We don't have to lint on something that's already `const`
123     if header.constness == Constness::Const {
124         return false;
125     }
126     true
127 }