Skip to content

Commit efe33f9

Browse files
committed
Add: option_manual_map lint
1 parent 728f397 commit efe33f9

File tree

7 files changed

+626
-1
lines changed

7 files changed

+626
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2161,6 +2161,7 @@ Released 2018-09-13
21612161
[`manual_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_filter_map
21622162
[`manual_find_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_find_map
21632163
[`manual_flatten`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_flatten
2164+
[`manual_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_map
21642165
[`manual_memcpy`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_memcpy
21652166
[`manual_non_exhaustive`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_non_exhaustive
21662167
[`manual_ok_or`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_ok_or

clippy_lints/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,7 @@ mod loops;
241241
mod macro_use;
242242
mod main_recursion;
243243
mod manual_async_fn;
244+
mod manual_map;
244245
mod manual_non_exhaustive;
245246
mod manual_ok_or;
246247
mod manual_strip;
@@ -706,6 +707,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
706707
&macro_use::MACRO_USE_IMPORTS,
707708
&main_recursion::MAIN_RECURSION,
708709
&manual_async_fn::MANUAL_ASYNC_FN,
710+
&manual_map::MANUAL_MAP,
709711
&manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE,
710712
&manual_ok_or::MANUAL_OK_OR,
711713
&manual_strip::MANUAL_STRIP,
@@ -1262,6 +1264,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12621264
store.register_late_pass(|| box case_sensitive_file_extension_comparisons::CaseSensitiveFileExtensionComparisons);
12631265
store.register_late_pass(|| box redundant_slicing::RedundantSlicing);
12641266
store.register_late_pass(|| box from_str_radix_10::FromStrRadix10);
1267+
store.register_late_pass(|| box manual_map::ManualMap);
12651268

12661269
store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
12671270
LintId::of(&arithmetic::FLOAT_ARITHMETIC),
@@ -1521,6 +1524,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
15211524
LintId::of(&loops::WHILE_LET_ON_ITERATOR),
15221525
LintId::of(&main_recursion::MAIN_RECURSION),
15231526
LintId::of(&manual_async_fn::MANUAL_ASYNC_FN),
1527+
LintId::of(&manual_map::MANUAL_MAP),
15241528
LintId::of(&manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE),
15251529
LintId::of(&manual_strip::MANUAL_STRIP),
15261530
LintId::of(&manual_unwrap_or::MANUAL_UNWRAP_OR),
@@ -1750,6 +1754,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
17501754
LintId::of(&loops::WHILE_LET_ON_ITERATOR),
17511755
LintId::of(&main_recursion::MAIN_RECURSION),
17521756
LintId::of(&manual_async_fn::MANUAL_ASYNC_FN),
1757+
LintId::of(&manual_map::MANUAL_MAP),
17531758
LintId::of(&manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE),
17541759
LintId::of(&map_clone::MAP_CLONE),
17551760
LintId::of(&matches::INFALLIBLE_DESTRUCTURING_MATCH),

clippy_lints/src/manual_map.rs

Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
use crate::utils::{
2+
is_type_diagnostic_item, match_def_path, paths, peel_hir_expr_refs, peel_mid_ty_refs_is_mutable,
3+
snippet_with_applicability, span_lint_and_sugg,
4+
};
5+
use rustc_ast::util::parser::PREC_POSTFIX;
6+
use rustc_errors::Applicability;
7+
use rustc_hir::{Arm, BindingAnnotation, Block, Expr, ExprKind, Mutability, Pat, PatKind, Path, QPath};
8+
use rustc_lint::{LateContext, LateLintPass, LintContext};
9+
use rustc_middle::lint::in_external_macro;
10+
use rustc_session::{declare_lint_pass, declare_tool_lint};
11+
use rustc_span::symbol::{sym, Ident};
12+
13+
declare_clippy_lint! {
14+
/// **What it does:** Checks for usages of `match` which could be implemented using `map`
15+
///
16+
/// **Why is this bad?** Using the `map` method is clearer and more concise.
17+
///
18+
/// **Known problems:** None.
19+
///
20+
/// **Example:**
21+
///
22+
/// ```rust
23+
/// match Some(0) {
24+
/// Some(x) => Some(x + 1),
25+
/// None => None,
26+
/// };
27+
/// ```
28+
/// Use instead:
29+
/// ```rust
30+
/// Some(0).map(|x| x + 1);
31+
/// ```
32+
pub MANUAL_MAP,
33+
style,
34+
"reimplementation of `map`"
35+
}
36+
37+
declare_lint_pass!(ManualMap => [MANUAL_MAP]);
38+
39+
impl LateLintPass<'_> for ManualMap {
40+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
41+
if in_external_macro(cx.sess(), expr.span) {
42+
return;
43+
}
44+
45+
if let ExprKind::Match(scrutinee, [arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }], _) =
46+
expr.kind
47+
{
48+
let (scrutinee_ty, ty_ref_count, ty_mutability) =
49+
peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
50+
if !is_type_diagnostic_item(cx, scrutinee_ty, sym::option_type)
51+
|| !is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::option_type)
52+
{
53+
return;
54+
}
55+
56+
let (some_expr, some_pat, pat_ref_count, is_wild_none) =
57+
match (try_parse_pattern(cx, arm1.pat), try_parse_pattern(cx, arm2.pat)) {
58+
(Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count }))
59+
if is_none_expr(cx, arm1.body) =>
60+
{
61+
(arm2.body, pattern, ref_count, true)
62+
},
63+
(Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count }))
64+
if is_none_expr(cx, arm1.body) =>
65+
{
66+
(arm2.body, pattern, ref_count, false)
67+
},
68+
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild))
69+
if is_none_expr(cx, arm2.body) =>
70+
{
71+
(arm1.body, pattern, ref_count, true)
72+
},
73+
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None))
74+
if is_none_expr(cx, arm2.body) =>
75+
{
76+
(arm1.body, pattern, ref_count, false)
77+
},
78+
_ => return,
79+
};
80+
81+
// Top level or patterns aren't allowed in closures.
82+
if matches!(some_pat.kind, PatKind::Or(_)) {
83+
return;
84+
}
85+
86+
let some_expr = match get_some_expr(cx, some_expr) {
87+
Some(expr) => expr,
88+
None => return,
89+
};
90+
91+
// Determine which binding mode to use.
92+
let explicit_ref = some_pat.contains_explicit_ref_binding();
93+
let binding_mutability = explicit_ref.or(if ty_ref_count != pat_ref_count {
94+
Some(ty_mutability)
95+
} else {
96+
None
97+
});
98+
let as_ref_str = match binding_mutability {
99+
Some(Mutability::Mut) => ".as_mut()",
100+
Some(Mutability::Not) => ".as_ref()",
101+
None => "",
102+
};
103+
104+
let mut app = Applicability::MachineApplicable;
105+
106+
// Remove address-of expressions from the scrutinee. `as_ref` will be called,
107+
// the type is copyable, or the option is being passed by value.
108+
let scrutinee = peel_hir_expr_refs(scrutinee).0;
109+
let scrutinee_str = snippet_with_applicability(cx, scrutinee.span, "_", &mut app);
110+
let scrutinee_str = if expr.precedence().order() < PREC_POSTFIX {
111+
// Parens are needed to chain method calls.
112+
format!("({})", scrutinee_str)
113+
} else {
114+
scrutinee_str.into()
115+
};
116+
117+
let body_str = if let PatKind::Binding(annotation, _, some_binding, None) = some_pat.kind {
118+
if let Some(func) = can_pass_as_func(cx, some_binding, some_expr) {
119+
snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
120+
} else {
121+
// `ref` and `ref mut` annotations were handled earlier.
122+
let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
123+
"mut "
124+
} else {
125+
""
126+
};
127+
format!(
128+
"|{}{}| {}",
129+
annotation,
130+
some_binding,
131+
snippet_with_applicability(cx, some_expr.span, "..", &mut app)
132+
)
133+
}
134+
} else if !is_wild_none && explicit_ref.is_none() {
135+
// TODO: handle explicit reference annotations.
136+
format!(
137+
"|{}| {}",
138+
snippet_with_applicability(cx, some_pat.span, "..", &mut app),
139+
snippet_with_applicability(cx, some_expr.span, "..", &mut app)
140+
)
141+
} else {
142+
// Refutable bindings and mixed reference annotations can't be handled by `map`.
143+
return;
144+
};
145+
146+
span_lint_and_sugg(
147+
cx,
148+
MANUAL_MAP,
149+
expr.span,
150+
"manual implementation of `Option::map`",
151+
"try this",
152+
format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str),
153+
app,
154+
);
155+
}
156+
}
157+
}
158+
159+
// Checks whether the expression could be passed as a function, or whether a closure is needed.
160+
// Returns the function to be passed to `map` if it exists.
161+
fn can_pass_as_func(cx: &LateContext<'tcx>, binding: Ident, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
162+
match expr.kind {
163+
ExprKind::Call(func, [arg])
164+
if matches!(arg.kind,
165+
ExprKind::Path(QPath::Resolved(None, Path { segments: [path], ..}))
166+
if path.ident == binding
167+
) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
168+
{
169+
Some(func)
170+
},
171+
_ => None,
172+
}
173+
}
174+
175+
enum OptionPat<'a> {
176+
Wild,
177+
None,
178+
Some {
179+
// The pattern contained in the `Some` tuple.
180+
pattern: &'a Pat<'a>,
181+
// The number of references before the `Some` tuple.
182+
// e.g. `&&Some(_)` has a ref count of 2.
183+
ref_count: usize,
184+
},
185+
}
186+
187+
// Try to parse into a recognized `Option` pattern.
188+
// i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
189+
fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) -> Option<OptionPat<'tcx>> {
190+
fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize) -> Option<OptionPat<'tcx>> {
191+
match pat.kind {
192+
PatKind::Wild => Some(OptionPat::Wild),
193+
PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1),
194+
PatKind::Path(QPath::Resolved(None, path))
195+
if path
196+
.res
197+
.opt_def_id()
198+
.map_or(false, |id| match_def_path(cx, id, &paths::OPTION_NONE)) =>
199+
{
200+
Some(OptionPat::None)
201+
},
202+
PatKind::TupleStruct(QPath::Resolved(None, path), [pattern], _)
203+
if path
204+
.res
205+
.opt_def_id()
206+
.map_or(false, |id| match_def_path(cx, id, &paths::OPTION_SOME)) =>
207+
{
208+
Some(OptionPat::Some { pattern, ref_count })
209+
},
210+
_ => None,
211+
}
212+
}
213+
f(cx, pat, 0)
214+
}
215+
216+
// Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
217+
fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
218+
// TODO: Allow more complex expressions.
219+
match expr.kind {
220+
ExprKind::Call(
221+
Expr {
222+
kind: ExprKind::Path(QPath::Resolved(None, path)),
223+
..
224+
},
225+
[arg],
226+
) => {
227+
if match_def_path(cx, path.res.opt_def_id()?, &paths::OPTION_SOME) {
228+
Some(arg)
229+
} else {
230+
None
231+
}
232+
},
233+
ExprKind::Block(
234+
Block {
235+
stmts: [],
236+
expr: Some(expr),
237+
..
238+
},
239+
_,
240+
) => get_some_expr(cx, expr),
241+
_ => None,
242+
}
243+
}
244+
245+
// Checks for the `None` value.
246+
fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
247+
match expr.kind {
248+
ExprKind::Path(QPath::Resolved(None, path)) => path
249+
.res
250+
.opt_def_id()
251+
.map_or(false, |id| match_def_path(cx, id, &paths::OPTION_NONE)),
252+
ExprKind::Block(
253+
Block {
254+
stmts: [],
255+
expr: Some(expr),
256+
..
257+
},
258+
_,
259+
) => is_none_expr(cx, expr),
260+
_ => false,
261+
}
262+
}

