Skip to content

Commit

Permalink
Do not trigger clippy::missing_const_for_fn triggering for tests
Browse files Browse the repository at this point in the history
  • Loading branch information
alex-semenyuk committed Jan 5, 2025
1 parent 034f3d2 commit d0a7688
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
9 changes: 6 additions & 3 deletions clippy_lints/src/missing_const_for_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::qualify_min_const_fn::is_min_const_fn;
use clippy_utils::{fn_has_unsatisfiable_preds, is_entrypoint_fn, is_from_proc_macro, trait_ref_of_method};
use clippy_utils::{fn_has_unsatisfiable_preds, is_entrypoint_fn, is_from_proc_macro, is_in_test, trait_ref_of_method};
use rustc_errors::Applicability;
use rustc_hir::def_id::CRATE_DEF_ID;
use rustc_hir::intravisit::FnKind;
Expand Down Expand Up @@ -101,6 +101,11 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn {
return;
}

let hir_id = cx.tcx.local_def_id_to_hir_id(def_id);
if is_in_test(cx.tcx, hir_id) {
return;
}

if in_external_macro(cx.tcx.sess, span) || is_entrypoint_fn(cx, def_id.to_def_id()) {
return;
}
Expand Down Expand Up @@ -136,8 +141,6 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn {
return;
}

let hir_id = cx.tcx.local_def_id_to_hir_id(def_id);

// Const fns are not allowed as methods in a trait.
{
let parent = cx.tcx.hir().get_parent_item(hir_id).def_id;
Expand Down
29 changes: 28 additions & 1 deletion tests/ui/missing_const_for_fn/cant_be_const.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,34 @@ fn get_y() -> u32 {
Y
}

// Don't lint entrypoint functions
#[cfg(test)]
mod with_test_fn {
#[derive(Clone, Copy)]
pub struct Foo {
pub n: u32,
}

impl Foo {
#[must_use]
pub const fn new(n: u32) -> Foo {
Foo { n }
}
}

#[test]
fn foo_is_copy() {
let foo = Foo::new(42);
let one = foo;
let two = foo;
_ = one;
_ = two;
}
}

// Allowing on this function, because it would lint, which we don't want in this case.
// if we have `#[start]` and `#[test]` check `is_entrypoint_fn(cx, def_id.to_def_id())` is stopped
// working
#[allow(clippy::missing_const_for_fn)]
#[start]
fn init(num: isize, something: *const *const u8) -> isize {
1
Expand Down

0 comments on commit d0a7688

Please sign in to comment.