Skip to content

Commit b220ddf

Browse files
committed
unit-arg - pr remarks
1 parent b1f0e01 commit b220ddf

File tree

2 files changed

+103
-75
lines changed

2 files changed

+103
-75
lines changed

clippy_lints/src/types.rs

+49-33
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ use crate::utils::paths;
3131
use crate::utils::{
3232
clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_type_diagnostic_item,
3333
last_path_segment, match_def_path, match_path, method_chain_args, multispan_sugg, numeric_literal::NumericLiteral,
34-
qpath_res, sext, snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite, span_lint,
35-
span_lint_and_help, span_lint_and_sugg, span_lint_and_then, trim_multiline, unsext,
34+
qpath_res, reindent_multiline, sext, snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite,
35+
span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext,
3636
};
3737

3838
declare_clippy_lint! {
@@ -802,7 +802,45 @@ impl<'tcx> LateLintPass<'tcx> for UnitArg {
802802
}
803803
}
804804

805-
#[allow(clippy::too_many_lines)]
805+
fn fmt_stmts_and_call(
806+
cx: &LateContext<'_>,
807+
call_expr: &Expr<'_>,
808+
call_snippet: &str,
809+
args_snippets: &[impl AsRef<str>],
810+
non_empty_block_args_snippets: &[impl AsRef<str>],
811+
) -> String {
812+
let call_expr_indent = indent_of(cx, call_expr.span).unwrap_or(0);
813+
let call_snippet_with_replacements = args_snippets
814+
.iter()
815+
.fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1));
816+
817+
let mut stmts_and_call = non_empty_block_args_snippets
818+
.iter()
819+
.map(|it| it.as_ref().to_owned())
820+
.collect::<Vec<_>>();
821+
stmts_and_call.push(call_snippet_with_replacements);
822+
stmts_and_call = stmts_and_call
823+
.into_iter()
824+
.map(|v| reindent_multiline(v.into(), true, Some(call_expr_indent)).into_owned())
825+
.collect();
826+
827+
let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
828+
// expr is not in a block statement or result expression position, wrap in a block
829+
let parent_node = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(call_expr.hir_id));
830+
if !matches!(parent_node, Some(Node::Block(_))) && !matches!(parent_node, Some(Node::Stmt(_))) {
831+
let block_indent = call_expr_indent + 4;
832+
stmts_and_call_snippet =
833+
reindent_multiline(stmts_and_call_snippet.into(), true, Some(block_indent)).into_owned();
834+
stmts_and_call_snippet = format!(
835+
"{{\n{}{}\n{}}}",
836+
" ".repeat(block_indent),
837+
&stmts_and_call_snippet,
838+
" ".repeat(call_expr_indent)
839+
);
840+
}
841+
stmts_and_call_snippet
842+
}
843+
806844
fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) {
807845
let mut applicability = Applicability::MachineApplicable;
808846
let (singular, plural) = if args_to_recover.len() > 1 {
@@ -857,37 +895,15 @@ fn lint_unit_args(cx: &LateContext<'_>, expr: &Expr<'_>, args_to_recover: &[&Exp
857895
.filter(|arg| !is_empty_block(arg))
858896
.filter_map(|arg| snippet_opt(cx, arg.span))
859897
.collect();
860-
let indent = indent_of(cx, expr.span).unwrap_or(0);
861-
862-
if let Some(expr_str) = snippet_opt(cx, expr.span) {
863-
let expr_with_replacements = arg_snippets
864-
.iter()
865-
.fold(expr_str, |acc, arg| acc.replacen(arg, "()", 1));
866-
867-
// expr is not in a block statement or result expression position, wrap in a block
868-
let parent_node = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(expr.hir_id));
869-
let wrap_in_block =
870-
!matches!(parent_node, Some(Node::Block(_))) && !matches!(parent_node, Some(Node::Stmt(_)));
871-
872-
let stmts_indent = if wrap_in_block { indent + 4 } else { indent };
873-
let mut stmts_and_call = arg_snippets_without_empty_blocks.clone();
874-
stmts_and_call.push(expr_with_replacements);
875-
let mut stmts_and_call_str = stmts_and_call
876-
.into_iter()
877-
.enumerate()
878-
.map(|(i, v)| {
879-
let with_indent_prefix = if i > 0 { " ".repeat(stmts_indent) + &v } else { v };
880-
trim_multiline(with_indent_prefix.into(), true, Some(stmts_indent)).into_owned()
881-
})
882-
.collect::<Vec<String>>()
883-
.join(";\n");
884-
885-
if wrap_in_block {
886-
stmts_and_call_str = " ".repeat(stmts_indent) + &stmts_and_call_str;
887-
stmts_and_call_str = format!("{{\n{}\n{}}}", &stmts_and_call_str, " ".repeat(indent));
888-
}
889898

890-
let sugg = stmts_and_call_str;
899+
if let Some(call_snippet) = snippet_opt(cx, expr.span) {
900+
let sugg = fmt_stmts_and_call(
901+
cx,
902+
expr,
903+
&call_snippet,
904+
&arg_snippets,
905+
&arg_snippets_without_empty_blocks,
906+
);
891907

892908
if arg_snippets_without_empty_blocks.is_empty() {
893909
db.multipart_suggestion(

clippy_lints/src/utils/mod.rs

+54-42
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub mod paths;
1919
pub mod ptr;
2020
pub mod sugg;
2121
pub mod usage;
22+
2223
pub use self::attrs::*;
2324
pub use self::diagnostics::*;
2425
pub use self::hir_utils::{both, eq_expr_value, over, SpanlessEq, SpanlessHash};
@@ -108,6 +109,7 @@ pub fn in_macro(span: Span) -> bool {
108109
false
109110
}
110111
}
112+
111113
// If the snippet is empty, it's an attribute that was inserted during macro
112114
// expansion and we want to ignore those, because they could come from external
113115
// sources that the user has no control over.
@@ -571,7 +573,7 @@ pub fn snippet_block<'a, T: LintContext>(
571573
) -> Cow<'a, str> {
572574
let snip = snippet(cx, span, default);
573575
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
574-
trim_multiline(snip, true, indent)
576+
reindent_multiline(snip, true, indent)
575577
}
576578

577579
/// Same as `snippet_block`, but adapts the applicability level by the rules of
@@ -585,7 +587,7 @@ pub fn snippet_block_with_applicability<'a, T: LintContext>(
585587
) -> Cow<'a, str> {
586588
let snip = snippet_with_applicability(cx, span, default, applicability);
587589
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
588-
trim_multiline(snip, true, indent)
590+
reindent_multiline(snip, true, indent)
589591
}
590592

591593
/// Returns a new Span that extends the original Span to the first non-whitespace char of the first
@@ -661,16 +663,16 @@ pub fn expr_block<'a, T: LintContext>(
661663
}
662664
}
663665

