]>
Commit | Line | Data |
---|---|---|
cdc7bbd5 XL |
1 | use clippy_utils::diagnostics::{span_lint, span_lint_and_help}; |
2 | use clippy_utils::{get_trait_def_id, paths}; | |
f20569fa XL |
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}; | |
7 | use rustc_middle::ty; | |
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}; | |
11 | ||
12 | declare_clippy_lint! { | |
94222f64 XL |
13 | /// ### What it does |
14 | /// Checks for functions that expect closures of type | |
f20569fa XL |
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. | |
17 | /// | |
94222f64 XL |
18 | /// ### Why is this bad? |
19 | /// Likely, returning the unit type is unintentional, and | |
f20569fa XL |
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. | |
23 | /// | |
94222f64 XL |
24 | /// ### Known problems |
25 | /// If returning unit is intentional, then there is no | |
f20569fa XL |
26 | /// way of specifying this without triggering needless_return lint |
27 | /// | |
94222f64 | 28 | /// ### Example |
f20569fa XL |
29 | /// ```rust |
30 | /// let mut twins = vec!((1, 1), (2, 2)); | |
31 | /// twins.sort_by_key(|x| { x.1; }); | |
32 | /// ``` | |
a2a8927a | 33 | #[clippy::version = "1.47.0"] |
f20569fa XL |
34 | pub UNIT_RETURN_EXPECTING_ORD, |
35 | correctness, | |
36 | "fn arguments of type Fn(...) -> Ord returning the unit type ()." | |
37 | } | |
38 | ||
39 | declare_lint_pass!(UnitReturnExpectingOrd => [UNIT_RETURN_EXPECTING_ORD]); | |
40 | ||
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 { | |
48 | if_chain! { | |
94222f64 | 49 | if let PredicateKind::Trait(poly_trait_pred) = pred.kind().skip_binder(); |
cdc7bbd5 | 50 | let trait_pred = cx.tcx.erase_late_bound_regions(pred.kind().rebind(poly_trait_pred)); |
f20569fa XL |
51 | if let Some(trait_def_id) = trait_id; |
52 | if trait_def_id == trait_pred.trait_ref.def_id; | |
53 | then { | |
54 | preds.push(trait_pred); | |
55 | } | |
56 | } | |
57 | } | |
58 | preds | |
59 | } | |
60 | ||
61 | fn get_projection_pred<'tcx>( | |
62 | cx: &LateContext<'tcx>, | |
63 | generics: GenericPredicates<'tcx>, | |
cdc7bbd5 | 64 | trait_pred: TraitPredicate<'tcx>, |
f20569fa XL |
65 | ) -> Option<ProjectionPredicate<'tcx>> { |
66 | generics.predicates.iter().find_map(|(proj_pred, _)| { | |
cdc7bbd5 XL |
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 { | |
f20569fa XL |
70 | return Some(projection_pred); |
71 | } | |
72 | } | |
73 | None | |
74 | }) | |
75 | } | |
76 | ||
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()); | |
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.iter().any(|ord| ord.self_ty() == return_ty_pred.ty) { | |
102 | args_to_check.push((i, "Ord".to_string())); | |
103 | } else if partial_ord_preds.iter().any(|pord| pord.self_ty() == return_ty_pred.ty) { | |
104 | args_to_check.push((i, "PartialOrd".to_string())); | |
105 | } | |
106 | } | |
107 | } | |
108 | } | |
109 | }); | |
110 | } | |
111 | args_to_check | |
112 | } | |
113 | ||
114 | fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> { | |
115 | if_chain! { | |
116 | if let ExprKind::Closure(_, _fn_decl, body_id, span, _) = arg.kind; | |
117 | if let ty::Closure(_def_id, substs) = &cx.typeck_results().node_type(arg.hir_id).kind(); | |
118 | let ret_ty = substs.as_closure().sig().output(); | |
119 | let ty = cx.tcx.erase_late_bound_regions(ret_ty); | |
120 | if ty.is_unit(); | |
121 | then { | |
cdc7bbd5 | 122 | let body = cx.tcx.hir().body(body_id); |
f20569fa | 123 | if_chain! { |
f20569fa XL |
124 | if let ExprKind::Block(block, _) = body.value.kind; |
125 | if block.expr.is_none(); | |
126 | if let Some(stmt) = block.stmts.last(); | |
127 | if let StmtKind::Semi(_) = stmt.kind; | |
128 | then { | |
129 | let data = stmt.span.data(); | |
130 | // Make a span out of the semicolon for the help message | |
94222f64 | 131 | Some((span, Some(data.with_lo(data.hi-BytePos(1))))) |
f20569fa XL |
132 | } else { |
133 | Some((span, None)) | |
134 | } | |
135 | } | |
136 | } else { | |
137 | None | |
138 | } | |
139 | } | |
140 | } | |
141 | ||
142 | impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd { | |
143 | fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { | |
cdc7bbd5 | 144 | if let ExprKind::MethodCall(_, _, args, _) = expr.kind { |
f20569fa XL |
145 | let arg_indices = get_args_to_check(cx, expr); |
146 | for (i, trait_name) in arg_indices { | |
147 | if i < args.len() { | |
148 | match check_arg(cx, &args[i]) { | |
149 | Some((span, None)) => { | |
150 | span_lint( | |
151 | cx, | |
152 | UNIT_RETURN_EXPECTING_ORD, | |
153 | span, | |
154 | &format!( | |
155 | "this closure returns \ | |
156 | the unit type which also implements {}", | |
157 | trait_name | |
158 | ), | |
159 | ); | |
160 | }, | |
161 | Some((span, Some(last_semi))) => { | |
162 | span_lint_and_help( | |
163 | cx, | |
164 | UNIT_RETURN_EXPECTING_ORD, | |
165 | span, | |
166 | &format!( | |
167 | "this closure returns \ | |
168 | the unit type which also implements {}", | |
169 | trait_name | |
170 | ), | |
171 | Some(last_semi), | |
a2a8927a | 172 | "probably caused by this trailing semicolon", |
f20569fa XL |
173 | ); |
174 | }, | |
175 | None => {}, | |
176 | } | |
177 | } | |
178 | } | |
179 | } | |
180 | } | |
181 | } |