Skip to content

Commit

Permalink
Auto merge of rust-lang#9099 - joshtriplett:unnecessary-lazy-eval-the…
Browse files Browse the repository at this point in the history
…n-some, r=flip1995

Extend unnecessary_lazy_eval to cover `bool::then` -> `bool::then_some`

fixes rust-lang#9097

changelog: Extend `unnecessary_lazy_eval` to convert `bool::then` to `bool::then_some`
  • Loading branch information
bors committed Jul 6, 2022
2 parents fd605ab + b7230d4 commit f93d418
Show file tree
Hide file tree
Showing 22 changed files with 78 additions and 54 deletions.
2 changes: 1 addition & 1 deletion clippy_dev/src/update_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ fn replace_ident_like(contents: &str, replacements: &[(&str, &str)]) -> Option<S
pos = m.end();
}
result.push_str(&contents[pos..]);
edited.then(|| result)
edited.then_some(result)
}

fn round_to_fifty(count: usize) -> usize {
Expand Down
4 changes: 3 additions & 1 deletion clippy_lints/src/dereference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,7 +744,9 @@ fn walk_parents<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> (Position, &
},
)
},
ExprKind::Call(func, _) if func.hir_id == child_id => (child_id == e.hir_id).then(|| Position::Callee),
ExprKind::Call(func, _) if func.hir_id == child_id => {
(child_id == e.hir_id).then_some(Position::Callee)
},
ExprKind::Call(func, args) => args
.iter()
.position(|arg| arg.hir_id == child_id)
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,7 @@ fn find_insert_calls<'tcx>(
let allow_insert_closure = s.allow_insert_closure;
let is_single_insert = s.is_single_insert;
let edits = s.edits;
s.can_use_entry.then(|| InsertSearchResults {
s.can_use_entry.then_some(InsertSearchResults {
edits,
allow_insert_closure,
is_single_insert,
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/inherent_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ fn get_impl_span(cx: &LateContext<'_>, id: LocalDefId) -> Option<Span> {
(!span.from_expansion()
&& impl_item.generics.params.is_empty()
&& !is_lint_allowed(cx, MULTIPLE_INHERENT_IMPL, id))
.then(|| span)
.then_some(span)
} else {
None
}
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/manual_non_exhaustive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustiveEnum {
(matches!(v.data, hir::VariantData::Unit(_))
&& v.ident.as_str().starts_with('_')
&& is_doc_hidden(cx.tcx.hir().attrs(v.id)))
.then(|| (id, v.span))
.then_some((id, v.span))
});
if let Some((id, span)) = iter.next()
&& iter.next().is_none()
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/matches/manual_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ fn check<'tcx>(

// Determine which binding mode to use.
let explicit_ref = some_pat.contains_explicit_ref_binding();
let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then(|| ty_mutability));
let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then_some(ty_mutability));

let as_ref_str = match binding_ref {
Some(Mutability::Mut) => ".as_mut()",
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/matches/match_same_arms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>]) {
normalized_pats[i + 1..]
.iter()
.enumerate()
.find_map(|(j, other)| pat.has_overlapping_values(other).then(|| i + 1 + j))
.find_map(|(j, other)| pat.has_overlapping_values(other).then_some(i + 1 + j))
.unwrap_or(normalized_pats.len())
})
.collect();
Expand All @@ -55,7 +55,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>]) {
.zip(forwards_blocking_idxs[..i].iter().copied().rev())
.skip_while(|&(_, forward_block)| forward_block > i)
.find_map(|((j, other), forward_block)| {
(forward_block == i || pat.has_overlapping_values(other)).then(|| j)
(forward_block == i || pat.has_overlapping_values(other)).then_some(j)
})
.unwrap_or(0)
})
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/matches/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1061,7 +1061,7 @@ fn contains_cfg_arm(cx: &LateContext<'_>, e: &Expr<'_>, scrutinee: &Expr<'_>, ar
let start = scrutinee_span.hi();
let mut arm_spans = arms.iter().map(|arm| {
let data = arm.span.data();
(data.ctxt == SyntaxContext::root()).then(|| (data.lo, data.hi))
(data.ctxt == SyntaxContext::root()).then_some((data.lo, data.hi))
});
let end = e.span.hi();

Expand Down Expand Up @@ -1095,7 +1095,7 @@ fn contains_cfg_arm(cx: &LateContext<'_>, e: &Expr<'_>, scrutinee: &Expr<'_>, ar
parent: None,
}
.span();
(!span_contains_cfg(cx, span)).then(|| next_start).ok_or(())
(!span_contains_cfg(cx, span)).then_some(next_start).ok_or(())
});
match found {
Ok(start) => {
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/methods/manual_str_repeat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn parse_repeat_arg(cx: &LateContext<'_>, e: &Expr<'_>) -> Option<RepeatKind> {
Some(RepeatKind::String)
} else {
let ty = ty.peel_refs();
(ty.is_str() || is_type_diagnostic_item(cx, ty, sym::String)).then(|| RepeatKind::String)
(ty.is_str() || is_type_diagnostic_item(cx, ty, sym::String)).then_some(RepeatKind::String)
}
}
}
Expand Down
6 changes: 6 additions & 0 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2737,6 +2737,12 @@ impl Methods {
}
},
("take", []) => needless_option_take::check(cx, expr, recv),
("then", [arg]) => {
if !meets_msrv(self.msrv, msrvs::BOOL_THEN_SOME) {
return;
}
unnecessary_lazy_eval::check(cx, expr, recv, arg, "then_some");
},
("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
implicit_clone::check(cx, name, expr, recv);
},
Expand Down
7 changes: 5 additions & 2 deletions clippy_lints/src/methods/unnecessary_lazy_eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ pub(super) fn check<'tcx>(
) {
let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Option);
let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Result);
let is_bool = cx.typeck_results().expr_ty(recv).is_bool();

