Skip to content

Commit 6b1a2a9

Browse files
committed
Auto merge of rust-lang#3648 - phansch:const_fn_lint, r=oli-obk
Add initial version of const_fn lint This adds an initial version of a lint that can tell if a function could be `const`. TODO: - [x] Finish up the docs - [x] Fix the ICE cc rust-lang#2440
2 parents f55d521 + d0d7c5e commit 6b1a2a9

File tree

9 files changed

+304
-2
lines changed

9 files changed

+304
-2
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,7 @@ All notable changes to this project will be documented in this file.
878878
[`min_max`]: https://rust-lang.github.io/rust-clippy/master/index.html#min_max
879879
[`misaligned_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#misaligned_transmute
880880
[`misrefactored_assign_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#misrefactored_assign_op
881+
[`missing_const_for_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn
881882
[`missing_docs_in_private_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_docs_in_private_items
882883
[`missing_inline_in_public_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_inline_in_public_items
883884
[`mistyped_literal_suffixes`]: https://rust-lang.github.io/rust-clippy/master/index.html#mistyped_literal_suffixes

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
99

10-
[There are 292 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
10+
[There are 293 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
1111

1212
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1313

clippy_lints/src/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ extern crate rustc_data_structures;
2323
#[allow(unused_extern_crates)]
2424
extern crate rustc_errors;
2525
#[allow(unused_extern_crates)]
26+
extern crate rustc_mir;
27+
#[allow(unused_extern_crates)]
2628
extern crate rustc_plugin;
2729
#[allow(unused_extern_crates)]
2830
extern crate rustc_target;
@@ -144,6 +146,7 @@ pub mod methods;
144146
pub mod minmax;
145147
pub mod misc;
146148
pub mod misc_early;
149+
pub mod missing_const_for_fn;
147150
pub mod missing_doc;
148151
pub mod missing_inline;
149152
pub mod multiple_crate_versions;
@@ -486,6 +489,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
486489
reg.register_late_lint_pass(box slow_vector_initialization::Pass);
487490
reg.register_late_lint_pass(box types::RefToMut);
488491
reg.register_late_lint_pass(box assertions_on_constants::AssertionsOnConstants);
492+
reg.register_late_lint_pass(box missing_const_for_fn::MissingConstForFn);
489493

490494
reg.register_lint_group("clippy::restriction", Some("clippy_restriction"), vec![
491495
arithmetic::FLOAT_ARITHMETIC,
@@ -1027,6 +1031,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
10271031
reg.register_lint_group("clippy::nursery", Some("clippy_nursery"), vec![
10281032
attrs::EMPTY_LINE_AFTER_OUTER_ATTR,
10291033
fallible_impl_from::FALLIBLE_IMPL_FROM,
1034+
missing_const_for_fn::MISSING_CONST_FOR_FN,
10301035
mutex_atomic::MUTEX_INTEGER,
10311036
needless_borrow::NEEDLESS_BORROW,
10321037
redundant_clone::REDUNDANT_CLONE,
+121
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
use crate::utils::{is_entrypoint_fn, span_lint};
2+
use rustc::hir;
3+
use rustc::hir::intravisit::FnKind;
4+
use rustc::hir::{Body, Constness, FnDecl};
5+
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6+
use rustc::{declare_tool_lint, lint_array};
7+
use rustc_mir::transform::qualify_min_const_fn::is_min_const_fn;
8+
use syntax::ast::NodeId;
9+
use syntax_pos::Span;
10+
11+
/// **What it does:**
12+
///
13+
/// Suggests the use of `const` in functions and methods where possible.
14+
///
15+
/// **Why is this bad?**
16+
///
17+
/// Not having the function const prevents callers of the function from being const as well.
18+
///
19+
/// **Known problems:**
20+
///
21+
/// Const functions are currently still being worked on, with some features only being available
22+
/// on nightly. This lint does not consider all edge cases currently and the suggestions may be
23+
/// incorrect if you are using this lint on stable.
24+
///
25+
/// Also, the lint only runs one pass over the code. Consider these two non-const functions:
26+
///
27+
/// ```rust
28+
/// fn a() -> i32 {
29+
/// 0
30+
/// }
31+
/// fn b() -> i32 {
32+
/// a()
33+
/// }
34+
/// ```
35+
///
36+
/// When running Clippy, the lint will only suggest to make `a` const, because `b` at this time
37+
/// can't be const as it calls a non-const function. Making `a` const and running Clippy again,
38+
/// will suggest to make `b` const, too.
39+
///
40+
/// **Example:**
41+
///
42+
/// ```rust
43+
/// fn new() -> Self {
44+
/// Self { random_number: 42 }
45+
/// }
46+
/// ```
47+
///
48+
/// Could be a const fn:
49+
///
50+
/// ```rust
51+
/// const fn new() -> Self {
52+
/// Self { random_number: 42 }
53+
/// }
54+
/// ```
55+
declare_clippy_lint! {
56+
pub MISSING_CONST_FOR_FN,
57+
nursery,
58+
"Lint functions definitions that could be made `const fn`"
59+
}
60+
61+
#[derive(Clone)]
62+
pub struct MissingConstForFn;
63+
64+
impl LintPass for MissingConstForFn {
65+
fn get_lints(&self) -> LintArray {
66+
lint_array!(MISSING_CONST_FOR_FN)
67+
}
68+
69+
fn name(&self) -> &'static str {
70+
"MissingConstForFn"
71+
}
72+
}
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+
node_id: NodeId,
83+
) {
84+
let def_id = cx.tcx.hir().local_def_id(node_id);
85+
86+
if is_entrypoint_fn(cx, def_id) {
87+
return;
88+
}
89+
90+
// Perform some preliminary checks that rule out constness on the Clippy side. This way we
91+
// can skip the actual const check and return early.
92+
match kind {
93+
FnKind::ItemFn(_, _, header, ..) => {
94+
if already_const(header) {
95+
return;
96+
}
97+
},
98+
FnKind::Method(_, sig, ..) => {
99+
if already_const(sig.header) {
100+
return;
101+
}
102+
},
103+
_ => return,
104+
}
105+
106+
let mir = cx.tcx.optimized_mir(def_id);
107+
108+
if let Err((span, err)) = is_min_const_fn(cx.tcx, def_id, &mir) {
109+
if cx.tcx.is_min_const_fn(def_id) {
110+
cx.tcx.sess.span_err(span, &err);
111+
}
112+
} else {
113+
span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a const_fn");
114+
}
115+
}
116+
}
117+
118+
// We don't have to lint on something that's already `const`
119+
fn already_const(header: hir::FnHeader) -> bool {
120+
header.constness == Constness::Const
121+
}

