Skip to content

Commit 4a94ad6

Browse files
authored
Simplify reindent_multiline() signature (#14101)
- `reindent_multiline()` always returns the result of `reindent_multiline_inner()` which returns a `String`. Make `reindent_multiline()` return a `String` as well, instead of a systematically owned `Cow<'_, str>`. - There is no reason for `reindent_multiline()` to force a caller to build a `Cow<'_, str>` instead of passing a `&str` directly, especially considering that a `String` will always be returned. Also, both the input parameter and return value (of type `Cow<'_, str>`) shared the same (elided) lifetime for no reason: this worked only because the result was always the `Cow::Owned` variant which is compatible with any lifetime. As a consequence, the signature changes from: ```rust fn reindent_multiline(s: Cow<'_, str>, …) -> Cow<'_, str> { … } ``` to ```rust fn reindent_multiline(s: &str, …) -> String { … } ``` changelog: none
2 parents dc330b8 + 64dec07 commit 4a94ad6

13 files changed

+46
-64
lines changed

clippy_lints/src/copies.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ use rustc_session::impl_lint_pass;
1818
use rustc_span::hygiene::walk_chain;
1919
use rustc_span::source_map::SourceMap;
2020
use rustc_span::{Span, Symbol};
21-
use std::borrow::Cow;
2221

2322
declare_clippy_lint! {
2423
/// ### What it does
@@ -248,18 +247,18 @@ fn lint_branches_sharing_code<'tcx>(
248247
let first_line_span = first_line_of_span(cx, expr.span);
249248
let replace_span = first_line_span.with_hi(span.hi());
250249
let cond_span = first_line_span.until(first_block.span);
251-
let cond_snippet = reindent_multiline(snippet(cx, cond_span, "_"), false, None);
250+
let cond_snippet = reindent_multiline(&snippet(cx, cond_span, "_"), false, None);
252251
let cond_indent = indent_of(cx, cond_span);
253-
let moved_snippet = reindent_multiline(snippet(cx, span, "_"), true, None);
252+
let moved_snippet = reindent_multiline(&snippet(cx, span, "_"), true, None);
254253
let suggestion = moved_snippet.to_string() + "\n" + &cond_snippet + "{";
255-
let suggestion = reindent_multiline(Cow::Borrowed(&suggestion), true, cond_indent);
254+
let suggestion = reindent_multiline(&suggestion, true, cond_indent);
256255
(replace_span, suggestion.to_string())
257256
});
258257
let end_suggestion = res.end_span(last_block, sm).map(|span| {
259-
let moved_snipped = reindent_multiline(snippet(cx, span, "_"), true, None);
258+
let moved_snipped = reindent_multiline(&snippet(cx, span, "_"), true, None);
260259
let indent = indent_of(cx, expr.span.shrink_to_hi());
261260
let suggestion = "}\n".to_string() + &moved_snipped;
262-
let suggestion = reindent_multiline(Cow::Borrowed(&suggestion), true, indent);
261+
let suggestion = reindent_multiline(&suggestion, true, indent);
263262

264263
let span = span.with_hi(last_block.span.hi());
265264
// Improve formatting if the inner block has indention (i.e. normal Rust formatting)

clippy_lints/src/entry.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,8 @@ impl<'tcx> LateLintPass<'tcx> for HashMapPass {
135135
format!(
136136
"match {map_str}.entry({key_str}) {{\n{indent_str} {entry}::{then_entry} => {}\n\
137137
{indent_str} {entry}::{else_entry} => {}\n{indent_str}}}",
138-
reindent_multiline(then_str.into(), true, Some(4 + indent_str.len())),
139-
reindent_multiline(else_str.into(), true, Some(4 + indent_str.len())),
138+
reindent_multiline(&then_str, true, Some(4 + indent_str.len())),
139+
reindent_multiline(&else_str, true, Some(4 + indent_str.len())),
140140
entry = map_ty.entry_path(),
141141
)
142142
}

clippy_lints/src/if_not_else.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
77
use rustc_lint::{LateContext, LateLintPass};
88
use rustc_session::declare_lint_pass;
99
use rustc_span::Span;
10-
use std::borrow::Cow;
1110

1211
declare_clippy_lint! {
1312
/// ### What it does
@@ -107,7 +106,7 @@ fn make_sugg<'a>(
107106
els_span: Span,
108107
default: &'a str,
109108
indent_relative_to: Option<Span>,
110-
) -> Cow<'a, str> {
109+
) -> String {
111110
let cond_inner_snip = snippet(sess, cond_inner, default);
112111
let els_snip = snippet(sess, els_span, default);
113112
let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
@@ -130,5 +129,5 @@ fn make_sugg<'a>(
130129
_ => String::new(),
131130
};
132131

