Skip to content

Commit a069320

Browse files
committed
Auto merge of #3684 - g-bartoszek:sugg-snippet-modifications, r=phansch
"make_return" and "blockify" convenience methods, fixes #3683 …ed them in "needless_bool".
2 parents a40d8e4 + 0f5c43a commit a069320

File tree

2 files changed

+35
-8
lines changed

2 files changed

+35
-8
lines changed

clippy_lints/src/needless_bool.rs

+6-8
Original file line numberDiff line numberDiff line change
@@ -70,16 +70,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
7070
let reduce = |ret, not| {
7171
let mut applicability = Applicability::MachineApplicable;
7272
let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
73-
let snip = if not { !snip } else { snip };
73+
let mut snip = if not { !snip } else { snip };
7474

75-
let mut hint = if ret {
76-
format!("return {}", snip)
77-
} else {
78-
snip.to_string()
79-
};
75+
if ret {
76+
snip = snip.make_return();
77+
}
8078

8179
if parent_node_is_if_expr(&e, &cx) {
82-
hint = format!("{{ {} }}", hint);
80+
snip = snip.blockify()
8381
}
8482

8583
span_lint_and_sugg(
@@ -88,7 +86,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
8886
e.span,
8987
"this if-then-else expression returns a bool literal",
9088
"you can reduce it to",
91-
hint,
89+
snip.to_string(),
9290
applicability,
9391
);
9492
};

clippy_lints/src/utils/sugg.rs

+29
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,17 @@ impl<'a> Sugg<'a> {
206206
make_unop("&mut *", self)
207207
}
208208

209+
/// Convenience method to transform suggestion into a return call
210+
pub fn make_return(self) -> Sugg<'static> {
211+
Sugg::NonParen(Cow::Owned(format!("return {}", self)))
212+
}
213+
214+
/// Convenience method to transform suggestion into a block
215+
/// where the suggestion is a trailing expression
216+
pub fn blockify(self) -> Sugg<'static> {
217+
Sugg::NonParen(Cow::Owned(format!("{{ {} }}", self)))
218+
}
219+
209220
/// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
210221
/// suggestion.
211222
#[allow(dead_code)]
@@ -578,3 +589,21 @@ impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_error
578589
self.span_suggestion_with_applicability(remove_span, msg, String::new(), applicability);
579590
}
580591
}
592+
593+
#[cfg(test)]
594+
mod test {
595+
use super::Sugg;
596+
use std::borrow::Cow;
597+
598+
const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
599+
600+
#[test]
601+
fn make_return_transform_sugg_into_a_return_call() {
602+
assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
603+
}
604+
605+
#[test]
606+
fn blockify_transforms_sugg_into_a_block() {
607+
assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
608+
}
609+
}

0 commit comments

Comments
 (0)