]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs
Merge commit 'da5a6fb1b65ec6581a67e942a3850f6bc15a552c' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / unit_return_expecting_ord.rs
1 use crate::utils::{get_trait_def_id, paths, span_lint, span_lint_and_help};
2 use if_chain::if_chain;
3 use rustc_hir::def_id::DefId;
4 use rustc_hir::{Expr, ExprKind, StmtKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::ty;
7 use rustc_middle::ty::{GenericPredicates, PredicateKind, ProjectionPredicate, TraitPredicate};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::{BytePos, Span};
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for functions that expect closures of type
13     /// Fn(...) -> Ord where the implemented closure returns the unit type.
14     /// The lint also suggests to remove the semi-colon at the end of the statement if present.
15     ///
16     /// **Why is this bad?** Likely, returning the unit type is unintentional, and
17     /// could simply be caused by an extra semi-colon. Since () implements Ord
18     /// it doesn't cause a compilation error.
19     /// This is the same reasoning behind the unit_cmp lint.
20     ///
21     /// **Known problems:** If returning unit is intentional, then there is no
22     /// way of specifying this without triggering needless_return lint
23     ///
24     /// **Example:**
25     ///
26     /// ```rust
27     /// let mut twins = vec!((1,1), (2,2));
28     /// twins.sort_by_key(|x| { x.1; });
29     /// ```
30     pub UNIT_RETURN_EXPECTING_ORD,
31     correctness,
32     "fn arguments of type Fn(...) -> Ord returning the unit type ()."
33 }
34
35 declare_lint_pass!(UnitReturnExpectingOrd => [UNIT_RETURN_EXPECTING_ORD]);
36
37 fn get_trait_predicates_for_trait_id<'tcx>(
38     cx: &LateContext<'tcx>,
39     generics: GenericPredicates<'tcx>,
40     trait_id: Option<DefId>,
41 ) -> Vec<TraitPredicate<'tcx>> {
42     let mut preds = Vec::new();
43     for (pred, _) in generics.predicates {
44         if_chain! {
45             if let PredicateKind::Trait(poly_trait_pred, _) = pred.kind();
46             let trait_pred = cx.tcx.erase_late_bound_regions(&poly_trait_pred);
47             if let Some(trait_def_id) = trait_id;
48             if trait_def_id == trait_pred.trait_ref.def_id;
49             then {
50                 preds.push(trait_pred);
51             }
52         }
53     }
54     preds
55 }
56
57 fn get_projection_pred<'tcx>(
58     cx: &LateContext<'tcx>,
59     generics: GenericPredicates<'tcx>,
60     pred: TraitPredicate<'tcx>,
61 ) -> Option<ProjectionPredicate<'tcx>> {
62     generics.predicates.iter().find_map(|(proj_pred, _)| {
63         if let PredicateKind::Projection(proj_pred) = proj_pred.kind() {
64             let projection_pred = cx.tcx.erase_late_bound_regions(proj_pred);
65             if projection_pred.projection_ty.substs == pred.trait_ref.substs {
66                 return Some(projection_pred);
67             }
68         }
69         None
70     })
71 }
72
73 fn get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Vec<(usize, String)> {
74     let mut args_to_check = Vec::new();
75     if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
76         let fn_sig = cx.tcx.fn_sig(def_id);
77         let generics = cx.tcx.predicates_of(def_id);
78         let fn_mut_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().fn_mut_trait());
79         let ord_preds = get_trait_predicates_for_trait_id(cx, generics, get_trait_def_id(cx, &paths::ORD));
80         let partial_ord_preds =
81             get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().partial_ord_trait());
82         // Trying to call erase_late_bound_regions on fn_sig.inputs() gives the following error
83         // The trait `rustc::ty::TypeFoldable<'_>` is not implemented for `&[&rustc::ty::TyS<'_>]`
84         let inputs_output = cx.tcx.erase_late_bound_regions(&fn_sig.inputs_and_output());
85         inputs_output
86             .iter()
87             .rev()
88             .skip(1)
89             .rev()
90             .enumerate()
91             .for_each(|(i, inp)| {
92                 for trait_pred in &fn_mut_preds {
93                     if_chain! {
94                         if trait_pred.self_ty() == inp;
95                         if let Some(return_ty_pred) = get_projection_pred(cx, generics, *trait_pred);
96                         then {
97                             if ord_preds.iter().any(|ord| ord.self_ty() == return_ty_pred.ty) {
98                                 args_to_check.push((i, "Ord".to_string()));
99                             } else if partial_ord_preds.iter().any(|pord| pord.self_ty() == return_ty_pred.ty) {
100                                 args_to_check.push((i, "PartialOrd".to_string()));
101                             }
102                         }
103                     }
104                 }
105             });
106     }
107     args_to_check
108 }
109
110 fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> {
111     if_chain! {
112         if let ExprKind::Closure(_, _fn_decl, body_id, span, _) = arg.kind;
113         if let ty::Closure(_def_id, substs) = &cx.typeck_results().node_type(arg.hir_id).kind;
114         let ret_ty = substs.as_closure().sig().output();
115         let ty = cx.tcx.erase_late_bound_regions(&ret_ty);
116         if ty.is_unit();
117         then {
118             if_chain! {
119                 let body = cx.tcx.hir().body(body_id);
120                 if let ExprKind::Block(block, _) = body.value.kind;
121                 if block.expr.is_none();
122                 if let Some(stmt) = block.stmts.last();
123                 if let StmtKind::Semi(_) = stmt.kind;
124                 then {
125                     let data = stmt.span.data();
126                     // Make a span out of the semicolon for the help message
127                     Some((span, Some(Span::new(data.hi-BytePos(1), data.hi, data.ctxt))))
128                 } else {
129                     Some((span, None))
130                 }
131             }
132         } else {
133             None
134         }
135     }
136 }
137
138 impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd {
139     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
140         if let ExprKind::MethodCall(_, _, ref args, _) = expr.kind {
141             let arg_indices = get_args_to_check(cx, expr);
142             for (i, trait_name) in arg_indices {
143                 if i < args.len() {
144                     match check_arg(cx, &args[i]) {
145                         Some((span, None)) => {
146                             span_lint(
147                                 cx,
148                                 UNIT_RETURN_EXPECTING_ORD,
149                                 span,
150                                 &format!(
151                                     "this closure returns \
152                                    the unit type which also implements {}",
153                                     trait_name
154                                 ),
155                             );
156                         },
157                         Some((span, Some(last_semi))) => {
158                             span_lint_and_help(
159                                 cx,
160                                 UNIT_RETURN_EXPECTING_ORD,
161                                 span,
162                                 &format!(
163                                     "this closure returns \
164                                    the unit type which also implements {}",
165                                     trait_name
166                                 ),
167                                 Some(last_semi),
168                                 &"probably caused by this trailing semicolon".to_string(),
169                             );
170                         },
171                         None => {},
172                     }
173                 }
174             }
175         }
176     }
177 }