133-
reindent_multiline(suggestion.into(), true, indent)
132+
reindent_multiline(&suggestion, true, indent)
134133
}

clippy_lints/src/matches/manual_unwrap_or.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ fn lint<'tcx>(
117117
or_body_snippet: &str,
118118
indent: usize,
119119
) {
120-
let reindented_or_body = reindent_multiline(or_body_snippet.into(), true, Some(indent));
120+
let reindented_or_body = reindent_multiline(or_body_snippet, true, Some(indent));
121121

122122
let mut app = Applicability::MachineApplicable;
123123
let suggestion = sugg::Sugg::hir_with_context(cx, scrutinee, expr.span.ctxt(), "..", &mut app).maybe_par();

clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,13 @@ pub(super) fn check<'tcx>(
5757
};
5858

5959
let suggestion_source = reindent_multiline(
60-
format!(
60+
&format!(
6161
"std::path::Path::new({})
6262
.extension()
6363
.map_or(false, |ext| ext.eq_ignore_ascii_case(\"{}\"))",
6464
recv_source,
6565
ext_str.strip_prefix('.').unwrap()
66-
)
67-
.into(),
66+
),
6867
true,
6968
Some(indent_of(cx, call_span).unwrap_or(0) + 4),
7069
);

clippy_lints/src/methods/filter_map.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ use rustc_lint::LateContext;
1212
use rustc_middle::ty::adjustment::Adjust;
1313
use rustc_span::Span;
1414
use rustc_span::symbol::{Ident, Symbol, sym};
15-
use std::borrow::Cow;
1615

1716
use super::{MANUAL_FILTER_MAP, MANUAL_FIND_MAP, OPTION_FILTER_MAP, RESULT_FILTER_MAP};
1817

@@ -302,7 +301,7 @@ pub(super) fn check(
302301
filter_span.with_hi(expr.span.hi()),
303302
"`filter` for `Some` followed by `unwrap`",
304303
"consider using `flatten` instead",
305-
reindent_multiline(Cow::Borrowed("flatten()"), true, indent_of(cx, map_span)).into_owned(),
304+
reindent_multiline("flatten()", true, indent_of(cx, map_span)),
306305
Applicability::MachineApplicable,
307306
);
308307

@@ -316,7 +315,7 @@ pub(super) fn check(
316315
filter_span.with_hi(expr.span.hi()),
317316
"`filter` for `Ok` followed by `unwrap`",
318317
"consider using `flatten` instead",
319-
reindent_multiline(Cow::Borrowed("flatten()"), true, indent_of(cx, map_span)).into_owned(),
318+
reindent_multiline("flatten()", true, indent_of(cx, map_span)),
320319
Applicability::MachineApplicable,
321320
);
322321

clippy_lints/src/methods/iter_filter.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ use rustc_hir as hir;
1212
use rustc_hir::QPath;
1313
use rustc_span::Span;
1414
use rustc_span::symbol::{Ident, Symbol, sym};
15-
use std::borrow::Cow;
1615

1716
///
1817
/// Returns true if the expression is a method call to `method_name`
@@ -181,7 +180,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, filter_arg: &hir
181180
filter_span.with_hi(expr.span.hi()),
182181
"`filter` for `is_ok` on iterator over `Result`s",
183182
"consider using `flatten` instead",
184-
reindent_multiline(Cow::Borrowed("flatten()"), true, indent_of(cx, filter_span)).into_owned(),
183+
reindent_multiline("flatten()", true, indent_of(cx, filter_span)),
185184
Applicability::HasPlaceholders,
186185
),
187186
Some(FilterType::IsSome) => span_lint_and_sugg(
@@ -190,7 +189,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, filter_arg: &hir
190189
filter_span.with_hi(expr.span.hi()),
191190
"`filter` for `is_some` on iterator over `Option`",
192191
"consider using `flatten` instead",
193-
reindent_multiline(Cow::Borrowed("flatten()"), true, indent_of(cx, filter_span)).into_owned(),
192+
reindent_multiline("flatten()", true, indent_of(cx, filter_span)),
194193
Applicability::HasPlaceholders,
195194
),
196195
}

