Skip to content

Fix unit_arg suggests wrongly for Default::default #14881

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

Open
wants to merge 3 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 2 additions & 16 deletions clippy_lints/src/default.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_sugg};
use clippy_utils::source::snippet_with_context;
use clippy_utils::ty::{has_drop, is_copy};
use clippy_utils::{contains_name, get_parent_expr, in_automatically_derived, is_from_proc_macro};
use clippy_utils::{contains_name, get_parent_expr, in_automatically_derived, is_expr_default, is_from_proc_macro};
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::Applicability;
use rustc_hir::def::Res;
use rustc_hir::{Block, Expr, ExprKind, PatKind, QPath, Stmt, StmtKind, StructTailExpr};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
Expand Down Expand Up @@ -129,7 +128,7 @@ impl<'tcx> LateLintPass<'tcx> for Default {
// only take bindings to identifiers
&& let PatKind::Binding(_, binding_id, ident, _) = local.pat.kind
// only when assigning `... = Default::default()`
&& is_expr_default(expr, cx)
&& is_expr_default(cx, expr)
&& let binding_type = cx.typeck_results().node_type(binding_id)
&& let ty::Adt(adt, args) = *binding_type.kind()
&& adt.is_struct()
Expand Down Expand Up @@ -251,19 +250,6 @@ impl<'tcx> LateLintPass<'tcx> for Default {
}
}

/// Checks if the given expression is the `default` method belonging to the `Default` trait.
fn is_expr_default<'tcx>(expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> bool {
if let ExprKind::Call(fn_expr, []) = &expr.kind
&& let ExprKind::Path(qpath) = &fn_expr.kind
&& let Res::Def(_, def_id) = cx.qpath_res(qpath, fn_expr.hir_id)
{
// right hand side of assignment is `Default::default`
cx.tcx.is_diagnostic_item(sym::default_fn, def_id)
} else {
false
}
}

/// Returns the reassigned field and the assigning expression (right-hand side of assign).
fn field_reassigned_by_stmt<'tcx>(this: &Stmt<'tcx>, binding_name: Symbol) -> Option<(Ident, &'tcx Expr<'tcx>)> {
if let StmtKind::Semi(later_expr) = this.kind
Expand Down
124 changes: 91 additions & 33 deletions clippy_lints/src/unit_types/unit_arg.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
use std::iter;

use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::is_from_proc_macro;
use clippy_utils::source::{SourceText, SpanRangeExt, indent_of, reindent_multiline};
use clippy_utils::source::{SpanRangeExt, indent_of, reindent_multiline};
use clippy_utils::sugg::Sugg;
use clippy_utils::ty::expr_type_is_certain;
use clippy_utils::{is_expr_default, is_from_proc_macro};
use rustc_errors::Applicability;
use rustc_hir::{Block, Expr, ExprKind, MatchSource, Node, StmtKind};
use rustc_lint::LateContext;
use rustc_span::SyntaxContext;

use super::{UNIT_ARG, utils};

Expand Down Expand Up @@ -59,7 +64,7 @@ fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
}
}

fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) {
fn lint_unit_args<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, args_to_recover: &[&'tcx Expr<'tcx>]) {
let mut applicability = Applicability::MachineApplicable;
let (singular, plural) = if args_to_recover.len() > 1 {
("", "s")
Expand Down Expand Up @@ -100,34 +105,41 @@ fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Exp

let arg_snippets: Vec<_> = args_to_recover
.iter()
.filter_map(|arg| arg.span.get_source_text(cx))
// If the argument is from an expansion and is a `Default::default()`, we skip it
.filter(|arg| !arg.span.from_expansion() || !is_expr_default_nested(cx, arg))
.filter_map(|arg| get_expr_snippet(cx, arg))
.collect();
let arg_snippets_without_empty_blocks: Vec<_> = args_to_recover

// If the argument is an empty block or `Default::default()`, we can replace it with `()`.
let arg_snippets_without_redundant_exprs: Vec<_> = args_to_recover
.iter()
.filter(|arg| !is_empty_block(arg))
.filter_map(|arg| arg.span.get_source_text(cx))
.filter(|arg| !is_expr_default_nested(cx, arg) && (arg.span.from_expansion() || !is_empty_block(arg)))
.filter_map(|arg| get_expr_snippet_with_type_certainty(cx, arg))
.collect();

if let Some(call_snippet) = expr.span.get_source_text(cx) {
let sugg = fmt_stmts_and_call(
cx,
expr,
&call_snippet,
&arg_snippets,
&arg_snippets_without_empty_blocks,
);

if arg_snippets_without_empty_blocks.is_empty() {
if arg_snippets_without_redundant_exprs.is_empty()
&& let suggestions = args_to_recover
.iter()
.filter(|arg| !arg.span.from_expansion() || !is_expr_default_nested(cx, arg))
.map(|arg| (arg.span.parent_callsite().unwrap_or(arg.span), "()".to_string()))
.collect::<Vec<_>>()
&& !suggestions.is_empty()
{
db.multipart_suggestion(
format!("use {singular}unit literal{plural} instead"),
args_to_recover
.iter()
.map(|arg| (arg.span, "()".to_string()))
.collect::<Vec<_>>(),
suggestions,
applicability,
);
} else {
let plural = arg_snippets_without_empty_blocks.len() > 1;
let plural = arg_snippets_without_redundant_exprs.len() > 1;
let sugg = fmt_stmts_and_call(
cx,
expr,
&call_snippet,
arg_snippets,
arg_snippets_without_redundant_exprs,
);
let empty_or_s = if plural { "s" } else { "" };
let it_or_them = if plural { "them" } else { "it" };
db.span_suggestion(
Expand All @@ -144,6 +156,55 @@ fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Exp
);
}

fn is_expr_default_nested<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
is_expr_default(cx, expr)
|| matches!(expr.kind, ExprKind::Block(block, _)
if block.expr.is_some() && is_expr_default_nested(cx, block.expr.unwrap()))
}

enum MaybeTypeUncertain<'tcx> {
Certain(Sugg<'tcx>),
Uncertain(Sugg<'tcx>),
}

impl From<MaybeTypeUncertain<'_>> for String {
fn from(value: MaybeTypeUncertain<'_>) -> Self {
match value {
MaybeTypeUncertain::Certain(sugg) => sugg.to_string(),
MaybeTypeUncertain::Uncertain(sugg) => format!("let _: () = {sugg}"),
}
}
}

fn get_expr_snippet<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<Sugg<'tcx>> {
let mut app = Applicability::MachineApplicable;
let snip = Sugg::hir_with_context(cx, expr, SyntaxContext::root(), "..", &mut app);
if app != Applicability::MachineApplicable {
return None;
}

Some(snip)
}

fn get_expr_snippet_with_type_certainty<'tcx>(
cx: &LateContext<'tcx>,
expr: &'tcx Expr<'tcx>,
) -> Option<MaybeTypeUncertain<'tcx>> {
get_expr_snippet(cx, expr).map(|snip| {
// If the type of the expression is certain, we can use it directly.
// Otherwise, we wrap it in a `let _: () = ...` to ensure the type is correct.
if !expr_type_is_certain(cx, expr) && !is_block_with_no_expr(expr) {
MaybeTypeUncertain::Uncertain(snip)
} else {
MaybeTypeUncertain::Certain(snip)
}
})
}