if is_option || is_result {
if is_option || is_result || is_bool {
if let hir::ExprKind::Closure { body, .. } = arg.kind {
let body = cx.tcx.hir().body(body);
let body_expr = &body.value;
Expand All @@ -33,8 +34,10 @@ pub(super) fn check<'tcx>(
if eager_or_lazy::switch_to_eager_eval(cx, body_expr) {
let msg = if is_option {
"unnecessary closure used to substitute value for `Option::None`"
} else {
} else if is_result {
"unnecessary closure used to substitute value for `Result::Err`"
} else {
"unnecessary closure used with `bool::then`"
};
let applicability = if body
.params
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/option_if_let_else.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ fn detect_option_if_let_else<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) ->
});
if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(local_id), .. })) = e.kind {
match some_captures.get(local_id)
.or_else(|| (method_sugg == "map_or_else").then(|| ()).and_then(|_| none_captures.get(local_id)))
.or_else(|| (method_sugg == "map_or_else").then_some(()).and_then(|_| none_captures.get(local_id)))
{
Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return None,
Some(CaptureKind::Ref(Mutability::Not)) if as_mut => return None,
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ fn check_mut_from_ref<'tcx>(cx: &LateContext<'tcx>, sig: &FnSig<'_>, body: Optio
.iter()
.filter_map(get_rptr_lm)
.filter(|&(lt, _, _)| lt.name == out.name)
.map(|(_, mutability, span)| (mutability == Mutability::Not).then(|| span))
.map(|(_, mutability, span)| (mutability == Mutability::Not).then_some(span))
.collect();
if let Some(args) = args
&& !args.is_empty()
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/swap_ptr_to_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ fn is_ptr_to_ref(cx: &LateContext<'_>, e: &Expr<'_>, ctxt: SyntaxContext) -> (bo
&& let ExprKind::Unary(UnOp::Deref, derefed_expr) = borrowed_expr.kind
&& cx.typeck_results().expr_ty(derefed_expr).is_unsafe_ptr()
{
(true, (borrowed_expr.span.ctxt() == ctxt || derefed_expr.span.ctxt() == ctxt).then(|| derefed_expr.span))
(true, (borrowed_expr.span.ctxt() == ctxt || derefed_expr.span.ctxt() == ctxt).then_some(derefed_expr.span))
} else {
(false, None)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -843,7 +843,7 @@ fn get_lint_group(cx: &LateContext<'_>, lint_id: LintId) -> Option<String> {
fn get_lint_level_from_group(lint_group: &str) -> Option<&'static str> {
DEFAULT_LINT_LEVELS
.iter()
.find_map(|(group_name, group_level)| (*group_name == lint_group).then(|| *group_level))
.find_map(|(group_name, group_level)| (*group_name == lint_group).then_some(*group_level))
}

pub(super) fn is_deprecated_lint(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,7 @@ impl Write {
args.push(arg, span);
}

parser.errors.is_empty().then(move || args)
parser.errors.is_empty().then_some(args)
}

/// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
Expand Down
2 changes: 1 addition & 1 deletion clippy_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1016,7 +1016,7 @@ pub fn can_move_expr_to_closure<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'
captures: HirIdMap::default(),
};
v.visit_expr(expr);
v.allow_closure.then(|| v.captures)
v.allow_closure.then_some(v.captures)
}

/// Returns the method names and argument list of nested method call expressions that make up
Expand Down
1 change: 1 addition & 0 deletions clippy_utils/src/msrvs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ macro_rules! msrv_aliases {

// names may refer to stabilized feature flags or library items
msrv_aliases! {
1,62,0 { BOOL_THEN_SOME }
1,53,0 { OR_PATTERNS, MANUAL_BITS, BTREE_MAP_RETAIN, BTREE_SET_RETAIN }
1,52,0 { STR_SPLIT_ONCE, REM_EUCLID_CONST }
1,51,0 { BORROW_AS_PTR, UNSIGNED_ABS }
Expand Down
2 changes: 1 addition & 1 deletion clippy_utils/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ pub fn snippet_with_context<'a>(
/// span containing `m!(0)`.
pub fn walk_span_to_context(span: Span, outer: SyntaxContext) -> Option<Span> {
let outer_span = hygiene::walk_chain(span, outer);
(outer_span.ctxt() == outer).then(|| outer_span)
(outer_span.ctxt() == outer).then_some(outer_span)
}

/// Removes block comments from the given `Vec` of lines.
Expand Down
2 changes: 2 additions & 0 deletions tests/ui/unnecessary_lazy_eval.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ fn main() {
let ext_opt = Some(42);
let nested_opt = Some(Some(42));
let nested_tuple_opt = Some(Some((42, 43)));
let cond = true;

// Should lint - Option
let _ = opt.unwrap_or(2);
Expand All @@ -42,6 +43,7 @@ fn main() {
let _ = opt.get_or_insert(2);
let _ = opt.ok_or(2);
let _ = nested_tuple_opt.unwrap_or(Some((1, 2)));
let _ = cond.then_some(astronomers_pi);

// Cases when unwrap is not called on a simple variable
let _ = Some(10).unwrap_or(2);
Expand Down
2 changes: 2 additions & 0 deletions tests/ui/unnecessary_lazy_eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ fn main() {
let ext_opt = Some(42);
let nested_opt = Some(Some(42));
let nested_tuple_opt = Some(Some((42, 43)));
let cond = true;

// Should lint - Option
let _ = opt.unwrap_or_else(|| 2);
Expand All @@ -42,6 +43,7 @@ fn main() {
let _ = opt.get_or_insert_with(|| 2);
let _ = opt.ok_or_else(|| 2);
let _ = nested_tuple_opt.unwrap_or_else(|| Some((1, 2)));
let _ = cond.then(|| astronomers_pi);

// Cases when unwrap is not called on a simple variable
let _ = Some(10).unwrap_or_else(|| 2);
Expand Down
Loading

0 comments on commit f93d418

Please sign in to comment.