clippy_lints/src/utils/mod.rs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use std::collections::hash_map::Entry;
3232
use std::hash::BuildHasherDefault;
3333

3434
use if_chain::if_chain;
35-
use rustc_ast::ast::{self, Attribute, LitKind};
35+
use rustc_ast::ast::{self, Attribute, BorrowKind, LitKind, Mutability};
3636
use rustc_data_structures::fx::FxHashMap;
3737
use rustc_errors::Applicability;
3838
use rustc_hir as hir;
@@ -1672,6 +1672,18 @@ pub fn peel_n_hir_expr_refs(expr: &'a Expr<'a>, count: usize) -> (&'a Expr<'a>,
16721672
f(expr, 0, count)
16731673
}
16741674

1675+
/// Peels off all references on the expression. Returns the underlying expression and the number of
1676+
/// references removed.
1677+
pub fn peel_hir_expr_refs(expr: &'a Expr<'a>) -> (&'a Expr<'a>, usize) {
1678+
fn f(expr: &'a Expr<'a>, count: usize) -> (&'a Expr<'a>, usize) {
1679+
match expr.kind {
1680+
ExprKind::AddrOf(BorrowKind::Ref, _, expr) => f(expr, count + 1),
1681+
_ => (expr, count),
1682+
}
1683+
}
1684+
f(expr, 0)
1685+
}
1686+
16751687
/// Peels off all references on the type. Returns the underlying type and the number of references
16761688
/// removed.
16771689
pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
@@ -1685,6 +1697,19 @@ pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
16851697
peel(ty, 0)
16861698
}
16871699

1700+
/// Peels off all references on the type.Returns the underlying type, the number of references
1701+
/// removed, and whether the pointer is ultimately mutable or not.
1702+
pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
1703+
fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
1704+
match ty.kind() {
1705+
ty::Ref(_, ty, Mutability::Mut) => f(ty, count + 1, mutability),
1706+
ty::Ref(_, ty, Mutability::Not) => f(ty, count + 1, Mutability::Not),
1707+
_ => (ty, count, mutability),
1708+
}
1709+
}
1710+
f(ty, 0, Mutability::Mut)
1711+
}
1712+
16881713
#[macro_export]
16891714
macro_rules! unwrap_cargo_metadata {
16901715
($cx: ident, $lint: ident, $deps: expr) => {{

0 commit comments

Comments
 (0)