664-
/// Trim indentation from a multiline string with possibility of ignoring the
665-
/// first line.
666-
pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
667-
let s_space = trim_multiline_inner(s, ignore_first, indent, ' ');
668-
let s_tab = trim_multiline_inner(s_space, ignore_first, indent, '\t');
669-
trim_multiline_inner(s_tab, ignore_first, indent, ' ')
666+
/// Reindent a multiline string with possibility of ignoring the first line.
667+
#[allow(clippy::needless_pass_by_value)]
668+
pub fn reindent_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
669+
let s_space = reindent_multiline_inner(&s, ignore_first, indent, ' ');
670+
let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
671+
reindent_multiline_inner(&s_tab, ignore_first, indent, ' ').into()
670672
}
671673

672-
fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>, ch: char) -> Cow<'_, str> {
673-
let mut x = s
674+
fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
675+
let x = s
674676
.lines()
675677
.skip(ignore_first as usize)
676678
.filter_map(|l| {
@@ -683,26 +685,20 @@ fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, indent: Option<usiz
683685
})
684686
.min()
685687
.unwrap_or(0);
686-
if let Some(indent) = indent {
687-
x = x.saturating_sub(indent);
688-
}
689-
if x > 0 {
690-
Cow::Owned(
691-
s.lines()
692-
.enumerate()
693-
.map(|(i, l)| {
694-
if (ignore_first && i == 0) || l.is_empty() {
695-
l
696-
} else {
697-
l.split_at(x).1
698-
}
699-
})
700-
.collect::<Vec<_>>()
701-
.join("\n"),
702-
)
703-
} else {
704-
s
705-
}
688+
let indent = indent.unwrap_or(0);
689+
s.lines()
690+
.enumerate()
691+
.map(|(i, l)| {
692+
if (ignore_first && i == 0) || l.is_empty() {
693+
l.to_owned()
694+
} else if x > indent {
695+
l.split_at(x - indent).1.to_owned()
696+
} else {
697+
" ".repeat(indent - x) + l
698+
}
699+
})
700+
.collect::<Vec<String>>()
701+
.join("\n")
706702
}
707703

