]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/unit_return_expecting_ord.rs
Make `ExprKind::Closure` a struct variant.
[rust.git] / clippy_lints / src / unit_return_expecting_ord.rs
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};
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! {
13     /// ### What it does
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.
17     ///
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.
23     ///
24     /// ### Known problems
25     /// If returning unit is intentional, then there is no
26     /// way of specifying this without triggering needless_return lint
27     ///
28     /// ### Example
29     /// ```rust
30     /// let mut twins = vec!((1, 1), (2, 2));
31     /// twins.sort_by_key(|x| { x.1; });
32     /// ```
33     #[clippy::version = "1.47.0"]
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! {
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;
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>,
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);
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
88         // `&[rustc_middle::ty::Ty<'_>]`
89         let inputs_output = cx.tcx.erase_late_bound_regions(fn_sig.inputs_and_output());
90         inputs_output
91             .iter()
92             .rev()
93             .skip(1)
94             .rev()
95             .enumerate()
96             .for_each(|(i, inp)| {
97                 for trait_pred in &fn_mut_preds {
98                     if_chain! {
99                         if trait_pred.self_ty() == inp;
100                         if let Some(return_ty_pred) = get_projection_pred(cx, generics, *trait_pred);
101                         then {
102                             if ord_preds.iter().any(|ord| Some(ord.self_ty()) == return_ty_pred.term.ty()) {
103                                 args_to_check.push((i, "Ord".to_string()));
104                             } else if partial_ord_preds.iter().any(|pord| {
105                                 pord.self_ty() == return_ty_pred.term.ty().unwrap()
106                             }) {
107                                 args_to_check.push((i, "PartialOrd".to_string()));
108                             }
109                         }
110                     }
111                 }
112             });
113     }
114     args_to_check
115 }
116
117 fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> {
118     if_chain! {
119         if let ExprKind::Closure { body, fn_decl_span, .. } = arg.kind;
120         if let ty::Closure(_def_id, substs) = &cx.typeck_results().node_type(arg.hir_id).kind();
121         let ret_ty = substs.as_closure().sig().output();
122         let ty = cx.tcx.erase_late_bound_regions(ret_ty);
123         if ty.is_unit();
124         then {
125             let body = cx.tcx.hir().body(body);
126             if_chain! {
127                 if let ExprKind::Block(block, _) = body.value.kind;
128                 if block.expr.is_none();
129                 if let Some(stmt) = block.stmts.last();
130                 if let StmtKind::Semi(_) = stmt.kind;
131                 then {
132                     let data = stmt.span.data();
133                     // Make a span out of the semicolon for the help message
134                     Some((fn_decl_span, Some(data.with_lo(data.hi-BytePos(1)))))
135                 } else {
136                     Some((fn_decl_span, None))
137                 }
138             }
139         } else {
140             None
141         }
142     }
143 }
144
145 impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd {
146     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
147         if let ExprKind::MethodCall(_, args, _) = expr.kind {
148             let arg_indices = get_args_to_check(cx, expr);
149             for (i, trait_name) in arg_indices {
150                 if i < args.len() {
151                     match check_arg(cx, &args[i]) {
152                         Some((span, None)) => {
153                             span_lint(
154                                 cx,
155                                 UNIT_RETURN_EXPECTING_ORD,
156                                 span,
157                                 &format!(
158                                     "this closure returns \
159                                    the unit type which also implements {}",
160                                     trait_name
161                                 ),
162                             );
163                         },
164                         Some((span, Some(last_semi))) => {
165                             span_lint_and_help(
166                                 cx,
167                                 UNIT_RETURN_EXPECTING_ORD,
168                                 span,
169                                 &format!(
170                                     "this closure returns \
171                                    the unit type which also implements {}",
172                                     trait_name
173                                 ),
174                                 Some(last_semi),
175                                 "probably caused by this trailing semicolon",
176                             );
177                         },
178                         None => {},
179                     }
180                 }
181             }
182         }
183     }
184 }