|
| 1 | +use crate::utils::span_lint; |
| 2 | +use if_chain::if_chain; |
| 3 | +use rustc_data_structures::fx::FxHashMap; |
| 4 | +use rustc_hir::{Expr, ExprKind, StmtKind}; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// **What it does:** Checks for functions that expect closures of type |
| 10 | + /// Fn(...) -> Ord where the implemented closure has a semi-colon |
| 11 | + /// at the end of the last statement. |
| 12 | + /// |
| 13 | + /// **Why is this bad?** Likely the semi-colon is unintentional which |
| 14 | + /// returns () instead of the result of last statement. Since () implements Ord |
| 15 | + /// it doesn't cause a compilation error |
| 16 | + /// |
| 17 | + /// **Known problems:** If returning unit is intentional, then there is no |
| 18 | + /// way of specifying this without triggering needless_return lint |
| 19 | + /// |
| 20 | + /// **Example:** |
| 21 | + /// |
| 22 | + /// ```rust |
| 23 | + /// let mut twins = vec!((1,1), (2,2)); |
| 24 | + /// twins.sort_by_key(|x| { x.1; }); |
| 25 | + /// ``` |
| 26 | + pub UNINTENTIONAL_UNIT_RETURN, |
| 27 | + nursery, |
| 28 | + "fn arguments of type Fn(...) -> Once having last statements with a semi-colon, suggesting to remove the semi-colon if it is unintentional." |
| 29 | +} |
| 30 | + |
| 31 | +declare_lint_pass!(UnintentionalUnitReturn => [UNINTENTIONAL_UNIT_RETURN]); |
| 32 | + |
| 33 | +impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnintentionalUnitReturn { |
| 34 | + fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { |
| 35 | + // Whitelist of function_name -> [argument_index] which are checked |
| 36 | + let mut func_args_to_lint = FxHashMap::default(); |
| 37 | + func_args_to_lint.insert("sort_by_key".to_string(), vec![1]); |
| 38 | + |
| 39 | + if_chain! { |
| 40 | + if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind; |
| 41 | + if let Some(arg_indices) = func_args_to_lint.get(&path.ident.to_string()); |
| 42 | + |
| 43 | + then { |
| 44 | + for i in arg_indices { |
| 45 | + if_chain! { |
| 46 | + if *i < args.len(); |
| 47 | + if let ExprKind::Closure(_, _fn_decl, body_id, _span, _) = args[*i].kind; |
| 48 | + let body = cx.tcx.hir().body(body_id); |
| 49 | + if let ExprKind::Block(block, _) = body.value.kind; |
| 50 | + if let Some(stmt) = block.stmts.last(); |
| 51 | + if let StmtKind::Semi(_) = stmt.kind; |
| 52 | + then { |
| 53 | + //TODO : Maybe only filter the closures where the last statement return type also is an unit |
| 54 | + span_lint(cx, |
| 55 | + UNINTENTIONAL_UNIT_RETURN, |
| 56 | + stmt.span, |
| 57 | + "Semi-colon on the last line of this closure returns \ |
| 58 | + the unit type which also implements Ord."); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments