Auto merge of #10752 - Alexendoo:default-units-macros, r=giraffate

Ignore expressions from macros in `default_constructed_unit_structs`

changelog: none, should be the same release as the lint itself
This commit is contained in:
bors 2023-05-08 00:21:43 +00:00
commit 3aab0ddc43
4 changed files with 47 additions and 4 deletions

View File

@ -1,4 +1,4 @@
use clippy_utils::{diagnostics::span_lint_and_sugg, is_from_proc_macro, match_def_path, paths};
use clippy_utils::{diagnostics::span_lint_and_sugg, match_def_path, paths};
use hir::{def::Res, ExprKind};
use rustc_errors::Applicability;
use rustc_hir as hir;
@ -55,7 +55,8 @@ impl LateLintPass<'_> for DefaultConstructedUnitStructs {
if let ty::Adt(def, ..) = cx.typeck_results().expr_ty(expr).kind();
if def.is_struct();
if let var @ ty::VariantDef { ctor: Some((hir::def::CtorKind::Const, _)), .. } = def.non_enum_variant();
if !var.is_field_list_non_exhaustive() && !is_from_proc_macro(cx, expr);
if !var.is_field_list_non_exhaustive();
if !expr.span.from_expansion() && !qpath.span().from_expansion();
then {
span_lint_and_sugg(
cx,

View File

@ -105,6 +105,7 @@ fn main() {
// should lint
let _ = PhantomData::<usize>;
let _: PhantomData<i32> = PhantomData;
let _: PhantomData<i32> = std::marker::PhantomData;
let _ = UnitStruct;
// should not lint
@ -116,4 +117,21 @@ fn main() {
let _ = EmptyStruct::default();
let _ = FakeDefault::default();
let _ = <FakeDefault as Default>::default();
macro_rules! in_macro {
($i:ident) => {{
let _ = UnitStruct::default();
let _ = $i::default();
}};
}
in_macro!(UnitStruct);
macro_rules! struct_from_macro {
() => {
UnitStruct
};
}
let _ = <struct_from_macro!()>::default();
}

View File

@ -105,6 +105,7 @@ fn main() {
// should lint
let _ = PhantomData::<usize>::default();
let _: PhantomData<i32> = PhantomData::default();
let _: PhantomData<i32> = std::marker::PhantomData::default();
let _ = UnitStruct::default();
// should not lint
@ -116,4 +117,21 @@ fn main() {
let _ = EmptyStruct::default();
let _ = FakeDefault::default();
let _ = <FakeDefault as Default>::default();
macro_rules! in_macro {
($i:ident) => {{
let _ = UnitStruct::default();
let _ = $i::default();
}};
}
in_macro!(UnitStruct);
macro_rules! struct_from_macro {
() => {
UnitStruct
};
}
let _ = <struct_from_macro!()>::default();
}

View File

@ -25,10 +25,16 @@ LL | let _: PhantomData<i32> = PhantomData::default();
| ^^^^^^^^^^^ help: remove this call to `default`
error: use of `default` to create a unit struct
--> $DIR/default_constructed_unit_structs.rs:108:23
--> $DIR/default_constructed_unit_structs.rs:108:55
|
LL | let _: PhantomData<i32> = std::marker::PhantomData::default();
| ^^^^^^^^^^^ help: remove this call to `default`
error: use of `default` to create a unit struct
--> $DIR/default_constructed_unit_structs.rs:109:23
|
LL | let _ = UnitStruct::default();
| ^^^^^^^^^^^ help: remove this call to `default`
error: aborting due to 5 previous errors
error: aborting due to 6 previous errors