clippy_lints/src/utils/mod.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use if_chain::if_chain;
33
use matches::matches;
44
use rustc::hir;
55
use rustc::hir::def::Def;
6-
use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
6+
use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
77
use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
88
use rustc::hir::Node;
99
use rustc::hir::*;
@@ -350,6 +350,14 @@ pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a
350350
Some(matched)
351351
}
352352

353+
/// Returns true if the provided `def_id` is an entrypoint to a program
354+
pub fn is_entrypoint_fn(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
355+
if let Some((entry_fn_def_id, _)) = cx.tcx.entry_fn(LOCAL_CRATE) {
356+
return def_id == entry_fn_def_id;
357+
}
358+
false
359+
}
360+
353361
/// Get the name of the item the expression is in, if available.
354362
pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<Name> {
355363
let parent_id = cx.tcx.hir().get_parent(expr.id);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
//! False-positive tests to ensure we don't suggest `const` for things where it would cause a
2+
//! compilation error.
3+
//! The .stderr output of this test should be empty. Otherwise it's a bug somewhere.
4+
5+
#![warn(clippy::missing_const_for_fn)]
6+
#![feature(start)]
7+
8+
struct Game;
9+
10+
// This should not be linted because it's already const
11+
const fn already_const() -> i32 {
12+
32
13+
}
14+
15+
impl Game {
16+
// This should not be linted because it's already const
17+
pub const fn already_const() -> i32 {
18+
32
19+
}
20+
}
21+
22+
// Allowing on this function, because it would lint, which we don't want in this case.
23+
#[allow(clippy::missing_const_for_fn)]
24+
fn random() -> u32 {
25+
42
26+
}
27+
28+
// We should not suggest to make this function `const` because `random()` is non-const
29+
fn random_caller() -> u32 {
30+
random()
31+
}
32+
33+
static Y: u32 = 0;
34+
35+
// We should not suggest to make this function `const` because const functions are not allowed to
36+
// refer to a static variable
37+
fn get_y() -> u32 {
38+
Y
39+
//~^ ERROR E0013
40+
}
41+
42+
// Don't lint entrypoint functions
43+
#[start]
44+
fn init(num: isize, something: *const *const u8) -> isize {
45+
1
46+
}
47+
48+
trait Foo {
49+
// This should not be suggested to be made const
50+
// (rustc doesn't allow const trait methods)
51+
fn f() -> u32;
52+
53+
// This should not be suggested to be made const either
54+
fn g() -> u32 {
55+
33
56+
}
57+
}

tests/ui/missing_const_for_fn/cant_be_const.stderr

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#![warn(clippy::missing_const_for_fn)]
2+
#![allow(clippy::let_and_return)]
3+
4+
use std::mem::transmute;
5+
6+
struct Game {
7+
guess: i32,
8+
}
9+
10+
impl Game {
11+
// Could be const
12+
pub fn new() -> Self {
13+
Self { guess: 42 }
14+
}
15+
}
16+
17+
// Could be const
18+
fn one() -> i32 {
19+
1
20+
}
21+
22+
// Could also be const
23+
fn two() -> i32 {
24+
let abc = 2;
25+
abc
26+
}
27+
28+
// FIXME: This is a false positive in the `is_min_const_fn` function.
29+
// At least until the `const_string_new` feature is stabilzed.
30+
fn string() -> String {
31+
String::new()
32+
}
33+
34+
// Could be const
35+
unsafe fn four() -> i32 {
36+
4
37+
}
38+
39+
// Could also be const
40+
fn generic<T>(t: T) -> T {
41+
t
42+
}
43+
44+
// FIXME: Depends on the `const_transmute` and `const_fn` feature gates.
45+
// In the future Clippy should be able to suggest this as const, too.
46+
fn sub(x: u32) -> usize {
47+
unsafe { transmute(&x) }
48+
}
49+
50+
// NOTE: This is currently not yet allowed to be const
51+
// Once implemented, Clippy should be able to suggest this as const, too.
52+
fn generic_arr<T: Copy>(t: [T; 1]) -> T {
53+
t[0]
54+
}
55+
56+
// Should not be const
57+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
error: this could be a const_fn
2+
--> $DIR/could_be_const.rs:12:5
3+
|
4+
LL | / pub fn new() -> Self {
5+
LL | | Self { guess: 42 }
6+
LL | | }
7+
| |_____^
8+
|
9+
= note: `-D clippy::missing-const-for-fn` implied by `-D warnings`
10+
11+
error: this could be a const_fn
12+
--> $DIR/could_be_const.rs:18:1
13+
|
14+
LL | / fn one() -> i32 {
15+
LL | | 1
16+
LL | | }
17+
| |_^
18+
19+
error: this could be a const_fn
20+
--> $DIR/could_be_const.rs:23:1
21+
|
22+
LL | / fn two() -> i32 {
23+
LL | | let abc = 2;
24+
LL | | abc
25+
LL | | }
26+
| |_^
27+
28+
error: this could be a const_fn
29+
--> $DIR/could_be_const.rs:30:1
30+
|
31+
LL | / fn string() -> String {
32+
LL | | String::new()
33+
LL | | }
34+
| |_^
35+
36+
error: this could be a const_fn
37+
--> $DIR/could_be_const.rs:35:1
38+
|
39+
LL | / unsafe fn four() -> i32 {
40+
LL | | 4
41+
LL | | }
42+
| |_^
43+
44+
error: this could be a const_fn
45+
--> $DIR/could_be_const.rs:40:1
46+
|
47+
LL | / fn generic<T>(t: T) -> T {
48+
LL | | t
49+
LL | | }
50+
| |_^
51+
52+
error: aborting due to 6 previous errors
53+

0 commit comments

Comments
 (0)