clippy_lints/src/methods/manual_ok_or.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ pub(super) fn check<'tcx>(
2727
&& let Some(err_arg_snippet) = err_arg.span.get_source_text(cx)
2828
&& let Some(indent) = indent_of(cx, expr.span)
2929
{
30-
let reindented_err_arg_snippet = reindent_multiline(err_arg_snippet.as_str().into(), true, Some(indent + 4));
30+
let reindented_err_arg_snippet = reindent_multiline(err_arg_snippet.as_str(), true, Some(indent + 4));
3131
span_lint_and_sugg(
3232
cx,
3333
MANUAL_OK_OR,

clippy_lints/src/methods/return_and_then.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ pub(super) fn check<'tcx>(
6060
"let {} = {}?;\n{}",
6161
arg_snip,
6262
recv_snip,
63-
reindent_multiline(inner.into(), false, indent_of(cx, expr.span))
63+
reindent_multiline(inner, false, indent_of(cx, expr.span))
6464
);
6565

6666
span_lint_and_sugg(cx, RETURN_AND_THEN, expr.span, msg, "try", sugg, applicability);

clippy_lints/src/needless_continue.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ fn suggestion_snippet_for_continue_inside_else(cx: &EarlyContext<'_>, data: &Lin
356356
.iter()
357357
.map(|stmt| {
358358
let span = cx.sess().source_map().stmt_span(stmt.span, data.loop_block.span);
359-
let snip = snippet_block(cx, span, "..", None).into_owned();
359+
let snip = snippet_block(cx, span, "..", None);
360360
snip.lines()
361361
.map(|line| format!("{}{line}", " ".repeat(indent)))
362362
.collect::<Vec<_>>()

clippy_lints/src/redundant_else.rs

+2-8
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ use rustc_errors::Applicability;
66
use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
77
use rustc_session::declare_lint_pass;
88
use rustc_span::Span;
9-
use std::borrow::Cow;
109

1110
declare_clippy_lint! {
1211
/// ### What it does
@@ -163,14 +162,9 @@ fn extract_else_block(mut block: &str) -> String {
163162
block.trim_end().to_string()
164163
}
165164

166-
fn make_sugg<'a>(
167-
cx: &EarlyContext<'_>,
168-
els_span: Span,
169-
default: &'a str,
170-
indent_relative_to: Option<Span>,
171-
) -> Cow<'a, str> {
165+
fn make_sugg(cx: &EarlyContext<'_>, els_span: Span, default: &str, indent_relative_to: Option<Span>) -> String {
172166
let extracted = extract_else_block(&snippet(cx, els_span, default));
173167
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
174168

175-
reindent_multiline(extracted.into(), false, indent)
169+
reindent_multiline(&extracted, false, indent)
176170
}

clippy_lints/src/unit_types/unit_arg.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -177,16 +177,15 @@ fn fmt_stmts_and_call(
177177
stmts_and_call.push(call_snippet_with_replacements);
178178
stmts_and_call = stmts_and_call
179179
.into_iter()
180-
.map(|v| reindent_multiline(v.into(), true, Some(call_expr_indent)).into_owned())
180+
.map(|v| reindent_multiline(&v, true, Some(call_expr_indent)))
181181
.collect();
182182

183183
let mut stmts_and_call_snippet = stmts_and_call.join(&format!("{}{}", ";\n", " ".repeat(call_expr_indent)));
184184
// expr is not in a block statement or result expression position, wrap in a block
185185
let parent_node = cx.tcx.parent_hir_node(call_expr.hir_id);
186186
if !matches!(parent_node, Node::Block(_)) && !matches!(parent_node, Node::Stmt(_)) {
187187
let block_indent = call_expr_indent + 4;
188-
stmts_and_call_snippet =
189-
reindent_multiline(stmts_and_call_snippet.into(), true, Some(block_indent)).into_owned();
188+
stmts_and_call_snippet = reindent_multiline(&stmts_and_call_snippet, true, Some(block_indent));
190189
stmts_and_call_snippet = format!(
191190
"{{\n{}{}\n{}}}",
192191
" ".repeat(block_indent),

clippy_utils/src/source.rs

+23-29
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,7 @@ pub fn expr_block(
307307
&& let ExprKind::Block(block, None) = expr.kind
308308
&& block.rules != BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
309309
{
310-
format!("{code}")
310+
code
311311
} else {
312312
// FIXME: add extra indent for the unsafe blocks:
313313
// original code: unsafe { ... }
@@ -420,11 +420,10 @@ pub fn position_before_rarrow(s: &str) -> Option<usize> {
420420
}
421421

422422
/// Reindent a multiline string with possibility of ignoring the first line.
423-
#[expect(clippy::needless_pass_by_value)]
424-
pub fn reindent_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
425-
let s_space = reindent_multiline_inner(&s, ignore_first, indent, ' ');
423+
pub fn reindent_multiline(s: &str, ignore_first: bool, indent: Option<usize>) -> String {
424+
let s_space = reindent_multiline_inner(s, ignore_first, indent, ' ');
426425
let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
427-
reindent_multiline_inner(&s_tab, ignore_first, indent, ' ').into()
426+
reindent_multiline_inner(&s_tab, ignore_first, indent, ' ')
428427
}
429428

430429
fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
@@ -552,42 +551,37 @@ pub fn snippet_opt(sess: &impl HasSession, span: Span) -> Option<String> {
552551
/// } // aligned with `if`
553552
/// ```
554553
/// Note that the first line of the snippet always has 0 indentation.
555-
pub fn snippet_block<'a>(
556-
sess: &impl HasSession,
557-
span: Span,
558-
default: &'a str,
559-
indent_relative_to: Option<Span>,
560-
) -> Cow<'a, str> {
554+
pub fn snippet_block(sess: &impl HasSession, span: Span, default: &str, indent_relative_to: Option<Span>) -> String {
561555
let snip = snippet(sess, span, default);
562556
let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
563-
reindent_multiline(snip, true, indent)
557+
reindent_multiline(&snip, true, indent)
564558
}
565559

566560
/// Same as `snippet_block`, but adapts the applicability level by the rules of
567561
/// `snippet_with_applicability`.
568-
pub fn snippet_block_with_applicability<'a>(
562+
pub fn snippet_block_with_applicability(
569563
sess: &impl HasSession,
570564
span: Span,
571-
default: &'a str,
565+
default: &str,
572566
indent_relative_to: Option<Span>,
573567
applicability: &mut Applicability,
574-
) -> Cow<'a, str> {
568+
) -> String {
575569
let snip = snippet_with_applicability(sess, span, default, applicability);
576570
let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
577-
reindent_multiline(snip, true, indent)
571+
reindent_multiline(&snip, true, indent)
578572
}
579573

580-
pub fn snippet_block_with_context<'a>(
574+
pub fn snippet_block_with_context(
581575
sess: &impl HasSession,
582576
span: Span,
583577
outer: SyntaxContext,
584-
default: &'a str,
578+
default: &str,
585579
indent_relative_to: Option<Span>,
586580
app: &mut Applicability,
587-
) -> (Cow<'a, str>, bool) {
581+
) -> (String, bool) {
588582
let (snip, from_macro) = snippet_with_context(sess, span, outer, default, app);
589583
let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
590-
(reindent_multiline(snip, true, indent), from_macro)
584+
(reindent_multiline(&snip, true, indent), from_macro)
591585
}
592586

593587
/// Same as `snippet_with_applicability`, but first walks the span up to the given context.
@@ -748,11 +742,11 @@ mod test {
748742

749743
#[test]
750744
fn test_reindent_multiline_single_line() {
751-
assert_eq!("", reindent_multiline("".into(), false, None));
752-
assert_eq!("...", reindent_multiline("...".into(), false, None));
753-
assert_eq!("...", reindent_multiline(" ...".into(), false, None));
754-
assert_eq!("...", reindent_multiline("\t...".into(), false, None));
755-
assert_eq!("...", reindent_multiline("\t\t...".into(), false, None));
745+
assert_eq!("", reindent_multiline("", false, None));
746+
assert_eq!("...", reindent_multiline("...", false, None));
747+
assert_eq!("...", reindent_multiline(" ...", false, None));
748+
assert_eq!("...", reindent_multiline("\t...", false, None));
749+
assert_eq!("...", reindent_multiline("\t\t...", false, None));
756750
}
757751

758752
#[test]
@@ -767,7 +761,7 @@ mod test {
767761
y
768762
} else {
769763
z
770-
}".into(), false, None));
764+
}", false, None));
771765
assert_eq!("\
772766
if x {
773767
\ty
@@ -777,7 +771,7 @@ mod test {
777771
\ty
778772
} else {
779773
\tz
780-
}".into(), false, None));
774+
}", false, None));
781775
}
782776

783777
#[test]
@@ -794,7 +788,7 @@ mod test {
794788
795789
} else {
796790
z
797-
}".into(), false, None));
791+
}", false, None));
798792
}
799793

800794
#[test]
@@ -810,6 +804,6 @@ mod test {
810804
y
811805
} else {
812806
z
813-
}".into(), true, Some(8)));
807+
}", true, Some(8)));
814808
}
815809
}

0 commit comments

Comments
 (0)