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! {
14 /// Checks for functions that expect closures of type
15 /// Fn(...) -> Ord where the implemented closure returns the unit type.
16 /// The lint also suggests to remove the semi-colon at the end of the statement if present.
18 /// ### Why is this bad?
19 /// Likely, returning the unit type is unintentional, and
20 /// could simply be caused by an extra semi-colon. Since () implements Ord
21 /// it doesn't cause a compilation error.
22 /// This is the same reasoning behind the unit_cmp lint.
24 /// ### Known problems
25 /// If returning unit is intentional, then there is no
26 /// way of specifying this without triggering needless_return lint
30 /// let mut twins = vec!((1, 1), (2, 2));
31 /// twins.sort_by_key(|x| { x.1; });
33 #[clippy::version = "1.47.0"]
34 pub UNIT_RETURN_EXPECTING_ORD,
36 "fn arguments of type Fn(...) -> Ord returning the unit type ()."
39 declare_lint_pass!(UnitReturnExpectingOrd => [UNIT_RETURN_EXPECTING_ORD]);
41 fn get_trait_predicates_for_trait_id<'tcx>(
42 cx: &LateContext<'tcx>,
43 generics: GenericPredicates<'tcx>,
44 trait_id: Option<DefId>,
45 ) -> Vec<TraitPredicate<'tcx>> {
46 let mut preds = Vec::new();
47 for (pred, _) in generics.predicates {
49 if let PredicateKind::Trait(poly_trait_pred) = pred.kind().skip_binder();
50 let trait_pred = cx.tcx.erase_late_bound_regions(pred.kind().rebind(poly_trait_pred));
51 if let Some(trait_def_id) = trait_id;
52 if trait_def_id == trait_pred.trait_ref.def_id;
54 preds.push(trait_pred);
61 fn get_projection_pred<'tcx>(
62 cx: &LateContext<'tcx>,
63 generics: GenericPredicates<'tcx>,
64 trait_pred: TraitPredicate<'tcx>,
65 ) -> Option<ProjectionPredicate<'tcx>> {
66 generics.predicates.iter().find_map(|(proj_pred, _)| {
67 if let ty::PredicateKind::Projection(pred) = proj_pred.kind().skip_binder() {
68 let projection_pred = cx.tcx.erase_late_bound_regions(proj_pred.kind().rebind(pred));
69 if projection_pred.projection_ty.substs == trait_pred.trait_ref.substs {
70 return Some(projection_pred);
77 fn get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Vec<(usize, String)> {
78 let mut args_to_check = Vec::new();
79 if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
80 let fn_sig = cx.tcx.fn_sig(def_id);
81 let generics = cx.tcx.predicates_of(def_id);
82 let fn_mut_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().fn_mut_trait());
83 let ord_preds = get_trait_predicates_for_trait_id(cx, generics, get_trait_def_id(cx, &paths::ORD));
84 let partial_ord_preds =
85 get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().partial_ord_trait());
86 // Trying to call erase_late_bound_regions on fn_sig.inputs() gives the following error
87 // The trait `rustc::ty::TypeFoldable<'_>` is not implemented for `&[&rustc::ty::TyS<'_>]`
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);
101 if ord_preds.iter().any(|ord| Some(ord.self_ty()) == return_ty_pred.term.ty()) {
102 args_to_check.push((i, "Ord".to_string()));
103 } else if partial_ord_preds.iter().any(|pord| {
104 pord.self_ty() == return_ty_pred.term.ty().unwrap()
106 args_to_check.push((i, "PartialOrd".to_string()));
116 fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> {
118 if let ExprKind::Closure(_, _fn_decl, body_id, span, _) = arg.kind;
119 if let ty::Closure(_def_id, substs) = &cx.typeck_results().node_type(arg.hir_id).kind();
120 let ret_ty = substs.as_closure().sig().output();
121 let ty = cx.tcx.erase_late_bound_regions(ret_ty);
124 let body = cx.tcx.hir().body(body_id);
126 if let ExprKind::Block(block, _) = body.value.kind;
127 if block.expr.is_none();
128 if let Some(stmt) = block.stmts.last();
129 if let StmtKind::Semi(_) = stmt.kind;
131 let data = stmt.span.data();
132 // Make a span out of the semicolon for the help message
133 Some((span, Some(data.with_lo(data.hi-BytePos(1)))))
144 impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd {
145 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
146 if let ExprKind::MethodCall(_, args, _) = expr.kind {
147 let arg_indices = get_args_to_check(cx, expr);
148 for (i, trait_name) in arg_indices {
150 match check_arg(cx, &args[i]) {
151 Some((span, None)) => {
154 UNIT_RETURN_EXPECTING_ORD,
157 "this closure returns \
158 the unit type which also implements {}",
163 Some((span, Some(last_semi))) => {
166 UNIT_RETURN_EXPECTING_ORD,
169 "this closure returns \
170 the unit type which also implements {}",
174 "probably caused by this trailing semicolon",