-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Lint against Iterator::map
receiving a callable that returns ()
#107890
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a914f37
Add lint against `Iterator::map` receiving a callable that returns `()`
obeis ddd7d10
Add ui test for `map_unit_fn` lint
obeis a87443a
Emit `map_unit_fn` lint in closure case
obeis b93d545
Add ui test for `map_unit_fn` lint in closure case
obeis 99344a8
Add ui test for `E0271` error
obeis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
use crate::lints::MappingToUnit; | ||
use crate::{LateContext, LateLintPass, LintContext}; | ||
|
||
use rustc_hir::{Expr, ExprKind, HirId, Stmt, StmtKind}; | ||
use rustc_middle::{ | ||
query::Key, | ||
ty::{self, Ty}, | ||
}; | ||
|
||
declare_lint! { | ||
/// The `map_unit_fn` lint checks for `Iterator::map` receive | ||
/// a callable that returns `()`. | ||
/// | ||
/// ### Example | ||
/// | ||
/// ```rust | ||
/// fn foo(items: &mut Vec<u8>) { | ||
/// items.sort(); | ||
/// } | ||
/// | ||
/// fn main() { | ||
/// let mut x: Vec<Vec<u8>> = vec![ | ||
/// vec![0, 2, 1], | ||
/// vec![5, 4, 3], | ||
/// ]; | ||
/// x.iter_mut().map(foo); | ||
/// } | ||
/// ``` | ||
/// | ||
/// {{produces}} | ||
/// | ||
/// ### Explanation | ||
/// | ||
/// Mapping to `()` is almost always a mistake. | ||
pub MAP_UNIT_FN, | ||
Warn, | ||
"`Iterator::map` call that discard the iterator's values" | ||
} | ||
|
||
declare_lint_pass!(MapUnitFn => [MAP_UNIT_FN]); | ||
|
||
impl<'tcx> LateLintPass<'tcx> for MapUnitFn { | ||
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &Stmt<'_>) { | ||
if stmt.span.from_expansion() { | ||
return; | ||
} | ||
|
||
if let StmtKind::Semi(expr) = stmt.kind { | ||
if let ExprKind::MethodCall(path, receiver, args, span) = expr.kind { | ||
if path.ident.name.as_str() == "map" { | ||
if receiver.span.from_expansion() | ||
|| args.iter().any(|e| e.span.from_expansion()) | ||
|| !is_impl_slice(cx, receiver) | ||
|| !is_diagnostic_name(cx, expr.hir_id, "IteratorMap") | ||
{ | ||
return; | ||
} | ||
let arg_ty = cx.typeck_results().expr_ty(&args[0]); | ||
if let ty::FnDef(id, _) = arg_ty.kind() { | ||
let fn_ty = cx.tcx.fn_sig(id).skip_binder(); | ||
let ret_ty = fn_ty.output().skip_binder(); | ||
if is_unit_type(ret_ty) { | ||
cx.emit_spanned_lint( | ||
MAP_UNIT_FN, | ||
span, | ||
MappingToUnit { | ||
function_label: cx.tcx.span_of_impl(*id).unwrap(), | ||
argument_label: args[0].span, | ||
map_label: arg_ty.default_span(cx.tcx), | ||
suggestion: path.ident.span, | ||
replace: "for_each".to_string(), | ||
}, | ||
) | ||
} | ||
} else if let ty::Closure(id, subs) = arg_ty.kind() { | ||
let cl_ty = subs.as_closure().sig(); | ||
let ret_ty = cl_ty.output().skip_binder(); | ||
if is_unit_type(ret_ty) { | ||
cx.emit_spanned_lint( | ||
MAP_UNIT_FN, | ||
span, | ||
MappingToUnit { | ||
function_label: cx.tcx.span_of_impl(*id).unwrap(), | ||
argument_label: args[0].span, | ||
map_label: arg_ty.default_span(cx.tcx), | ||
suggestion: path.ident.span, | ||
replace: "for_each".to_string(), | ||
}, | ||
) | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
fn is_impl_slice(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { | ||
if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) { | ||
if let Some(impl_id) = cx.tcx.impl_of_method(method_id) { | ||
return cx.tcx.type_of(impl_id).skip_binder().is_slice(); | ||
} | ||
} | ||
false | ||
} | ||
|
||
fn is_unit_type(ty: Ty<'_>) -> bool { | ||
ty.is_unit() || ty.is_never() | ||
} | ||
|
||
fn is_diagnostic_name(cx: &LateContext<'_>, id: HirId, name: &str) -> bool { | ||
if let Some(def_id) = cx.typeck_results().type_dependent_def_id(id) { | ||
if let Some(item) = cx.tcx.get_diagnostic_name(def_id) { | ||
if item.as_str() == name { | ||
return true; | ||
} | ||
} | ||
} | ||
false | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
fn foo(items: &mut Vec<u8>) { | ||
items.sort(); | ||
} | ||
|
||
fn bar() -> impl Iterator<Item = i32> { | ||
//~^ ERROR expected `foo` to be a fn item that returns `i32`, but it returns `()` [E0271] | ||
let mut x: Vec<Vec<u8>> = vec![vec![0, 2, 1], vec![5, 4, 3]]; | ||
x.iter_mut().map(foo) | ||
} | ||
|
||
fn main() { | ||
bar(); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
error[E0271]: expected `foo` to be a fn item that returns `i32`, but it returns `()` | ||
--> $DIR/issue-106991.rs:5:13 | ||
| | ||
LL | fn bar() -> impl Iterator<Item = i32> { | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found `i32` | ||
| | ||
= note: required for `Map<std::slice::IterMut<'_, Vec<u8>>, for<'a> fn(&'a mut Vec<u8>) {foo}>` to implement `Iterator` | ||
Comment on lines
+1
to
+7
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is a case where we should be doing more than we are now. A similar explanation to the lint's would be necessary to properly convey to users what the problem was. At least pointing at the return expression with nothing else would be an improvement. |
||
|
||
error: aborting due to previous error | ||
|
||
For more information about this error, try `rustc --explain E0271`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
#![deny(map_unit_fn)] | ||
|
||
fn foo(items: &mut Vec<u8>) { | ||
items.sort(); | ||
} | ||
|
||
fn main() { | ||
let mut x: Vec<Vec<u8>> = vec![vec![0, 2, 1], vec![5, 4, 3]]; | ||
x.iter_mut().map(foo); | ||
//~^ ERROR `Iterator::map` call that discard the iterator's values | ||
x.iter_mut().map(|items| { | ||
//~^ ERROR `Iterator::map` call that discard the iterator's values | ||
items.sort(); | ||
}); | ||
let f = |items: &mut Vec<u8>| { | ||
items.sort(); | ||
}; | ||
x.iter_mut().map(f); | ||
//~^ ERROR `Iterator::map` call that discard the iterator's values | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
error: `Iterator::map` call that discard the iterator's values | ||
--> $DIR/lint_map_unit_fn.rs:9:18 | ||
| | ||
LL | fn foo(items: &mut Vec<u8>) { | ||
| --------------------------- this function returns `()`, which is likely not what you wanted | ||
... | ||
LL | x.iter_mut().map(foo); | ||
| ^^^^---^ | ||
| | | | ||
| | called `Iterator::map` with callable that returns `()` | ||
| 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 | ||
| | ||
= 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 | ||
note: the lint level is defined here | ||
--> $DIR/lint_map_unit_fn.rs:1:9 | ||
| | ||
LL | #![deny(map_unit_fn)] | ||
| ^^^^^^^^^^^ | ||
help: you might have meant to use `Iterator::for_each` | ||
| | ||
LL | x.iter_mut().for_each(foo); | ||
| ~~~~~~~~ | ||
|
||
error: `Iterator::map` call that discard the iterator's values | ||
--> $DIR/lint_map_unit_fn.rs:11:18 | ||
| | ||
LL | x.iter_mut().map(|items| { | ||
| ^ ------- | ||
| | | | ||
| ____________________|___this function returns `()`, which is likely not what you wanted | ||
| | __________________| | ||
| | | | ||
LL | | | | ||
LL | | | items.sort(); | ||
LL | | | }); | ||
| | | -^ 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 | ||
| | |_____|| | ||
| |_______| | ||
| called `Iterator::map` with callable that returns `()` | ||
| | ||
= 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 | ||
help: you might have meant to use `Iterator::for_each` | ||
| | ||
LL | x.iter_mut().for_each(|items| { | ||
| ~~~~~~~~ | ||
|
||
error: `Iterator::map` call that discard the iterator's values | ||
--> $DIR/lint_map_unit_fn.rs:18:18 | ||
| | ||
LL | let f = |items: &mut Vec<u8>| { | ||
| --------------------- this function returns `()`, which is likely not what you wanted | ||
... | ||
LL | x.iter_mut().map(f); | ||
| ^^^^-^ | ||
| | | | ||
| | called `Iterator::map` with callable that returns `()` | ||
| 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 | ||
| | ||
= 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 | ||
help: you might have meant to use `Iterator::for_each` | ||
| | ||
LL | x.iter_mut().for_each(f); | ||
| ~~~~~~~~ | ||
|
||
error: aborting due to 3 previous errors | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.