diff --git a/clippy_lints/src/methods/mod.rs b/clippy_lints/src/methods/mod.rs index dc468e072e5..cc22d3b9865 100644 --- a/clippy_lints/src/methods/mod.rs +++ b/clippy_lints/src/methods/mod.rs @@ -2800,7 +2800,10 @@ impl SelfKind { hir::Mutability::MutMutable => &paths::ASMUT_TRAIT, }; - let trait_def_id = get_trait_def_id(cx, trait_path).expect("trait def id not found"); + let trait_def_id = match get_trait_def_id(cx, trait_path) { + Some(did) => did, + None => return false, + }; implements_trait(cx, ty, trait_def_id, &[parent_ty.into()]) } diff --git a/clippy_lints/src/utils/mod.rs b/clippy_lints/src/utils/mod.rs index 2d772d77ed1..408deb1b402 100644 --- a/clippy_lints/src/utils/mod.rs +++ b/clippy_lints/src/utils/mod.rs @@ -261,6 +261,7 @@ pub fn path_to_res(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<(def::Res) } /// Convenience function to get the `DefId` of a trait by path. +/// It could be a trait or trait alias. pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option { let res = match path_to_res(cx, path) { Some(res) => res, @@ -268,7 +269,8 @@ pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option Some(trait_id), + Res::Def(DefKind::Trait, trait_id) | Res::Def(DefKind::TraitAlias, trait_id) => Some(trait_id), + Res::Err => unreachable!("this trait resolution is impossible: {:?}", &path), _ => None, } } diff --git a/tests/ui/def_id_nocore.rs b/tests/ui/def_id_nocore.rs new file mode 100644 index 00000000000..2a948d60b10 --- /dev/null +++ b/tests/ui/def_id_nocore.rs @@ -0,0 +1,29 @@ +// ignore-windows +// ignore-macos + +#![feature(no_core, lang_items, start)] +#![no_core] + +#[link(name = "c")] +extern "C" {} + +#[lang = "sized"] +pub trait Sized {} +#[lang = "copy"] +pub trait Copy {} +#[lang = "freeze"] +pub unsafe trait Freeze {} + +#[lang = "start"] +#[start] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + 0 +} + +pub struct A; + +impl A { + pub fn as_ref(self) -> &'static str { + "A" + } +} diff --git a/tests/ui/def_id_nocore.stderr b/tests/ui/def_id_nocore.stderr new file mode 100644 index 00000000000..ed87a50547d --- /dev/null +++ b/tests/ui/def_id_nocore.stderr @@ -0,0 +1,10 @@ +error: methods called `as_*` usually take self by reference or self by mutable reference; consider choosing a less ambiguous name + --> $DIR/def_id_nocore.rs:26:19 + | +LL | pub fn as_ref(self) -> &'static str { + | ^^^^ + | + = note: `-D clippy::wrong-self-convention` implied by `-D warnings` + +error: aborting due to previous error +