fn is_block_with_no_expr(expr: &Expr<'_>) -> bool {
matches!(expr.kind, ExprKind::Block(Block { expr: None, .. }, _))
}

fn is_empty_block(expr: &Expr<'_>) -> bool {
matches!(
expr.kind,
Expand All @@ -162,23 +223,20 @@ fn fmt_stmts_and_call(
cx: &LateContext<'_>,
call_expr: &Expr<'_>,
call_snippet: &str,
args_snippets: &[SourceText],
non_empty_block_args_snippets: &[SourceText],
args_snippets: Vec<Sugg<'_>>,
non_empty_block_args_snippets: Vec<MaybeTypeUncertain<'_>>,
) -> String {
let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0);
let call_snippet_with_replacements = args_snippets
.iter()
.fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1));
let call_snippet_with_replacements = args_snippets.into_iter().fold(call_snippet.to_owned(), |acc, arg| {
acc.replacen(&arg.to_string(), "()", 1)
});

let mut stmts_and_call = non_empty_block_args_snippets
.iter()
.map(|it| it.as_ref().to_owned())
.collect::<Vec<_>>();
stmts_and_call.push(call_snippet_with_replacements);
stmts_and_call = stmts_and_call
let stmts_and_call = non_empty_block_args_snippets
.into_iter()
.map(Into::into)
.chain(iter::once(call_snippet_with_replacements))
.map(|v| reindent_multiline(&v, true, Some(call_expr_indent)))
.collect();
.collect::<Vec<_>>();

let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
// expr is not in a block statement or result expression position, wrap in a block
Expand Down
12 changes: 12 additions & 0 deletions clippy_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3471,3 +3471,15 @@ pub fn desugar_await<'tcx>(expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
None
}
}

/// Checks if the given expression is a call to `Default::default()`.
pub fn is_expr_default<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
if let ExprKind::Call(fn_expr, []) = &expr.kind
&& let ExprKind::Path(qpath) = &fn_expr.kind
&& let Res::Def(_, def_id) = cx.qpath_res(qpath, fn_expr.hir_id)
{
cx.tcx.is_diagnostic_item(sym::default_fn, def_id)
} else {
false
}
}
24 changes: 24 additions & 0 deletions tests/ui/unit_arg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,27 @@ fn main() {
bad();
ok();
}

fn issue14857() {
let fn_take_unit = |_: ()| {};
fn some_other_fn(_: &i32) {}

macro_rules! mac {
(def) => {
Default::default()
};
(func $f:expr) => {
$f()
};
(nonempty_block $e:expr) => {{
some_other_fn(&$e);
$e
}};
}
fn_take_unit(mac!(def));
//~^ unit_arg
fn_take_unit(mac!(func Default::default));
//~^ unit_arg
fn_take_unit(mac!(nonempty_block Default::default()));
//~^ unit_arg
}
23 changes: 22 additions & 1 deletion tests/ui/unit_arg.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -199,5 +199,26 @@ LL ~ foo(1);
LL + Some(())
|

error: aborting due to 10 previous errors
error: passing a unit value to a function
--> tests/ui/unit_arg.rs:171:5
|
LL | fn_take_unit(mac!(def));
| ^^^^^^^^^^^^^^^^^^^^^^^
|

error: passing a unit value to a function
--> tests/ui/unit_arg.rs:173:5
|
LL | fn_take_unit(mac!(func Default::default));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|

error: passing a unit value to a function
--> tests/ui/unit_arg.rs:175:5
|
LL | fn_take_unit(mac!(nonempty_block Default::default()));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|

error: aborting due to 13 previous errors

34 changes: 0 additions & 34 deletions tests/ui/unit_arg_empty_blocks.fixed

This file was deleted.

31 changes: 0 additions & 31 deletions tests/ui/unit_arg_empty_blocks.rs

This file was deleted.

Loading