1 use super::{contains_return, BIND_INSTEAD_OF_MAP};
3 in_macro, match_qpath, match_type, method_calls, multispan_sugg_with_applicability, paths, remove_blocks, snippet,
4 snippet_with_macro_callsite, span_lint_and_sugg, span_lint_and_then,
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
9 use rustc_hir::intravisit::{self, Visitor};
10 use rustc_lint::LateContext;
11 use rustc_middle::hir::map::Map;
14 pub(crate) struct OptionAndThenSome;
16 impl BindInsteadOfMap for OptionAndThenSome {
17 const TYPE_NAME: &'static str = "Option";
18 const TYPE_QPATH: &'static [&'static str] = &paths::OPTION;
20 const BAD_METHOD_NAME: &'static str = "and_then";
21 const BAD_VARIANT_NAME: &'static str = "Some";
22 const BAD_VARIANT_QPATH: &'static [&'static str] = &paths::OPTION_SOME;
24 const GOOD_METHOD_NAME: &'static str = "map";
27 pub(crate) struct ResultAndThenOk;
29 impl BindInsteadOfMap for ResultAndThenOk {
30 const TYPE_NAME: &'static str = "Result";
31 const TYPE_QPATH: &'static [&'static str] = &paths::RESULT;
33 const BAD_METHOD_NAME: &'static str = "and_then";
34 const BAD_VARIANT_NAME: &'static str = "Ok";
35 const BAD_VARIANT_QPATH: &'static [&'static str] = &paths::RESULT_OK;
37 const GOOD_METHOD_NAME: &'static str = "map";
40 pub(crate) struct ResultOrElseErrInfo;
42 impl BindInsteadOfMap for ResultOrElseErrInfo {
43 const TYPE_NAME: &'static str = "Result";
44 const TYPE_QPATH: &'static [&'static str] = &paths::RESULT;
46 const BAD_METHOD_NAME: &'static str = "or_else";
47 const BAD_VARIANT_NAME: &'static str = "Err";
48 const BAD_VARIANT_QPATH: &'static [&'static str] = &paths::RESULT_ERR;
50 const GOOD_METHOD_NAME: &'static str = "map_err";
53 pub(crate) trait BindInsteadOfMap {
54 const TYPE_NAME: &'static str;
55 const TYPE_QPATH: &'static [&'static str];
57 const BAD_METHOD_NAME: &'static str;
58 const BAD_VARIANT_NAME: &'static str;
59 const BAD_VARIANT_QPATH: &'static [&'static str];
61 const GOOD_METHOD_NAME: &'static str;
63 fn no_op_msg() -> String {
65 "using `{}.{}({})`, which is a no-op",
67 Self::BAD_METHOD_NAME,
68 Self::BAD_VARIANT_NAME
72 fn lint_msg() -> String {
74 "using `{}.{}(|x| {}(y))`, which is more succinctly expressed as `{}(|x| y)`",
76 Self::BAD_METHOD_NAME,
77 Self::BAD_VARIANT_NAME,
78 Self::GOOD_METHOD_NAME
82 fn lint_closure_autofixable(
85 args: &[hir::Expr<'_>],
86 closure_expr: &hir::Expr<'_>,
87 closure_args_span: Span,
90 if let hir::ExprKind::Call(ref some_expr, ref some_args) = closure_expr.kind;
91 if let hir::ExprKind::Path(ref qpath) = some_expr.kind;
92 if match_qpath(qpath, Self::BAD_VARIANT_QPATH);
93 if some_args.len() == 1;
95 let inner_expr = &some_args[0];
97 if contains_return(inner_expr) {
101 let some_inner_snip = if inner_expr.span.from_expansion() {
102 snippet_with_macro_callsite(cx, inner_expr.span, "_")
104 snippet(cx, inner_expr.span, "_")
107 let closure_args_snip = snippet(cx, closure_args_span, "..");
108 let option_snip = snippet(cx, args[0].span, "..");
109 let note = format!("{}.{}({} {})", option_snip, Self::GOOD_METHOD_NAME, closure_args_snip, some_inner_snip);
114 Self::lint_msg().as_ref(),
117 Applicability::MachineApplicable,
126 fn lint_closure(cx: &LateContext<'_>, expr: &hir::Expr<'_>, closure_expr: &hir::Expr<'_>) -> bool {
127 let mut suggs = Vec::new();
128 let can_sugg: bool = find_all_ret_expressions(cx, closure_expr, |ret_expr| {
130 if !in_macro(ret_expr.span);
131 if let hir::ExprKind::Call(ref func_path, ref args) = ret_expr.kind;
132 if let hir::ExprKind::Path(ref qpath) = func_path.kind;
133 if match_qpath(qpath, Self::BAD_VARIANT_QPATH);
135 if !contains_return(&args[0]);
137 suggs.push((ret_expr.span, args[0].span.source_callsite()));
146 span_lint_and_then(cx, BIND_INSTEAD_OF_MAP, expr.span, Self::lint_msg().as_ref(), |diag| {
147 multispan_sugg_with_applicability(
150 Applicability::MachineApplicable,
151 std::iter::once((*method_calls(expr, 1).2.get(0).unwrap(), Self::GOOD_METHOD_NAME.into())).chain(
154 .map(|(span1, span2)| (span1, snippet(cx, span2, "_").into())),
162 /// Lint use of `_.and_then(|x| Some(y))` for `Option`s
163 fn lint(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) -> bool {
164 if !match_type(cx, cx.typeck_results().expr_ty(&args[0]), Self::TYPE_QPATH) {
169 hir::ExprKind::Closure(_, _, body_id, closure_args_span, _) => {
170 let closure_body = cx.tcx.hir().body(body_id);
171 let closure_expr = remove_blocks(&closure_body.value);
173 if Self::lint_closure_autofixable(cx, expr, args, closure_expr, closure_args_span) {
176 Self::lint_closure(cx, expr, closure_expr)
179 // `_.and_then(Some)` case, which is no-op.
180 hir::ExprKind::Path(ref qpath) if match_qpath(qpath, Self::BAD_VARIANT_QPATH) => {
185 Self::no_op_msg().as_ref(),
186 "use the expression directly",
187 snippet(cx, args[0].span, "..").into(),
188 Applicability::MachineApplicable,
197 /// returns `true` if expr contains match expr desugared from try
198 fn contains_try(expr: &hir::Expr<'_>) -> bool {
203 impl<'hir> intravisit::Visitor<'hir> for TryFinder {
204 type Map = Map<'hir>;
206 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
207 intravisit::NestedVisitorMap::None
210 fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
215 hir::ExprKind::Match(_, _, hir::MatchSource::TryDesugar) => self.found = true,
216 _ => intravisit::walk_expr(self, expr),
221 let mut visitor = TryFinder { found: false };
222 visitor.visit_expr(expr);
226 fn find_all_ret_expressions<'hir, F>(_cx: &LateContext<'_>, expr: &'hir hir::Expr<'hir>, callback: F) -> bool
228 F: FnMut(&'hir hir::Expr<'hir>) -> bool,
230 struct RetFinder<F> {
236 struct WithStmtGuarg<'a, F> {
237 val: &'a mut RetFinder<F>,
241 impl<F> RetFinder<F> {
242 fn inside_stmt(&mut self, in_stmt: bool) -> WithStmtGuarg<'_, F> {
243 let prev_in_stmt = std::mem::replace(&mut self.in_stmt, in_stmt);
251 impl<F> std::ops::Deref for WithStmtGuarg<'_, F> {
252 type Target = RetFinder<F>;
254 fn deref(&self) -> &Self::Target {
259 impl<F> std::ops::DerefMut for WithStmtGuarg<'_, F> {
260 fn deref_mut(&mut self) -> &mut Self::Target {
265 impl<F> Drop for WithStmtGuarg<'_, F> {
267 self.val.in_stmt = self.prev_in_stmt;
271 impl<'hir, F: FnMut(&'hir hir::Expr<'hir>) -> bool> intravisit::Visitor<'hir> for RetFinder<F> {
272 type Map = Map<'hir>;
274 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
275 intravisit::NestedVisitorMap::None
278 fn visit_stmt(&mut self, stmt: &'hir hir::Stmt<'_>) {
279 intravisit::walk_stmt(&mut *self.inside_stmt(true), stmt)
282 fn visit_expr(&mut self, expr: &'hir hir::Expr<'_>) {
288 hir::ExprKind::Ret(Some(expr)) => self.inside_stmt(false).visit_expr(expr),
289 _ => intravisit::walk_expr(self, expr),
293 hir::ExprKind::Match(cond, arms, _) => {
294 self.inside_stmt(true).visit_expr(cond);
296 self.visit_expr(arm.body);
299 hir::ExprKind::Block(..) => intravisit::walk_expr(self, expr),
300 hir::ExprKind::Ret(Some(expr)) => self.visit_expr(expr),
301 _ => self.failed |= !(self.cb)(expr),
307 !contains_try(expr) && {
308 let mut ret_finder = RetFinder {
313 ret_finder.visit_expr(expr);