1 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
2 use if_chain::if_chain;
3 use rustc_hir::def_id::DefId;
4 use rustc_hir::{Closure, Expr, ExprKind, StmtKind};
5 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty::{Clause, GenericPredicates, PredicateKind, ProjectionPredicate, TraitPredicate};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::{sym, BytePos, Span};
11 declare_clippy_lint! {
13 /// 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?
18 /// Likely, returning the unit type is unintentional, and
19 /// could simply be caused by an extra semi-colon. Since () implements Ord
20 /// it doesn't cause a compilation error.
21 /// This is the same reasoning behind the unit_cmp lint.
23 /// ### Known problems
24 /// If returning unit is intentional, then there is no
25 /// way of specifying this without triggering needless_return lint
29 /// let mut twins = vec!((1, 1), (2, 2));
30 /// twins.sort_by_key(|x| { x.1; });
32 #[clippy::version = "1.47.0"]
33 pub UNIT_RETURN_EXPECTING_ORD,
35 "fn arguments of type Fn(...) -> Ord returning the unit type ()."
38 declare_lint_pass!(UnitReturnExpectingOrd => [UNIT_RETURN_EXPECTING_ORD]);
40 fn get_trait_predicates_for_trait_id<'tcx>(
41 cx: &LateContext<'tcx>,
42 generics: GenericPredicates<'tcx>,
43 trait_id: Option<DefId>,
44 ) -> Vec<TraitPredicate<'tcx>> {
45 let mut preds = Vec::new();
46 for (pred, _) in generics.predicates {
48 if let PredicateKind::Clause(Clause::Trait(poly_trait_pred)) = pred.kind().skip_binder();
49 let trait_pred = cx.tcx.erase_late_bound_regions(pred.kind().rebind(poly_trait_pred));
50 if let Some(trait_def_id) = trait_id;
51 if trait_def_id == trait_pred.trait_ref.def_id;
53 preds.push(trait_pred);
60 fn get_projection_pred<'tcx>(
61 cx: &LateContext<'tcx>,
62 generics: GenericPredicates<'tcx>,
63 trait_pred: TraitPredicate<'tcx>,
64 ) -> Option<ProjectionPredicate<'tcx>> {
65 generics.predicates.iter().find_map(|(proj_pred, _)| {
66 if let ty::PredicateKind::Clause(Clause::Projection(pred)) = proj_pred.kind().skip_binder() {
67 let projection_pred = cx.tcx.erase_late_bound_regions(proj_pred.kind().rebind(pred));
68 if projection_pred.projection_ty.substs == trait_pred.trait_ref.substs {
69 return Some(projection_pred);
76 fn get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Vec<(usize, String)> {
77 let mut args_to_check = Vec::new();
78 if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
79 let fn_sig = cx.tcx.fn_sig(def_id);
80 let generics = cx.tcx.predicates_of(def_id);
81 let fn_mut_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().fn_mut_trait());
82 let ord_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.get_diagnostic_item(sym::Ord));
83 let partial_ord_preds =
84 get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().partial_ord_trait());
85 // Trying to call erase_late_bound_regions on fn_sig.inputs() gives the following error
86 // The trait `rustc::ty::TypeFoldable<'_>` is not implemented for
87 // `&[rustc_middle::ty::Ty<'_>]`
88 let inputs_output = cx.tcx.erase_late_bound_regions(fn_sig.inputs_and_output());
95 .for_each(|(i, inp)| {
96 for trait_pred in &fn_mut_preds {
98 if trait_pred.self_ty() == inp;
99 if let Some(return_ty_pred) = get_projection_pred(cx, generics, *trait_pred);
103 .any(|ord| Some(ord.self_ty()) == return_ty_pred.term.ty())
105 args_to_check.push((i, "Ord".to_string()));
106 } else if partial_ord_preds
108 .any(|pord| pord.self_ty() == return_ty_pred.term.ty().unwrap())
110 args_to_check.push((i, "PartialOrd".to_string()));
120 fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> {
122 if let ExprKind::Closure(&Closure { body, fn_decl_span, .. }) = arg.kind;
123 if let ty::Closure(_def_id, substs) = &cx.typeck_results().node_type(arg.hir_id).kind();
124 let ret_ty = substs.as_closure().sig().output();
125 let ty = cx.tcx.erase_late_bound_regions(ret_ty);
128 let body = cx.tcx.hir().body(body);
130 if let ExprKind::Block(block, _) = body.value.kind;
131 if block.expr.is_none();
132 if let Some(stmt) = block.stmts.last();
133 if let StmtKind::Semi(_) = stmt.kind;
135 let data = stmt.span.data();
136 // Make a span out of the semicolon for the help message
137 Some((fn_decl_span, Some(data.with_lo(data.hi-BytePos(1)))))
139 Some((fn_decl_span, None))
148 impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd {
149 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
150 if let ExprKind::MethodCall(_, receiver, args, _) = expr.kind {
151 let arg_indices = get_args_to_check(cx, expr);
152 let args = std::iter::once(receiver).chain(args.iter()).collect::<Vec<_>>();
153 for (i, trait_name) in arg_indices {
155 match check_arg(cx, args[i]) {
156 Some((span, None)) => {
159 UNIT_RETURN_EXPECTING_ORD,
162 "this closure returns \
163 the unit type which also implements {trait_name}"
167 Some((span, Some(last_semi))) => {
170 UNIT_RETURN_EXPECTING_ORD,
173 "this closure returns \
174 the unit type which also implements {trait_name}"
177 "probably caused by this trailing semicolon",