Fix missing_const_for_fn for impl trait methods

This commit is contained in:
Philipp Hansch 2019-03-05 08:11:55 +01:00
parent b87f5bc55a
commit 15cba2e956
No known key found for this signature in database
GPG Key ID: B6FA06A6E0E2665B
2 changed files with 23 additions and 1 deletions

View File

@ -1,4 +1,5 @@
use crate::utils::{is_entrypoint_fn, span_lint};
use if_chain::if_chain;
use rustc::hir;
use rustc::hir::intravisit::FnKind;
use rustc::hir::{Body, Constness, FnDecl, HirId};
@ -95,7 +96,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingConstForFn {
}
},
FnKind::Method(_, sig, ..) => {
if already_const(sig.header) {
if is_trait_method(cx, hir_id) || already_const(sig.header) {
return;
}
},
@ -114,6 +115,18 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingConstForFn {
}
}
fn is_trait_method(cx: &LateContext<'_, '_>, hir_id: HirId) -> bool {
// Get the implemented trait for the current function
let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
if_chain! {
if parent_impl != hir::CRATE_HIR_ID;
if let hir::Node::Item(item) = cx.tcx.hir().get_by_hir_id(parent_impl);
if let hir::ItemKind::Impl(_, _, _, _, Some(_trait_ref), _, _) = &item.node;
then { return true; }
}
false
}
// We don't have to lint on something that's already `const`
fn already_const(header: hir::FnHeader) -> bool {
header.constness == Constness::Const

View File

@ -59,3 +59,12 @@ trait Foo {
// Don't lint in external macros (derive)
#[derive(PartialEq, Eq)]
struct Point(isize, isize);
impl std::ops::Add for Point {
type Output = Self;
// Don't lint in trait impls of derived methods
fn add(self, other: Self) -> Self {
Point(self.0 + other.0, self.1 + other.1)
}
}