1 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
2 use clippy_utils::{get_trait_def_id, paths};
3 use if_chain::if_chain;
4 use rustc_hir::def_id::DefId;
5 use rustc_hir::{Expr, ExprKind, StmtKind};
6 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty::{GenericPredicates, PredicateKind, ProjectionPredicate, TraitPredicate};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::{BytePos, Span};
12 declare_clippy_lint! {
13 /// **What it does:** Checks for functions that expect closures of type
14 /// Fn(...) -> Ord where the implemented closure returns the unit type.
15 /// The lint also suggests to remove the semi-colon at the end of the statement if present.
17 /// **Why is this bad?** Likely, returning the unit type is unintentional, and
18 /// could simply be caused by an extra semi-colon. Since () implements Ord
19 /// it doesn't cause a compilation error.
20 /// This is the same reasoning behind the unit_cmp lint.
22 /// **Known problems:** If returning unit is intentional, then there is no
23 /// way of specifying this without triggering needless_return lint
28 /// let mut twins = vec!((1, 1), (2, 2));
29 /// twins.sort_by_key(|x| { x.1; });
31 pub UNIT_RETURN_EXPECTING_ORD,
33 "fn arguments of type Fn(...) -> Ord returning the unit type ()."
36 declare_lint_pass!(UnitReturnExpectingOrd => [UNIT_RETURN_EXPECTING_ORD]);
38 fn get_trait_predicates_for_trait_id<'tcx>(
39 cx: &LateContext<'tcx>,
40 generics: GenericPredicates<'tcx>,
41 trait_id: Option<DefId>,
42 ) -> Vec<TraitPredicate<'tcx>> {
43 let mut preds = Vec::new();
44 for (pred, _) in generics.predicates {
46 if let PredicateKind::Trait(poly_trait_pred, _) = pred.kind().skip_binder();
47 let trait_pred = cx.tcx.erase_late_bound_regions(pred.kind().rebind(poly_trait_pred));
48 if let Some(trait_def_id) = trait_id;
49 if trait_def_id == trait_pred.trait_ref.def_id;
51 preds.push(trait_pred);
58 fn get_projection_pred<'tcx>(
59 cx: &LateContext<'tcx>,
60 generics: GenericPredicates<'tcx>,
61 trait_pred: TraitPredicate<'tcx>,
62 ) -> Option<ProjectionPredicate<'tcx>> {
63 generics.predicates.iter().find_map(|(proj_pred, _)| {
64 if let ty::PredicateKind::Projection(pred) = proj_pred.kind().skip_binder() {
65 let projection_pred = cx.tcx.erase_late_bound_regions(proj_pred.kind().rebind(pred));
66 if projection_pred.projection_ty.substs == trait_pred.trait_ref.substs {
67 return Some(projection_pred);
74 fn get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Vec<(usize, String)> {
75 let mut args_to_check = Vec::new();
76 if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
77 let fn_sig = cx.tcx.fn_sig(def_id);
78 let generics = cx.tcx.predicates_of(def_id);
79 let fn_mut_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().fn_mut_trait());
80 let ord_preds = get_trait_predicates_for_trait_id(cx, generics, get_trait_def_id(cx, &paths::ORD));
81 let partial_ord_preds =
82 get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().partial_ord_trait());
83 // Trying to call erase_late_bound_regions on fn_sig.inputs() gives the following error
84 // The trait `rustc::ty::TypeFoldable<'_>` is not implemented for `&[&rustc::ty::TyS<'_>]`
85 let inputs_output = cx.tcx.erase_late_bound_regions(fn_sig.inputs_and_output());
92 .for_each(|(i, inp)| {
93 for trait_pred in &fn_mut_preds {
95 if trait_pred.self_ty() == inp;
96 if let Some(return_ty_pred) = get_projection_pred(cx, generics, *trait_pred);
98 if ord_preds.iter().any(|ord| ord.self_ty() == return_ty_pred.ty) {
99 args_to_check.push((i, "Ord".to_string()));
100 } else if partial_ord_preds.iter().any(|pord| pord.self_ty() == return_ty_pred.ty) {
101 args_to_check.push((i, "PartialOrd".to_string()));
111 fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> {
113 if let ExprKind::Closure(_, _fn_decl, body_id, span, _) = arg.kind;
114 if let ty::Closure(_def_id, substs) = &cx.typeck_results().node_type(arg.hir_id).kind();
115 let ret_ty = substs.as_closure().sig().output();
116 let ty = cx.tcx.erase_late_bound_regions(ret_ty);
119 let body = cx.tcx.hir().body(body_id);
121 if let ExprKind::Block(block, _) = body.value.kind;
122 if block.expr.is_none();
123 if let Some(stmt) = block.stmts.last();
124 if let StmtKind::Semi(_) = stmt.kind;
126 let data = stmt.span.data();
127 // Make a span out of the semicolon for the help message
128 Some((span, Some(Span::new(data.hi-BytePos(1), data.hi, data.ctxt))))
139 impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd {
140 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
141 if let ExprKind::MethodCall(_, _, args, _) = expr.kind {
142 let arg_indices = get_args_to_check(cx, expr);
143 for (i, trait_name) in arg_indices {
145 match check_arg(cx, &args[i]) {
146 Some((span, None)) => {
149 UNIT_RETURN_EXPECTING_ORD,
152 "this closure returns \
153 the unit type which also implements {}",
158 Some((span, Some(last_semi))) => {
161 UNIT_RETURN_EXPECTING_ORD,
164 "this closure returns \
165 the unit type which also implements {}",
169 &"probably caused by this trailing semicolon".to_string(),