2020-08-21 17:43:04 -05:00
|
|
|
use crate::utils::{eager_or_lazy, usage};
|
|
|
|
use crate::utils::{is_type_diagnostic_item, snippet, span_lint_and_sugg};
|
2020-08-16 13:47:50 -05:00
|
|
|
use rustc_errors::Applicability;
|
|
|
|
use rustc_hir as hir;
|
|
|
|
use rustc_lint::LateContext;
|
|
|
|
|
2020-08-16 15:16:39 -05:00
|
|
|
use super::UNNECESSARY_LAZY_EVALUATIONS;
|
2020-08-16 13:47:50 -05:00
|
|
|
|
|
|
|
/// lint use of `<fn>_else(simple closure)` for `Option`s and `Result`s that can be
|
|
|
|
/// replaced with `<fn>(return value of simple closure)`
|
|
|
|
pub(super) fn lint<'tcx>(
|
|
|
|
cx: &LateContext<'tcx>,
|
|
|
|
expr: &'tcx hir::Expr<'_>,
|
|
|
|
args: &'tcx [hir::Expr<'_>],
|
|
|
|
simplify_using: &str,
|
|
|
|
) {
|
|
|
|
let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&args[0]), sym!(option_type));
|
|
|
|
let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&args[0]), sym!(result_type));
|
|
|
|
|
2020-08-16 14:04:02 -05:00
|
|
|
if is_option || is_result {
|
|
|
|
if let hir::ExprKind::Closure(_, _, eid, _, _) = args[1].kind {
|
|
|
|
let body = cx.tcx.hir().body(eid);
|
2020-08-21 17:43:04 -05:00
|
|
|
let body_expr = &body.value;
|
|
|
|
|
|
|
|
if usage::BindingUsageFinder::are_params_used(cx, body) {
|
|
|
|
return;
|
|
|
|
}
|
2020-08-16 13:47:50 -05:00
|
|
|
|
2020-08-21 17:43:04 -05:00
|
|
|
if eager_or_lazy::is_eagerness_candidate(cx, body_expr) {
|
2020-08-16 14:04:02 -05:00
|
|
|
let msg = if is_option {
|
|
|
|
"unnecessary closure used to substitute value for `Option::None`"
|
2020-08-16 13:47:50 -05:00
|
|
|
} else {
|
2020-08-16 14:04:02 -05:00
|
|
|
"unnecessary closure used to substitute value for `Result::Err`"
|
|
|
|
};
|
2020-08-16 13:47:50 -05:00
|
|
|
|
2020-08-16 14:04:02 -05:00
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
2020-08-16 15:16:39 -05:00
|
|
|
UNNECESSARY_LAZY_EVALUATIONS,
|
2020-08-16 14:04:02 -05:00
|
|
|
expr.span,
|
|
|
|
msg,
|
|
|
|
&format!("Use `{}` instead", simplify_using),
|
|
|
|
format!(
|
|
|
|
"{0}.{1}({2})",
|
|
|
|
snippet(cx, args[0].span, ".."),
|
|
|
|
simplify_using,
|
2020-08-21 17:43:04 -05:00
|
|
|
snippet(cx, body_expr.span, ".."),
|
2020-08-16 14:04:02 -05:00
|
|
|
),
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
2020-08-16 13:47:50 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|