Skip to content

Commit a914f37

Browse files
committed
Add lint against Iterator::map receiving a callable that returns ()
1 parent 8b1dbf7 commit a914f37

File tree

6 files changed

+134
-1
lines changed

6 files changed

+134
-1
lines changed

compiler/rustc_lint/locales/en-US.ftl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ lint_for_loops_over_fallibles =
2424
.use_while_let = to check pattern in a loop use `while let`
2525
.use_question_mark = consider unwrapping the `Result` with `?` to iterate over its contents
2626
27+
lint_map_unit_fn = `Iterator::map` call that discard the iterator's values
28+
.note = `Iterator::map`, like many of the methods on `Iterator`, gets executed lazily, meaning that its effects won't be visible until it is iterated
29+
.function_label = this function returns `()`, which is likely not what you wanted
30+
.argument_label = called `Iterator::map` with callable that returns `()`
31+
.map_label = after this call to map, the resulting iterator is `impl Iterator<Item = ()>`, which means the only information carried by the iterator is the number of items
32+
.suggestion = you might have meant to use `Iterator::for_each`
33+
2734
lint_non_binding_let_on_sync_lock =
2835
non-binding let on a synchronization lock
2936

compiler/rustc_lint/src/lib.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ mod late;
6363
mod let_underscore;
6464
mod levels;
6565
mod lints;
66+
mod map_unit_fn;
6667
mod methods;
6768
mod multiple_supertrait_upcastable;
6869
mod non_ascii_idents;
@@ -100,6 +101,7 @@ use for_loops_over_fallibles::*;
100101
use hidden_unicode_codepoints::*;
101102
use internal::*;
102103
use let_underscore::*;
104+
use map_unit_fn::*;
103105
use methods::*;
104106
use multiple_supertrait_upcastable::*;
105107
use non_ascii_idents::*;
@@ -239,6 +241,7 @@ late_lint_methods!(
239241
NamedAsmLabels: NamedAsmLabels,
240242
OpaqueHiddenInferredBound: OpaqueHiddenInferredBound,
241243
MultipleSupertraitUpcastable: MultipleSupertraitUpcastable,
244+
MapUnitFn: MapUnitFn,
242245
]
243246
]
244247
);
@@ -298,7 +301,8 @@ fn register_builtins(store: &mut LintStore) {
298301
UNUSED_LABELS,
299302
UNUSED_PARENS,
300303
UNUSED_BRACES,
301-
REDUNDANT_SEMICOLONS
304+
REDUNDANT_SEMICOLONS,
305+
MAP_UNIT_FN
302306
);
303307

304308
add_lint_group!("let_underscore", LET_UNDERSCORE_DROP, LET_UNDERSCORE_LOCK);

compiler/rustc_lint/src/lints.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -748,6 +748,22 @@ impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub {
748748
}
749749
}
750750

