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