Remove brackets around type name when it is no longer a prefix

When `<T>::default()` is replaced by `T` when `T` is a singleton,
the brackets around the type name can be removed.
This commit is contained in:
Samuel Tardieu 2025-03-06 23:08:15 +01:00
parent 253ecb9d7d
commit 0aa0d074cd
4 changed files with 37 additions and 10 deletions

View file

@ -1,6 +1,6 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::is_ty_alias;
use clippy_utils::sugg::DiagExt as _;
use clippy_utils::source::SpanRangeExt as _;
use hir::ExprKind;
use hir::def::Res;
use rustc_errors::Applicability;
@ -74,16 +74,20 @@ impl LateLintPass<'_> for DefaultConstructedUnitStructs {
// do not suggest replacing an expression by a type name with placeholders
&& !base.is_suggestable_infer_ty()
{
let mut removals = vec![(expr.span.with_lo(qpath.qself_span().hi()), String::new())];
if expr.span.with_source_text(cx, |s| s.starts_with('<')) == Some(true) {
// Remove `<`, '>` has already been removed by the existing removal expression.
removals.push((expr.span.with_hi(qpath.qself_span().lo()), String::new()));
}
span_lint_and_then(
cx,
DEFAULT_CONSTRUCTED_UNIT_STRUCTS,
expr.span,
"use of `default` to create a unit struct",
|diag| {
diag.suggest_remove_item(
cx,
expr.span.with_lo(qpath.qself_span().hi()),
diag.multipart_suggestion(
"remove this call to `default`",
removals,
Applicability::MachineApplicable,
);
},

View file

@ -8,7 +8,8 @@ struct UnitStruct;
impl UnitStruct {
fn new() -> Self {
//should lint
Self//~^ default_constructed_unit_structs
Self
//~^ default_constructed_unit_structs
}
}
@ -168,4 +169,9 @@ fn issue12654() {
fn f(_g: G) {}
f(<_>::default());
f(G);
//~^ default_constructed_unit_structs
// No lint because `as Default` hides the singleton
f(<G as Default>::default());
}

View file

@ -169,4 +169,9 @@ fn issue12654() {
fn f(_g: G) {}
f(<_>::default());
f(<G>::default());
//~^ default_constructed_unit_structs
// No lint because `as Default` hides the singleton
f(<G as Default>::default());
}

View file

@ -1,10 +1,10 @@
error: use of `default` to create a unit struct
--> tests/ui/default_constructed_unit_structs.rs:11:9
|
LL | Self::default()
| _________^^^^-^^^^^^^^^^
LL | |
| |________- help: remove this call to `default`
LL | Self::default()
| ^^^^-----------
| |
| help: remove this call to `default`
|
= note: `-D clippy::default-constructed-unit-structs` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::default_constructed_unit_structs)]`
@ -49,5 +49,17 @@ LL | let _ = UnitStruct::default();
| |
| help: remove this call to `default`
error: aborting due to 6 previous errors
error: use of `default` to create a unit struct
--> tests/ui/default_constructed_unit_structs.rs:172:7
|
LL | f(<G>::default());
| ^^^^^^^^^^^^^^
|
help: remove this call to `default`
|
LL - f(<G>::default());
LL + f(G);
|
error: aborting due to 7 previous errors