Auto merge of #10903 - Centri3:new_without_default, r=llogiq

[`new_without_default`]: Now emits on const fns

While `Default::default` is not const, it can still call `const new`; there's no reason this shouldn't be linted as well.

fixes #10877

changelog: [`new_without_default`]: Now emits on const fns
This commit is contained in:
bors 2024-02-16 07:55:05 +00:00
commit 61daf674ea
4 changed files with 28 additions and 9 deletions

View File

@ -75,10 +75,6 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind { if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind {
let name = impl_item.ident.name; let name = impl_item.ident.name;
let id = impl_item.owner_id; let id = impl_item.owner_id;
if sig.header.constness == hir::Constness::Const {
// can't be implemented by default
return;
}
if sig.header.unsafety == hir::Unsafety::Unsafe { if sig.header.unsafety == hir::Unsafety::Unsafe {
// can't be implemented for unsafe new // can't be implemented for unsafe new
return; return;

View File

@ -132,12 +132,18 @@ impl PrivateItem {
} // We don't lint private items on public structs } // We don't lint private items on public structs
} }
struct Const; pub struct Const;
impl Default for Const {
fn default() -> Self {
Self::new()
}
}
impl Const { impl Const {
pub const fn new() -> Const { pub const fn new() -> Const {
Const Const
} // const fns can't be implemented via Default } // While Default is not const, it can still call const functions, so we should lint this
} }
pub struct IgnoreGenericNew; pub struct IgnoreGenericNew;

View File

@ -114,12 +114,12 @@ fn new() -> PrivateItem {
} // We don't lint private items on public structs } // We don't lint private items on public structs
} }
struct Const; pub struct Const;
impl Const { impl Const {
pub const fn new() -> Const { pub const fn new() -> Const {
Const Const
} // const fns can't be implemented via Default } // While Default is not const, it can still call const functions, so we should lint this
} }
pub struct IgnoreGenericNew; pub struct IgnoreGenericNew;

View File

@ -55,6 +55,23 @@ LL + }
LL + } LL + }
| |
error: you should consider adding a `Default` implementation for `Const`
--> $DIR/new_without_default.rs:120:5
|
LL | / pub const fn new() -> Const {
LL | | Const
LL | | } // While Default is not const, it can still call const functions, so we should lint this
| |_____^
|
help: try adding this
|
LL + impl Default for Const {
LL + fn default() -> Self {
LL + Self::new()
LL + }
LL + }
|
error: you should consider adding a `Default` implementation for `NewNotEqualToDerive` error: you should consider adding a `Default` implementation for `NewNotEqualToDerive`
--> $DIR/new_without_default.rs:180:5 --> $DIR/new_without_default.rs:180:5
| |
@ -149,5 +166,5 @@ LL + }
LL + } LL + }
| |
error: aborting due to 8 previous errors error: aborting due to 9 previous errors