]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs
Auto merge of #93312 - pierwill:map-all-local-trait-impls, r=cjgillot
[rust.git] / src / tools / clippy / 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 `&[&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| Some(ord.self_ty()) == return_ty_pred.term.ty()) {
102                                 args_to_check.push((i, "Ord".to_string()));
103                             } else if partial_ord_preds.iter().any(|pord| {
104                                 pord.self_ty() == return_ty_pred.term.ty().unwrap()
105                             }) {
106                                 args_to_check.push((i, "PartialOrd".to_string()));
107                             }
108                         }
109                     }
110                 }
111             });
112     }
113     args_to_check
114 }
115
116 fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> {
117     if_chain! {
118         if let ExprKind::Closure(_, _fn_decl, body_id, span, _) = arg.kind;
119         if let ty::Closure(_def_id, substs) = &cx.typeck_results().node_type(arg.hir_id).kind();
120         let ret_ty = substs.as_closure().sig().output();
121         let ty = cx.tcx.erase_late_bound_regions(ret_ty);
122         if ty.is_unit();
123         then {
124             let body = cx.tcx.hir().body(body_id);
125             if_chain! {
126                 if let ExprKind::Block(block, _) = body.value.kind;
127                 if block.expr.is_none();
128                 if let Some(stmt) = block.stmts.last();
129                 if let StmtKind::Semi(_) = stmt.kind;
130                 then {
131                     let data = stmt.span.data();
132                     // Make a span out of the semicolon for the help message
133                     Some((span, Some(data.with_lo(data.hi-BytePos(1)))))
134                 } else {
135                     Some((span, None))
136                 }
137             }
138         } else {
139             None
140         }
141     }
142 }
143
144 impl<'tcx> LateLintPass<'tcx> for UnitReturnExpectingOrd {
145     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
146         if let ExprKind::MethodCall(_, args, _) = expr.kind {
147             let arg_indices = get_args_to_check(cx, expr);
148             for (i, trait_name) in arg_indices {
149                 if i < args.len() {
150                     match check_arg(cx, &args[i]) {
151                         Some((span, None)) => {
152                             span_lint(
153                                 cx,
154                                 UNIT_RETURN_EXPECTING_ORD,
155                                 span,
156                                 &format!(
157                                     "this closure returns \
158                                    the unit type which also implements {}",
159                                     trait_name
160                                 ),
161                             );
162                         },
163                         Some((span, Some(last_semi))) => {
164                             span_lint_and_help(
165                                 cx,
166                                 UNIT_RETURN_EXPECTING_ORD,
167                                 span,
168                                 &format!(
169                                     "this closure returns \
170                                    the unit type which also implements {}",
171                                     trait_name
172                                 ),
173                                 Some(last_semi),
174                                 "probably caused by this trailing semicolon",
175                             );
176                         },
177                         None => {},
178                     }
179                 }
180             }
181         }
182     }
183 }