Skip to content

Commit 97d7a8b

Browse files
committed
Auto merge of rust-lang#5737 - Uriopass:unit-for-ord, r=flip1995
Reprise: new lint: Unintentional return of unit from closures expecting Ord This lint catches cases where the last statement of a closure expecting an instance of Ord has a trailing semi-colon. It compiles since the closure ends up return () which also implements Ord but causes unexpected results in cases such as sort_by_key. Fixes rust-lang#5080 Reprise of rust-lang#5348 where I addressed all the comments there changelog: add lint [`unit_return_expecting_ord`]
2 parents 2ca58e7 + 1267909 commit 97d7a8b

File tree

6 files changed

+265
-0
lines changed

6 files changed

+265
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1679,6 +1679,7 @@ Released 2018-09-13
16791679
[`uninit_assumed_init`]: https://rust-lang.github.io/rust-clippy/master/index.html#uninit_assumed_init
16801680
[`unit_arg`]: https://rust-lang.github.io/rust-clippy/master/index.html#unit_arg
16811681
[`unit_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#unit_cmp
1682+
[`unit_return_expecting_ord`]: https://rust-lang.github.io/rust-clippy/master/index.html#unit_return_expecting_ord
16821683
[`unknown_clippy_lints`]: https://rust-lang.github.io/rust-clippy/master/index.html#unknown_clippy_lints
16831684
[`unnecessary_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
16841685
[`unnecessary_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map

clippy_lints/src/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@ mod trivially_copy_pass_by_ref;
300300
mod try_err;
301301
mod types;
302302
mod unicode;
303+
mod unit_return_expecting_ord;
303304
mod unnamed_address;
304305
mod unnecessary_sort_by;
305306
mod unnested_or_patterns;
@@ -826,6 +827,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
826827
&unicode::NON_ASCII_LITERAL,
827828
&unicode::UNICODE_NOT_NFC,
828829
&unicode::ZERO_WIDTH_SPACE,
830+
&unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD,
829831
&unnamed_address::FN_ADDRESS_COMPARISONS,
830832
&unnamed_address::VTABLE_ADDRESS_COMPARISONS,
831833
&unnecessary_sort_by::UNNECESSARY_SORT_BY,
@@ -891,6 +893,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
891893
store.register_late_pass(|| box attrs::Attributes);
892894
store.register_late_pass(|| box blocks_in_if_conditions::BlocksInIfConditions);
893895
store.register_late_pass(|| box unicode::Unicode);
896+
store.register_late_pass(|| box unit_return_expecting_ord::UnitReturnExpectingOrd);
894897
store.register_late_pass(|| box strings::StringAdd);
895898
store.register_late_pass(|| box implicit_return::ImplicitReturn);
896899
store.register_late_pass(|| box implicit_saturating_sub::ImplicitSaturatingSub);
@@ -1436,6 +1439,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
14361439
LintId::of(&types::UNNECESSARY_CAST),
14371440
LintId::of(&types::VEC_BOX),
14381441
LintId::of(&unicode::ZERO_WIDTH_SPACE),
1442+
LintId::of(&unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD),
14391443
LintId::of(&unnamed_address::FN_ADDRESS_COMPARISONS),
14401444
LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS),
14411445
LintId::of(&unnecessary_sort_by::UNNECESSARY_SORT_BY),
@@ -1692,6 +1696,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
16921696
LintId::of(&types::CAST_REF_TO_MUT),
16931697
LintId::of(&types::UNIT_CMP),
16941698
LintId::of(&unicode::ZERO_WIDTH_SPACE),
1699+
LintId::of(&unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD),
16951700
LintId::of(&unnamed_address::FN_ADDRESS_COMPARISONS),
16961701
LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS),
16971702
LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
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.tables().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.tables().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+
}

src/lintlist/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -2292,6 +2292,13 @@ pub static ref ALL_LINTS: Vec<Lint> = vec![
22922292
deprecation: None,
22932293
module: "types",
22942294
},
2295+
Lint {
2296+
name: "unit_return_expecting_ord",
2297+
group: "correctness",
2298+
desc: "fn arguments of type Fn(...) -> Ord returning the unit type ().",
2299+
deprecation: None,
2300+
module: "unit_return_expecting_ord",
2301+
},
22952302
Lint {
22962303
name: "unknown_clippy_lints",
22972304
group: "style",

tests/ui/unit_return_expecting_ord.rs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#![warn(clippy::unit_return_expecting_ord)]
2+
#![allow(clippy::needless_return)]
3+
#![allow(clippy::unused_unit)]
4+
#![feature(is_sorted)]
5+
6+
struct Struct {
7+
field: isize,
8+
}
9+
10+
fn double(i: isize) -> isize {
11+
i * 2
12+
}
13+
14+
fn unit(_i: isize) {}
15+
16+
fn main() {
17+
let mut structs = vec![Struct { field: 2 }, Struct { field: 1 }];
18+
structs.sort_by_key(|s| {
19+
double(s.field);
20+
});
21+
structs.sort_by_key(|s| double(s.field));
22+
structs.is_sorted_by_key(|s| {
23+
double(s.field);
24+
});
25+
structs.is_sorted_by_key(|s| {
26+
if s.field > 0 {
27+
()
28+
} else {
29+
return ();
30+
}
31+
});
32+
structs.sort_by_key(|s| {
33+
return double(s.field);
34+
});
35+
structs.sort_by_key(|s| unit(s.field));
36+
}
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
error: this closure returns the unit type which also implements Ord
2+
--> $DIR/unit_return_expecting_ord.rs:18:25
3+
|
4+
LL | structs.sort_by_key(|s| {
5+
| ^^^
6+
|
7+
= note: `-D clippy::unit-return-expecting-ord` implied by `-D warnings`
8+
help: probably caused by this trailing semicolon
9+
--> $DIR/unit_return_expecting_ord.rs:19:24
10+
|
11+
LL | double(s.field);
12+
| ^
13+
14+
error: this closure returns the unit type which also implements PartialOrd
15+
--> $DIR/unit_return_expecting_ord.rs:22:30
16+
|
17+
LL | structs.is_sorted_by_key(|s| {
18+
| ^^^
19+
|
20+
help: probably caused by this trailing semicolon
21+
--> $DIR/unit_return_expecting_ord.rs:23:24
22+
|
23+
LL | double(s.field);
24+
| ^
25+
26+
error: this closure returns the unit type which also implements PartialOrd
27+
--> $DIR/unit_return_expecting_ord.rs:25:30
28+
|
29+
LL | structs.is_sorted_by_key(|s| {
30+
| ^^^
31+
32+
error: this closure returns the unit type which also implements Ord
33+
--> $DIR/unit_return_expecting_ord.rs:35:25
34+
|
35+
LL | structs.sort_by_key(|s| unit(s.field));
36+
| ^^^
37+
38+
error: aborting due to 4 previous errors
39+

0 commit comments

Comments
 (0)