751+
// map_unit_fn.rs
752+
#[derive(LintDiagnostic)]
753+
#[diag(lint_map_unit_fn)]
754+
#[note]
755+
pub struct MappingToUnit {
756+
#[label(lint_function_label)]
757+
pub function_label: Span,
758+
#[label(lint_argument_label)]
759+
pub argument_label: Span,
760+
#[label(lint_map_label)]
761+
pub map_label: Span,
762+
#[suggestion(style = "verbose", code = "{replace}", applicability = "maybe-incorrect")]
763+
pub suggestion: Span,
764+
pub replace: String,
765+
}
766+
751767
// internal.rs
752768
#[derive(LintDiagnostic)]
753769
#[diag(lint_default_hash_types)]
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
use crate::lints::MappingToUnit;
2+
use crate::{LateContext, LateLintPass, LintContext};
3+
4+
use rustc_hir::{Expr, ExprKind, HirId, Stmt, StmtKind};
5+
use rustc_middle::{
6+
query::Key,
7+
ty::{self, Ty},
8+
};
9+
10+
declare_lint! {
11+
/// The `map_unit_fn` lint checks for `Iterator::map` receive
12+
/// a callable that returns `()`.
13+
///
14+
/// ### Example
15+
///
16+
/// ```rust
17+
/// fn foo(items: &mut Vec<u8>) {
18+
/// items.sort();
19+
/// }
20+
///
21+
/// fn main() {
22+
/// let mut x: Vec<Vec<u8>> = vec![
23+
/// vec![0, 2, 1],
24+
/// vec![5, 4, 3],
25+
/// ];
26+
/// x.iter_mut().map(foo);
27+
/// }
28+
/// ```
29+
///
30+
/// {{produces}}
31+
///
32+
/// ### Explanation
33+
///
34+
/// Mapping to `()` is almost always a mistake.
35+
pub MAP_UNIT_FN,
36+
Warn,
37+
"`Iterator::map` call that discard the iterator's values"
38+
}
39+
40+
declare_lint_pass!(MapUnitFn => [MAP_UNIT_FN]);
41+
42+
impl<'tcx> LateLintPass<'tcx> for MapUnitFn {
43+
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &Stmt<'_>) {
44+
if stmt.span.from_expansion() {
45+
return;
46+
}
47+
48+
if let StmtKind::Semi(expr) = stmt.kind {
49+
if let ExprKind::MethodCall(path, receiver, args, span) = expr.kind {
50+
if path.ident.name.as_str() == "map" {
51+
if receiver.span.from_expansion()
52+
|| args.iter().any(|e| e.span.from_expansion())
53+
|| !is_impl_slice(cx, receiver)
54+
|| !is_diagnostic_name(cx, expr.hir_id, "IteratorMap")
55+
{
56+
return;
57+
}
58+
let arg_ty = cx.typeck_results().expr_ty(&args[0]);
59+
if let ty::FnDef(id, _) = arg_ty.kind() {
60+
let fn_ty = cx.tcx.fn_sig(id).skip_binder();
61+
let ret_ty = fn_ty.output().skip_binder();
62+
if is_unit_type(ret_ty) {
63+
cx.emit_spanned_lint(
64+
MAP_UNIT_FN,
65+
span,
66+
MappingToUnit {
67+
function_label: cx.tcx.span_of_impl(*id).unwrap(),
68+
argument_label: args[0].span,
69+
map_label: arg_ty.default_span(cx.tcx),
70+
suggestion: path.ident.span,
71+
replace: "for_each".to_string(),
72+
},
73+
)
74+
}
75+
}
76+
}
77+
}
78+
}
79+
}
80+
}
81+
82+
fn is_impl_slice(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
83+
if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
84+
if let Some(impl_id) = cx.tcx.impl_of_method(method_id) {
85+
return cx.tcx.type_of(impl_id).skip_binder().is_slice();
86+
}
87+
}
88+
false
89+
}
90+
91+
fn is_unit_type(ty: Ty<'_>) -> bool {
92+
ty.is_unit() || ty.is_never()
93+
}
94+
95+
fn is_diagnostic_name(cx: &LateContext<'_>, id: HirId, name: &str) -> bool {
96+
if let Some(def_id) = cx.typeck_results().type_dependent_def_id(id) {
97+
if let Some(item) = cx.tcx.get_diagnostic_name(def_id) {
98+
if item.as_str() == name {
99+
return true;
100+
}
101+
}
102+
}
103+
false
104+
}

library/core/src/iter/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,7 @@
278278
//!
279279
//! ```
280280
//! # #![allow(unused_must_use)]
281+
//! # #![cfg_attr(not(bootstrap), allow(map_unit_fn))]
281282
//! let v = vec![1, 2, 3, 4, 5];
282283
//! v.iter().map(|x| println!("{x}"));
283284
//! ```

library/core/src/iter/traits/iterator.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,7 @@ pub trait Iterator {
777777
/// println!("{x}");
778778
/// }
779779
/// ```
780+
#[rustc_diagnostic_item = "IteratorMap"]
780781
#[inline]
781782
#[stable(feature = "rust1", since = "1.0.0")]
782783
fn map<B, F>(self, f: F) -> Map<Self, F>

0 commit comments

Comments
 (0)