Skip to content

Commit 0e2505b

Browse files
authored
Do not trigger missing_const_for_fn for tests (#13945)
Close #13938 changelog: [`missing_const_for_fn`]: do not trigger for tests
2 parents a9c0e22 + ca55534 commit 0e2505b

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

clippy_lints/src/missing_const_for_fn.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use clippy_config::Conf;
22
use clippy_utils::diagnostics::span_lint_and_then;
33
use clippy_utils::msrvs::{self, Msrv};
44
use clippy_utils::qualify_min_const_fn::is_min_const_fn;
5-
use clippy_utils::{fn_has_unsatisfiable_preds, is_entrypoint_fn, is_from_proc_macro, trait_ref_of_method};
5+
use clippy_utils::{fn_has_unsatisfiable_preds, is_entrypoint_fn, is_from_proc_macro, is_in_test, trait_ref_of_method};
66
use rustc_errors::Applicability;
77
use rustc_hir::def_id::CRATE_DEF_ID;
88
use rustc_hir::intravisit::FnKind;
@@ -97,6 +97,11 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn {
9797
span: Span,
9898
def_id: LocalDefId,
9999
) {
100+
let hir_id = cx.tcx.local_def_id_to_hir_id(def_id);
101+
if is_in_test(cx.tcx, hir_id) {
102+
return;
103+
}
104+
100105
if !self.msrv.meets(msrvs::CONST_IF_MATCH) {
101106
return;
102107
}
@@ -136,8 +141,6 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn {
136141
return;
137142
}
138143

139-
let hir_id = cx.tcx.local_def_id_to_hir_id(def_id);
140-
141144
// Const fns are not allowed as methods in a trait.
142145
{
143146
let parent = cx.tcx.hir().get_parent_item(hir_id).def_id;

tests/ui/missing_const_for_fn/cant_be_const.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,34 @@ fn get_y() -> u32 {
4747
Y
4848
}
4949

50-
// Don't lint entrypoint functions
50+
#[cfg(test)]
51+
mod with_test_fn {
52+
#[derive(Clone, Copy)]
53+
pub struct Foo {
54+
pub n: u32,
55+
}
56+
57+
impl Foo {
58+
#[must_use]
59+
pub const fn new(n: u32) -> Foo {
60+
Foo { n }
61+
}
62+
}
63+
64+
#[test]
65+
fn foo_is_copy() {
66+
let foo = Foo::new(42);
67+
let one = foo;
68+
let two = foo;
69+
_ = one;
70+
_ = two;
71+
}
72+
}
73+
74+
// Allowing on this function, because it would lint, which we don't want in this case.
75+
// if we have `#[start]` and `#[test]` check `is_entrypoint_fn(cx, def_id.to_def_id())` is stopped
76+
// working
77+
#[allow(clippy::missing_const_for_fn)]
5178
#[start]
5279
fn init(num: isize, something: *const *const u8) -> isize {
5380
1

0 commit comments

Comments
 (0)