Skip to content

Commit 8d4dd77

Browse files
committed
Fix missing_const_for_fn false positive
We don't want to lint if the type of the method implements drop. (constant functions cannot evaluate destructors)
1 parent 05f603e commit 8d4dd77

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

clippy_lints/src/missing_const_for_fn.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
use crate::utils::{is_entrypoint_fn, span_lint, trait_ref_of_method};
1+
use crate::utils::{has_drop, is_entrypoint_fn, is_self_ty, span_lint, trait_ref_of_method};
22
use rustc::hir;
33
use rustc::hir::intravisit::FnKind;
44
use rustc::hir::{Body, Constness, FnDecl, HirId};
55
use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintPass};
66
use rustc::{declare_lint_pass, declare_tool_lint};
77
use rustc_mir::transform::qualify_min_const_fn::is_min_const_fn;
8+
use rustc_typeck::hir_ty_to_ty;
89
use syntax_pos::Span;
910

1011
declare_clippy_lint! {
@@ -94,6 +95,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingConstForFn {
9495
}
9596
},
9697
FnKind::Method(_, sig, ..) => {
98+
// Don't lint if `Self` implements drop
99+
let input_tys = &sig.decl.inputs;
100+
if input_tys.len() > 0 {
101+
let hir_ty = &input_tys[0];
102+
let ty_ty = hir_ty_to_ty(cx.tcx, hir_ty);
103+
if is_self_ty(hir_ty) && has_drop(cx, ty_ty) {
104+
return;
105+
}
106+
}
97107
if trait_ref_of_method(cx, hir_id).is_some() || already_const(sig.header) {
98108
return;
99109
}

tests/ui/missing_const_for_fn/cant_be_const.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,16 @@ impl std::ops::Add for Point {
6868
Point(self.0 + other.0, self.1 + other.1)
6969
}
7070
}
71+
72+
pub struct A;
73+
impl A {
74+
// This should not be const because the type implements `Drop`.
75+
pub fn a(self) -> B {
76+
B
77+
}
78+
}
79+
impl Drop for A {
80+
fn drop(&mut self) {}
81+
}
82+
83+
pub struct B;

0 commit comments

Comments
 (0)