2 use rustc::hir::intravisit::FnKind;
3 use rustc::hir::{Body, Constness, FnDecl};
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};
14 /// Suggests the use of `const` in functions and methods where possible
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.
20 /// **Known problems:**
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.
26 /// Also, the lint only runs one pass over the code. Consider these two non-const functions:
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.
44 /// fn new() -> Self {
45 /// Self { random_number: 42 }
49 /// Could be a const fn:
52 /// const fn new() -> Self {
53 /// Self { random_number: 42 }
56 declare_clippy_lint! {
57 pub MISSING_CONST_FOR_FN,
59 "Lint functions definitions that could be made `const fn`"
63 pub struct MissingConstForFn;
65 impl LintPass for MissingConstForFn {
66 fn get_lints(&self) -> LintArray {
67 lint_array!(MISSING_CONST_FOR_FN)
70 fn name(&self) -> &'static str {
75 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingConstForFn {
78 cx: &LateContext<'_, '_>,
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.
88 FnKind::ItemFn(name, _generics, header, _vis, attrs) => {
89 if !can_be_const_fn(&name.as_str(), header, attrs) {
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) {
103 let def_id = cx.tcx.hir().local_def_id(node_id);
104 let mir = cx.tcx.optimized_mir(def_id);
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);
111 span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a const_fn");
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) {
122 // We don't have to lint on something that's already `const`
123 if header.constness == Constness::Const {