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};
6 use rustc_middle::ty;
7 use rustc_middle::ty::{ClauseKind, GenericPredicates, ProjectionPredicate, TraitPredicate};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::{sym, BytePos, Span};
10
11 declare_clippy_lint! {
12 /// ### What it does
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.
16 ///
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.
22 ///
23 /// ### Known problems
24 /// If returning unit is intentional, then there is no
25 /// way of specifying this without triggering needless_return lint
26 ///
27 /// ### Example
28 /// ```rust
29 /// let mut twins = vec!((1, 1), (2, 2));
30 /// twins.sort_by_key(|x| { x.1; });
31 /// ```
32 #[clippy::version = "1.47.0"]
33 pub UNIT_RETURN_EXPECTING_ORD,
34 correctness,
35 "fn arguments of type Fn(...) -> Ord returning the unit type ()."
36 }
37
38 declare_lint_pass!(UnitReturnExpectingOrd => [UNIT_RETURN_EXPECTING_ORD]);
39
get_trait_predicates_for_trait_id<'tcx>( cx: &LateContext<'tcx>, generics: GenericPredicates<'tcx>, trait_id: Option<DefId>, ) -> Vec<TraitPredicate<'tcx>>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 {
47 if_chain! {
48 if let ClauseKind::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;
52 then {
53 preds.push(trait_pred);
54 }
55 }
56 }
57 preds
58 }
59
get_projection_pred<'tcx>( cx: &LateContext<'tcx>, generics: GenericPredicates<'tcx>, trait_pred: TraitPredicate<'tcx>, ) -> Option<ProjectionPredicate<'tcx>>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 ClauseKind::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);
70 }
71 }
72 None
73 })
74 }
75
get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Vec<(usize, String)>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).subst_identity();
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());
89 inputs_output
90 .iter()
91 .rev()
92 .skip(1)
93 .rev()
94 .enumerate()
95 .for_each(|(i, inp)| {
96 for trait_pred in &fn_mut_preds {
97 if_chain! {
98 if trait_pred.self_ty() == inp;
99 if let Some(return_ty_pred) = get_projection_pred(cx, generics, *trait_pred);
100 then {
101 if ord_preds
102 .iter()
103 .any(|ord| Some(ord.self_ty()) == return_ty_pred.term.ty())
104 {
105 args_to_check.push((i, "Ord".to_string()));
106 } else if partial_ord_preds
107 .iter()
108 .any(|pord| pord.self_ty() == return_ty_pred.term.ty().unwrap())
109 {
110 args_to_check.push((i, "PartialOrd".to_string()));
111 }
112 }
113 }
114 }
115 });
116 }
117 args_to_check
118 }
119
check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)>120 fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> {
121 if_chain! {
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);
126 if ty.is_unit();
127 then {
128 let body = cx.tcx.hir().body(body);
129 if_chain! {
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;
134 then {
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)))))
138 } else {
139 Some((fn_decl_span, None))
140 }
141 }
142 } else {
143 None
144 }
145 }
146 }
147
148 impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>)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 {
154 if i < args.len() {
155 match check_arg(cx, args[i]) {
156 Some((span, None)) => {
157 span_lint(
158 cx,
159 UNIT_RETURN_EXPECTING_ORD,
160 span,
161 &format!(
162 "this closure returns \
163 the unit type which also implements {trait_name}"
164 ),
165 );
166 },
167 Some((span, Some(last_semi))) => {
168 span_lint_and_help(
169 cx,
170 UNIT_RETURN_EXPECTING_ORD,
171 span,
172 &format!(
173 "this closure returns \
174 the unit type which also implements {trait_name}"
175 ),
176 Some(last_semi),
177 "probably caused by this trailing semicolon",
178 );
179 },
180 None => {},
181 }
182 }
183 }
184 }
185 }
186 }
187