Skip to content

Commit f016862

Browse files
authored
Merge pull request #2281 from detrumi/match-as-ref
Lint for matching option as ref
2 parents cf58e1c + a6ccc6f commit f016862

File tree

4 files changed

+117
-3
lines changed

4 files changed

+117
-3
lines changed

clippy_lints/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
499499
loops::WHILE_LET_LOOP,
500500
loops::WHILE_LET_ON_ITERATOR,
501501
map_clone::MAP_CLONE,
502+
matches::MATCH_AS_REF,
502503
matches::MATCH_BOOL,
503504
matches::MATCH_OVERLAPPING_ARM,
504505
matches::MATCH_REF_PATS,

clippy_lints/src/matches.rs

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ use syntax::ast::LitKind;
1111
use syntax::ast::NodeId;
1212
use syntax::codemap::Span;
1313
use utils::paths;
14-
use utils::{expr_block, in_external_macro, is_allowed, is_expn_of, match_type, remove_blocks, snippet,
15-
span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty};
14+
use utils::{expr_block, in_external_macro, is_allowed, is_expn_of, match_qpath, match_type, remove_blocks,
15+
snippet, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty};
1616
use utils::sugg::Sugg;
1717

1818
/// **What it does:** Checks for matches with a single arm where an `if let`
@@ -145,6 +145,27 @@ declare_lint! {
145145
"a match with `Err(_)` arm and take drastic actions"
146146
}
147147

148+
/// **What it does:** Checks for match which is used to add a reference to an
149+
/// `Option` value.
150+
///
151+
/// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
152+
///
153+
/// **Known problems:** None.
154+
///
155+
/// **Example:**
156+
/// ```rust
157+
/// let x: Option<()> = None;
158+
/// let r: Option<&()> = match x {
159+
/// None => None,
160+
/// Some(ref v) => Some(v),
161+
/// };
162+
/// ```
163+
declare_lint! {
164+
pub MATCH_AS_REF,
165+
Warn,
166+
"a match on an Option value instead of using `as_ref()` or `as_mut`"
167+
}
168+
148169
#[allow(missing_copy_implementations)]
149170
pub struct MatchPass;
150171

@@ -156,7 +177,8 @@ impl LintPass for MatchPass {
156177
MATCH_BOOL,
157178
SINGLE_MATCH_ELSE,
158179
MATCH_OVERLAPPING_ARM,
159-
MATCH_WILD_ERR_ARM
180+
MATCH_WILD_ERR_ARM,
181+
MATCH_AS_REF
160182
)
161183
}
162184
}
@@ -171,6 +193,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
171193
check_match_bool(cx, ex, arms, expr);
172194
check_overlapping_arms(cx, ex, arms);
173195
check_wild_err_arm(cx, ex, arms);
196+
check_match_as_ref(cx, ex, arms, expr);
174197
}
175198
if let ExprMatch(ref ex, ref arms, source) = expr.node {
176199
check_match_ref_pats(cx, ex, arms, source, expr);
@@ -411,6 +434,31 @@ fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: Match
411434
}
412435
}
413436

437+
fn check_match_as_ref(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
438+
if arms.len() == 2 &&
439+
arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
440+
arms[1].pats.len() == 1 && arms[1].guard.is_none() {
441+
let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
442+
is_ref_some_arm(&arms[1])
443+
} else if is_none_arm(&arms[1]) {
444+
is_ref_some_arm(&arms[0])
445+
} else {
446+
None
447+
};
448+
if let Some(rb) = arm_ref {
449+
let suggestion = if rb == BindingAnnotation::Ref { "as_ref" } else { "as_mut" };
450+
span_lint_and_sugg(
451+
cx,
452+
MATCH_AS_REF,
453+
expr.span,
454+
&format!("use {}() instead", suggestion),
455+
"try this",
456+
format!("{}.{}()", snippet(cx, ex.span, "_"), suggestion)
457+
)
458+
}
459+
}
460+
}
461+
414462
/// Get all arms that are unbounded `PatRange`s.
415463
fn all_ranges<'a, 'tcx>(
416464
cx: &LateContext<'a, 'tcx>,
@@ -524,6 +572,34 @@ fn is_unit_expr(expr: &Expr) -> bool {
524572
}
525573
}
526574

575+
// Checks if arm has the form `None => None`
576+
fn is_none_arm(arm: &Arm) -> bool {
577+
match arm.pats[0].node {
578+
PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
579+
_ => false,
580+
}
581+
}
582+
583+
// Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
584+
fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
585+
if_chain! {
586+
if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
587+
if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
588+
if let PatKind::Binding(rb, _, ref ident, _) = pats[0].node;
589+
if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
590+
if let ExprCall(ref e, ref args) = remove_blocks(&arm.body).node;
591+
if let ExprPath(ref some_path) = e.node;
592+
if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
593+
if let ExprPath(ref qpath) = args[0].node;
594+
if let &QPath::Resolved(_, ref path2) = qpath;
595+
if path2.segments.len() == 1 && ident.node == path2.segments[0].name;
596+
then {
597+
return Some(rb)
598+
}
599+
}
600+
None
601+
}
602+
527603
fn has_only_ref_pats(arms: &[Arm]) -> bool {
528604
let mapped = arms.iter()
529605
.flat_map(|a| &a.pats)

tests/ui/matches.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,5 +315,20 @@ fn match_wild_err_arm() {
315315
}
316316
}
317317

318+
fn match_as_ref() {
319+
let owned: Option<()> = None;
320+
let borrowed: Option<&()> = match owned {
321+
None => None,
322+
Some(ref v) => Some(v),
323+
};
324+
325+
let mut mut_owned: Option<()> = None;
326+
let borrow_mut: Option<&mut ()> = match mut_owned {
327+
None => None,
328+
Some(ref mut v) => Some(v),
329+
};
330+
331+
}
332+
318333
fn main() {
319334
}

tests/ui/matches.stderr

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,3 +426,25 @@ note: consider refactoring into `Ok(3) | Ok(_)`
426426
| ^^^^^^^^^^^^^^
427427
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
428428

429+
error: use as_ref() instead
430+
--> $DIR/matches.rs:320:33
431+
|
432+
320 | let borrowed: Option<&()> = match owned {
433+
| _________________________________^
434+
321 | | None => None,
435+
322 | | Some(ref v) => Some(v),
436+
323 | | };
437+
| |_____^ help: try this: `owned.as_ref()`
438+
|
439+
= note: `-D match-as-ref` implied by `-D warnings`
440+
441+
error: use as_mut() instead
442+
--> $DIR/matches.rs:326:39
443+
|
444+
326 | let borrow_mut: Option<&mut ()> = match mut_owned {
445+
| _______________________________________^
446+
327 | | None => None,
447+
328 | | Some(ref mut v) => Some(v),
448+
329 | | };
449+
| |_____^ help: try this: `mut_owned.as_mut()`
450+

0 commit comments

Comments
 (0)