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};
7 use rustc_middle::ty::{GenericPredicates, PredicateAtom, ProjectionPredicate, TraitPredicate};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::{BytePos, Span};
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.
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.
21 /// **Known problems:** If returning unit is intentional, then there is no
22 /// way of specifying this without triggering needless_return lint
27 /// let mut twins = vec!((1,1), (2,2));
28 /// twins.sort_by_key(|x| { x.1; });
30 pub UNIT_RETURN_EXPECTING_ORD,
32 "fn arguments of type Fn(...) -> Ord returning the unit type ()."
35 declare_lint_pass!(UnitReturnExpectingOrd => [UNIT_RETURN_EXPECTING_ORD]);
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 {
45 if let PredicateAtom::Trait(poly_trait_pred, _) = pred.skip_binders();
46 let trait_pred = cx.tcx.erase_late_bound_regions(&ty::Binder::bind(poly_trait_pred));
47 if let Some(trait_def_id) = trait_id;
48 if trait_def_id == trait_pred.trait_ref.def_id;
50 preds.push(trait_pred);
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 ty::PredicateAtom::Projection(proj_pred) = proj_pred.skip_binders() {
64 let projection_pred = cx.tcx.erase_late_bound_regions(&ty::Binder::bind(proj_pred));
65 if projection_pred.projection_ty.substs == pred.trait_ref.substs {
66 return Some(projection_pred);
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());
91 .for_each(|(i, inp)| {
92 for trait_pred in &fn_mut_preds {
94 if trait_pred.self_ty() == inp;
95 if let Some(return_ty_pred) = get_projection_pred(cx, generics, *trait_pred);
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()));
110 fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> {
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);
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;
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))))
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 {
144 match check_arg(cx, &args[i]) {
145 Some((span, None)) => {
148 UNIT_RETURN_EXPECTING_ORD,
151 "this closure returns \
152 the unit type which also implements {}",
157 Some((span, Some(last_semi))) => {
160 UNIT_RETURN_EXPECTING_ORD,
163 "this closure returns \
164 the unit type which also implements {}",
168 &"probably caused by this trailing semicolon".to_string(),