Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add lint for recreation of an entire struct #12772

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
107 changes: 107 additions & 0 deletions clippy_lints/src/redundant_owned_struct_recreation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use std::fmt::{self, Write as _};

declare_clippy_lint! {
/// ### What it does
/// Checks for struct literals that recreate a struct we already have an owned
/// version of.
///
/// ### Why is this bad?
/// This is essentially a no-op as all members are being moved into the new
/// struct and the old one becomes inaccessible.
///
/// ### Example
/// ```no_run
/// fn redundant () {
/// struct Foo { a: i32, b: String }
///
/// let foo = Foo { a: 42, b: "Hello, Foo!".into() };
///
/// let bar = Foo { a: foo.a, b: foo.b };
///
/// println!("redundant: bar = Foo {{ a: {}, b: \"{}\" }}", bar.a, bar.b);
/// }
/// ```
///
/// The struct literal in the assignment to ``bar`` could be replaced with
/// ``let bar = foo``.
///
/// Empty structs are ignored by the lint.
#[clippy::version = "pre 1.29.0"]
pub REDUNDANT_OWNED_STRUCT_RECREATION,
//pedantic,
correctness,
"recreation of owned structs from identical parts"
}

declare_lint_pass!(RedundantOwnedStructRecreation => [REDUNDANT_OWNED_STRUCT_RECREATION]);

impl<'tcx> LateLintPass<'tcx> for RedundantOwnedStructRecreation {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
if !expr.span.from_expansion()
&& let ExprKind::Struct(qpath, fields, base) = expr.kind
{
let ty = cx.typeck_results().expr_ty(expr);

// Conditions that must be satisfied to trigger the lint:
// - source of the assignment must be a struct
// - type of struct in expr must match
// - names of assignee struct fields (lhs) must match the names of the assigned on (rhs)
// - all fields musts be assigned (no Default)

if base.is_some() {
// one or more fields assigned from `..Default`
return;
}

let matching = fields.iter().filter(|f| !f.is_shorthand).try_fold(
None,
|seen_path, f| -> Result<Option<&'tcx Path<'tcx>>, ()> {
// fields are assigned from expression
if let ExprKind::Field(expr, ident) = f.expr.kind
// expression type matches
&& ty == cx.typeck_results().expr_ty(expr)
// field name matches
&& f.ident == ident
&& let ExprKind::Path(QPath::Resolved(None, path)) = expr.kind
{
match seen_path {
None => {
// first field assignment
Ok(Some(path))
},
Some(p) if p.res == path.res => {
// subsequent field assignment, same origin struct as before
Ok(seen_path)
},
Some(_) => {
// subsequent field assignment, different origin struct as before
Err(())
},
}
} else {
// source of field assignment not an expression
Err(())
}
},
);

let Ok(Some(path)) = matching else { return };

let sugg = format!("{}", snippet(cx, path.span, ".."),);

span_lint_and_sugg(
cx,
REDUNDANT_OWNED_STRUCT_RECREATION,
expr.span,
"recreation of owned struct from identical parts",
"try replacing it with",
sugg,
// the lint may be incomplete due to partial moves
// of struct fields
Applicability::MaybeIncorrect,
);
}
}
}
188 changes: 152 additions & 36 deletions clippy_lints/src/unnecessary_struct_initialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet;
use clippy_utils::ty::is_copy;
use clippy_utils::{get_parent_expr, path_to_local};
use rustc_hir::{BindingMode, Expr, ExprKind, Node, PatKind, UnOp};
use rustc_hir::{BindingMode, Expr, ExprField, ExprKind, Node, PatKind, Path, QPath, UnOp};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;

