Skip to content

Commit

Permalink
Rollup merge of rust-lang#3684 - g-bartoszek:sugg-snippet-modificatio…
Browse files Browse the repository at this point in the history
…ns, r=oli-obk

"make_return" and "blockify" convenience methods, fixes rust-lang#3683

…ed them in "needless_bool".
  • Loading branch information
flip1995 committed Jan 22, 2019
2 parents d342761 + 0f5c43a commit 1e672af
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
14 changes: 6 additions & 8 deletions clippy_lints/src/needless_bool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
let reduce = |ret, not| {
let mut applicability = Applicability::MachineApplicable;
let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
let snip = if not { !snip } else { snip };
let mut snip = if not { !snip } else { snip };

let mut hint = if ret {
format!("return {}", snip)
} else {
snip.to_string()
};
if ret {
snip = snip.make_return();
}

if parent_node_is_if_expr(&e, &cx) {
hint = format!("{{ {} }}", hint);
snip = snip.blockify()
}

span_lint_and_sugg(
Expand All @@ -88,7 +86,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
e.span,
"this if-then-else expression returns a bool literal",
"you can reduce it to",
hint,
snip.to_string(),
applicability,
);
};
Expand Down
29 changes: 29 additions & 0 deletions clippy_lints/src/utils/sugg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,17 @@ impl<'a> Sugg<'a> {
make_unop("&mut *", self)
}

/// Convenience method to transform suggestion into a return call
pub fn make_return(self) -> Sugg<'static> {
Sugg::NonParen(Cow::Owned(format!("return {}", self)))
}

/// Convenience method to transform suggestion into a block
/// where the suggestion is a trailing expression
pub fn blockify(self) -> Sugg<'static> {
Sugg::NonParen(Cow::Owned(format!("{{ {} }}", self)))
}

/// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
/// suggestion.
#[allow(dead_code)]
Expand Down Expand Up @@ -578,3 +589,21 @@ impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_error
self.span_suggestion_with_applicability(remove_span, msg, String::new(), applicability);
}
}

#[cfg(test)]
mod test {
use super::Sugg;
use std::borrow::Cow;

const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));

#[test]
fn make_return_transform_sugg_into_a_return_call() {
assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
}

#[test]
fn blockify_transforms_sugg_into_a_block() {
assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
}
}

0 comments on commit 1e672af

Please sign in to comment.