Skip to content

Commit 69a2186

Browse files
committed
rewrite
1 parent 03232a6 commit 69a2186

File tree

8 files changed

+467
-256
lines changed

8 files changed

+467
-256
lines changed

clippy_lints/src/manual_map.rs

Lines changed: 109 additions & 124 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
use crate::utils::{
2-
is_allowed, is_type_diagnostic_item, match_def_path, match_path, paths, snippet_with_applicability,
3-
span_lint_and_sugg,
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,
44
};
5-
use core::fmt;
6-
use if_chain::if_chain;
5+
use rustc_ast::util::parser::PREC_POSTFIX;
76
use rustc_errors::Applicability;
8-
use rustc_hir::{Arm, BindingAnnotation, Block, Expr, ExprKind, PatKind, QPath, Pat, Path, Mutability};
7+
use rustc_hir::{Arm, BindingAnnotation, Block, Expr, ExprKind, Mutability, Pat, PatKind, Path, QPath};
98
use rustc_lint::{LateContext, LateLintPass, LintContext};
10-
use rustc_middle::{lint::in_external_macro, ty::{self, Ty, TyS}};
9+
use rustc_middle::lint::in_external_macro;
1110
use rustc_session::{declare_lint_pass, declare_tool_lint};
1211
use rustc_span::symbol::{sym, Ident};
1312

@@ -39,176 +38,159 @@ declare_lint_pass!(ManualMap => [MANUAL_MAP]);
3938

4039
impl LateLintPass<'_> for ManualMap {
4140
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
42-
if !in_external_macro(cx.sess(), expr.span) {
41+
if in_external_macro(cx.sess(), expr.span) {
4342
return;
4443
}
4544

4645
if let ExprKind::Match(scrutinee, [arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }], _) =
4746
expr.kind
4847
{
49-
let scrutinee_ty = cx.typeck_results().expr_ty(expr);
50-
let some_ty = match extract_some_ty(cx, scrutinee_ty) {
51-
Some(ty) => ty,
52-
None => return,
53-
};
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+
}
5455

55-
let (some_expr, some_pat, is_ref, is_wild_none) =
56+
let (some_expr, some_pat, pat_ref_count, is_wild_none) =
5657
match (try_parse_pattern(cx, arm1.pat), try_parse_pattern(cx, arm2.pat)) {
57-
(Some(OptionPat::Wild), Some(OptionPat::Some { pattern, is_ref }))
58+
(Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count }))
5859
if is_none_expr(cx, arm1.body) =>
5960
{
60-
(arm2.body, pattern, is_ref, true)
61+
(arm2.body, pattern, ref_count, true)
6162
},
62-
(Some(OptionPat::None), Some(OptionPat::Some { pattern, is_ref }))
63+
(Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count }))
6364
if is_none_expr(cx, arm1.body) =>
6465
{
65-
(arm2.body, pattern, is_ref, false)
66+
(arm2.body, pattern, ref_count, false)
6667
},
67-
(Some(OptionPat::Some { pattern, is_ref }), Some(OptionPat::Wild))
68-
if is_none_expr(cx, arm1.body) =>
68+
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild))
69+
if is_none_expr(cx, arm2.body) =>
6970
{
70-
(arm2.body, pattern, is_ref, true)
71+
(arm1.body, pattern, ref_count, true)
7172
},
72-
(Some(OptionPat::Some { pattern, is_ref }), Some(OptionPat::None))
73+
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None))
7374
if is_none_expr(cx, arm2.body) =>
7475
{
75-
(arm1.body, pattern, is_ref, false)
76+
(arm1.body, pattern, ref_count, false)
7677
},
7778
_ => return,
7879
};
7980

81+
// Top level or patterns aren't allowed in closures.
8082
if matches!(some_pat.kind, PatKind::Or(_)) {
8183
return;
8284
}
8385

84-
if let Some(some_expr) = get_some_expr(cx, some_expr) {
85-
let explicit_ref = some_pat.contains_explicit_ref_binding();
86-
let binding_mutability = match scrutinee_ty.kind() {
87-
ty::Ref(_, _, mutability) if !is_ref => Some(mutability),
88-
_ => explicit_ref,
89-
};
86+
let some_expr = match get_some_expr(cx, some_expr) {
87+
Some(expr) => expr,
88+
None => return,
89+
};
9090

91-
let as_ref_str = match binding_mutability {
92-
Some(Mutability::Mut) => "as_mut()",
93-
Some(Mutability::Not) => "as_ref()",
94-
None => "",
95-
};
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+
};
96103

97-
let mut app = Applicability::MachineApplicable;
104+
let mut app = Applicability::MachineApplicable;
98105

99-
let scrutinee_span = match scrutinee.kind {
100-
ExprKind::AddrOf(_, _, expr) => expr.span,
101-
_ => scrutinee.span,
102-
};
103-
let scrutinee_str = snippet_with_applicability(cx, scrutinee_span, "_", &mut app);
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+
};
104116