declare_clippy_lint! {
/// ### What it does
/// Checks for initialization of a `struct` by copying a base without setting
/// any field.
/// Checks for initialization of an identical `struct` from another instance
/// of the type, either by copying a base without setting any field or by
/// moving all fields individually.
///
/// ### Why is this bad?
/// Readability suffers from unnecessary struct building.
Expand All @@ -29,9 +30,14 @@ declare_clippy_lint! {
/// let b = a;
/// ```
///
/// The struct literal ``S { ..a }`` in the assignment to ``b`` could be replaced
/// with just ``a``.
///
/// ### Known Problems
/// Has false positives when the base is a place expression that cannot be
/// moved out of, see [#10547](https://github.com/rust-lang/rust-clippy/issues/10547).
///
/// Empty structs are ignored by the lint.
#[clippy::version = "1.70.0"]
pub UNNECESSARY_STRUCT_INITIALIZATION,
nursery,
Expand All @@ -41,43 +47,113 @@ declare_lint_pass!(UnnecessaryStruct => [UNNECESSARY_STRUCT_INITIALIZATION]);

impl LateLintPass<'_> for UnnecessaryStruct {
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
if let ExprKind::Struct(_, &[], Some(base)) = expr.kind {
if let Some(parent) = get_parent_expr(cx, expr)
&& let parent_ty = cx.typeck_results().expr_ty_adjusted(parent)
&& parent_ty.is_any_ptr()
{
if is_copy(cx, cx.typeck_results().expr_ty(expr)) && path_to_local(base).is_some() {
// When the type implements `Copy`, a reference to the new struct works on the
// copy. Using the original would borrow it.
return;
}

if parent_ty.is_mutable_ptr() && !is_mutable(cx, base) {
// The original can be used in a mutable reference context only if it is mutable.
return;
}
}
let ExprKind::Struct(_, fields, base) = expr.kind else {
return;
};

// TODO: do not propose to replace *XX if XX is not Copy
if let ExprKind::Unary(UnOp::Deref, target) = base.kind
&& matches!(target.kind, ExprKind::Path(..))
&& !is_copy(cx, cx.typeck_results().expr_ty(expr))
{
// `*base` cannot be used instead of the struct in the general case if it is not Copy.
return;
}
if expr.span.from_expansion() {
// Prevent lint from hitting inside macro code
return;
}

// Conditions that must be satisfied to trigger this variant of the lint:
// - source of the assignment must be a struct
// - type of struct in expr must match
// - of destination struct fields must match the names of the source
// - all fields musts be assigned (no Default)

let field_path = same_path_in_all_fields(cx, expr, fields);

let sugg = match (field_path, base) {
(Some(&path), None) => {
// all fields match, no base given
path.span
},
/*
(Some(&path), Some(&Expr{ kind: ExprKind::Struct(&base_path, _, _), .. }))
//if ExprKind::Path(base_path) == path => {
if base_path == path => {
// all fields match, has base: ensure that the path of the base matches
path.span
},
*/
(Some(path), Some(base)) if base_is_suitable(cx, expr, base) && path_matches_base(path, base) => {
eprintln!("[phg] »»» path: {:?}", path);
eprintln!("[phg] »»» base: {:?}", base);

// all fields match, has base: ensure that the path of the base matches
base.span
},
(None, Some(base)) if fields.is_empty() && base_is_suitable(cx, expr, base) => {
// just the base, no explicit fields

base.span
},
_ => return,
};

span_lint_and_sugg(
cx,
UNNECESSARY_STRUCT_INITIALIZATION,
expr.span,
"unnecessary struct building",
"replace with",
snippet(cx, sugg, "..").into_owned(),
rustc_errors::Applicability::MachineApplicable,
);
}
}

fn base_is_suitable(cx: &LateContext<'_>, expr: &Expr<'_>, base: &Expr<'_>) -> bool {
if !mutability_matches(cx, expr, base) {
return false;
}
// TODO: do not propose to replace *XX if XX is not Copy
if let ExprKind::Unary(UnOp::Deref, target) = base.kind
&& matches!(target.kind, ExprKind::Path(..))
&& !is_copy(cx, cx.typeck_results().expr_ty(expr))
{
// `*base` cannot be used instead of the struct in the general case if it is not Copy.
return false;
}
true
}

fn same_path_in_all_fields<'tcx>(
cx: &LateContext<'_>,
expr: &Expr<'_>,
fields: &[ExprField<'tcx>],
) -> Option<&'tcx Path<'tcx>> {
let ty = cx.typeck_results().expr_ty(expr);

let mut seen_path = None;

span_lint_and_sugg(
cx,
UNNECESSARY_STRUCT_INITIALIZATION,
expr.span,
"unnecessary struct building",
"replace with",
snippet(cx, base.span, "..").into_owned(),
rustc_errors::Applicability::MachineApplicable,
);
for f in fields.iter().filter(|f| !f.is_shorthand) {
// fields are assigned from expression
if let ExprKind::Field(expr, ident) = f.expr.kind
// expression type matches
&& ty == cx.typeck_results().expr_ty(expr)
// field name matches
&& f.ident == ident
// assigned from a path expression
&& let ExprKind::Path(QPath::Resolved(None, path)) = expr.kind
{
let Some(p) = seen_path else {
// this is the first field assignment in the list
seen_path = Some(path);
continue;
};

if p.res == path.res {
// subsequent field assignment with same origin struct as before
continue;
}
}
// source of field assignment doesn’t qualify
return None;
}

seen_path
}

fn is_mutable(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
Expand All @@ -89,3 +165,43 @@ fn is_mutable(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
true
}
}

fn mutability_matches(cx: &LateContext<'_>, expr_a: &Expr<'_>, expr_b: &Expr<'_>) -> bool {
if let Some(parent) = get_parent_expr(cx, expr_a)
&& let parent_ty = cx.typeck_results().expr_ty_adjusted(parent)
&& parent_ty.is_any_ptr()
{
if is_copy(cx, cx.typeck_results().expr_ty(expr_a)) && path_to_local(expr_b).is_some() {
// When the type implements `Copy`, a reference to the new struct works on the
// copy. Using the original would borrow it.
return false;
}

if parent_ty.is_mutable_ptr() && !is_mutable(cx, expr_b) {
// The original can be used in a mutable reference context only if it is mutable.
return false;
}
}

true
}

/// When some fields are assigned from a base struct and others individually
/// the lint applies only if the source of the field is the same as the base.
/// This is enforced here by comparing the path of the base expression;
/// needless to say the link only applies if it (or whatever expression it is
/// a reference of) actually has a path.
fn path_matches_base(path: &Path<'_>, base: &Expr<'_>) -> bool {
let base_path = match base.kind {
ExprKind::Unary(UnOp::Deref, base_expr) => {
if let ExprKind::Path(QPath::Resolved(_, base_path)) = base_expr.kind {
base_path
} else {
return false;
}
},
ExprKind::Path(QPath::Resolved(_, base_path)) => base_path,
_ => return false,
};
path.res == base_path.res
}
16 changes: 16 additions & 0 deletions tests/ui/unnecessary_struct_initialization.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ struct V {
f: u32,
}

struct W {
f1: u32,
f2: u32,
}

impl Clone for V {
fn clone(&self) -> Self {
// Lint: `Self` implements `Copy`
Expand Down Expand Up @@ -68,4 +73,15 @@ fn main() {

// Should lint: the result of an expression is mutable and temporary
let p = &mut *Box::new(T { f: 5 });

// Should lint: all fields of `q` would be consumed anyway
let q = W { f1: 42, f2: 1337 };
let r = q;

// Should not lint: not all fields of `t` from same source
let s = W { f1: 1337, f2: 42 };
let t = W { f1: s.f1, f2: r.f2 };

// Should not lint: different fields of `s` assigned
let u = W { f1: s.f2, f2: s.f1 };
}