708704
/// Gets the parent expression, if any –- this is useful to constrain a lint.
@@ -1475,26 +1471,26 @@ macro_rules! unwrap_cargo_metadata {
14751471

14761472
#[cfg(test)]
14771473
mod test {
1478-
use super::{trim_multiline, without_block_comments};
1474+
use super::{reindent_multiline, without_block_comments};
14791475

14801476
#[test]
1481-
fn test_trim_multiline_single_line() {
1482-
assert_eq!("", trim_multiline("".into(), false, None));
1483-
assert_eq!("...", trim_multiline("...".into(), false, None));
1484-
assert_eq!("...", trim_multiline(" ...".into(), false, None));
1485-
assert_eq!("...", trim_multiline("\t...".into(), false, None));
1486-
assert_eq!("...", trim_multiline("\t\t...".into(), false, None));
1477+
fn test_reindent_multiline_single_line() {
1478+
assert_eq!("", reindent_multiline("".into(), false, None));
1479+
assert_eq!("...", reindent_multiline("...".into(), false, None));
1480+
assert_eq!("...", reindent_multiline(" ...".into(), false, None));
1481+
assert_eq!("...", reindent_multiline("\t...".into(), false, None));
1482+
assert_eq!("...", reindent_multiline("\t\t...".into(), false, None));
14871483
}
14881484

14891485
#[test]
14901486
#[rustfmt::skip]
1491-
fn test_trim_multiline_block() {
1487+
fn test_reindent_multiline_block() {
14921488
assert_eq!("\
14931489
if x {
14941490
y
14951491
} else {
14961492
z
1497-
}", trim_multiline(" if x {
1493+
}", reindent_multiline(" if x {
14981494
y
14991495
} else {
15001496
z
@@ -1504,7 +1500,7 @@ mod test {
15041500
\ty
15051501
} else {
15061502
\tz
1507-
}", trim_multiline(" if x {
1503+
}", reindent_multiline(" if x {
15081504
\ty
15091505
} else {
15101506
\tz
@@ -1513,21 +1509,37 @@ mod test {
15131509

15141510
#[test]
15151511
#[rustfmt::skip]
1516-
fn test_trim_multiline_empty_line() {
1512+
fn test_reindent_multiline_empty_line() {
15171513
assert_eq!("\
15181514
if x {
15191515
y
15201516
15211517
} else {
15221518
z
1523-
}", trim_multiline(" if x {
1519+
}", reindent_multiline(" if x {
15241520
y
15251521
15261522
} else {
15271523
z
15281524
}".into(), false, None));
15291525
}
15301526

1527+
#[test]
1528+
#[rustfmt::skip]
1529+
fn test_reindent_multiline_lines_deeper() {
1530+
assert_eq!("\
1531+
if x {
1532+
y
1533+
} else {
1534+
z
1535+
}", reindent_multiline("\
1536+
if x {
1537+
y
1538+
} else {
1539+
z
1540+
}".into(), true, Some(8)));
1541+
}
1542+
15311543
#[test]
15321544
fn test_without_block_comments_lines_without_block_comments() {
15331545
let result = without_block_comments(vec!["/*", "", "*/"]);

0 commit comments

Comments
 (0)