105-
let body_str = if let PatKind::Binding(annotation, _, some_binding, None) = some_pat {
106-
match some_expr.kind {
107-
ExprKind::Call(
108-
&Expr {
109-
kind: ExprKind::Path(func_path),
110-
hir_id: func_id,
111-
span: func_span,
112-
..
113-
},
114-
[Expr {
115-
kind:
116-
ExprKind::Path(QPath::Resolved(
117-
None,
118-
&Path {
119-
segments: [arg_name], ..
120-
},
121-
)),
122-
..
123-
}],
124-
) if arg_name.ident == some_binding
125-
&& cx.qpath_res(func_path, func_id).opt_def_id().map_or(false, |id| {
126-
TyS::same_type(
127-
peel_ref_if(
128-
cx.tcx.fn_sig(id).skip_binder().inputs()[0],
129-
binding_mutability.is_some(),
130-
),
131-
some_ty,
132-
)
133-
}) =>
134-
{
135-
snippet_with_applicability(cx, func_span, "..", &mut app).into_owned()
136-
},
137-
_ => {
138-
let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
139-
"mut "
140-
} else {
141-
""
142-
};
143-
format!(
144-
"|{}{}| {}",
145-
annotation,
146-
some_binding,
147-
snippet_with_applicability(cx, some_expr.span, "..", &mut app)
148-
)
149-
},
150-
}
151-
} else if !is_wild_none && explicit_ref.is_none() {
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+
};
152127
format!(
153-
"|{}| {}",
154-
snippet_with_applicability(cx, some_pat.span, "..", &mut app),
128+
"|{}{}| {}",
129+
annotation,
130+
some_binding,
155131
snippet_with_applicability(cx, some_expr.span, "..", &mut app)
156132
)
157-
} else {
158-
// TODO: handle explicit reference annotations
159-
return;
160-
};
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+
};
161145

162-
span_lint_and_sugg(
163-
cx,
164-
MANUAL_MAP,
165-
expr.span,
166-
"manual implementation of `Option::map`",
167-
"use `map` instead",
168-
format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str),
169-
app,
170-
);
171-
}
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+
);
172155
}
173156
}
174157
}
175158

176-
fn extract_some_ty(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
177-
match ty.kind() {
178-
ty::Ref(_, ty, _) if is_type_diagnostic_item(cx, ty, sym::option_type) => {
179-
if let ty::Adt(_, subs) = ty.kind() {
180-
subs.types().next()
181-
} else {
182-
None
183-
}
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)
184170
},
185-
ty::Adt(_, subs) if is_type_diagnostic_item(cx, ty, sym::option_type) => subs.types().next(),
186171
_ => None,
187172
}
188173
}
189174

190-
fn peel_ref_if(ty: Ty<'_>, cond: bool) -> Ty<'_> {
191-
match ty.kind() {
192-
ty::Ref(_, ty, _) if cond => ty,
193-
_ => ty,
194-
}
195-
}
196-
197175
enum OptionPat<'a> {
198176
Wild,
199177
None,
200178
Some {
179+
// The pattern contained in the `Some` tuple.
201180
pattern: &'a Pat<'a>,
202-
// &Some(_)
203-
is_ref: bool,
181+
// The number of references before the `Some` tuple.
182+
// e.g. `&&Some(_)` has a ref count of 2.
183+
ref_count: usize,
204184
},
205185
}
206186

187+
// Try to parse into a recognized `Option` pattern.
188+
// i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
207189
fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) -> Option<OptionPat<'tcx>> {
208-
fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, is_ref: bool) -> Option<OptionPat<'tcx>> {
190+
fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize) -> Option<OptionPat<'tcx>> {
209191
match pat.kind {
210192
PatKind::Wild => Some(OptionPat::Wild),
211-
PatKind::Ref(pat, _) => f(cx, pat, true),
193+
PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1),
212194
PatKind::Path(QPath::Resolved(None, path))
213195
if path
214196
.res
@@ -223,15 +205,17 @@ fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) -> Option<Optio
223205
.opt_def_id()
224206
.map_or(false, |id| match_def_path(cx, id, &paths::OPTION_SOME)) =>
225207
{
226-
Some(OptionPat::Some { pattern, is_ref })
208+
Some(OptionPat::Some { pattern, ref_count })
227209
},
228210
_ => None,
229211
}
230212
}
231-
f(cx, pat, false)
213+
f(cx, pat, 0)
232214
}
233215

216+
// Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
234217
fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
218+
// TODO: Allow more complex expressions.
235219
match expr.kind {
236220
ExprKind::Call(
237221
Expr {
@@ -258,6 +242,7 @@ fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx E
258242
}
259243
}
260244

245+
// Checks for the `None` value.
261246
fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
262247
match expr.kind {
263248
ExprKind::Path(QPath::Resolved(None, path)) => path

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) => {{

tests/ui/manual_map.fixed

Lines changed: 0 additions & 25 deletions
This file was deleted.

0 commit comments

Comments
 (0)