Ignore expressions from macros in default_constructed_unit_structs

This commit is contained in:
Alex Macleod 2023-05-05 18:30:41 +00:00
parent 371120bdbf
commit 68eb864c91
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 @@ fn check_expr<'tcx>(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tc
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