-#[rustfmt::skip]
-fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
- if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
- if expr.span.from_expansion() {
- // Don't lint match expressions present in
- // macro_rules! block
- return;
- }
- if let PatKind::Or(..) = arms[0].pat.kind {
- // don't lint for or patterns for now, this makes
- // the lint noisy in unnecessary situations
- return;
- }
- let els = arms[1].body;
- let els = if is_unit_expr(peel_blocks(els)) {
- None
- } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
- if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
- // single statement/expr "else" block, don't lint
- return;
- }
- // block with 2+ statements or 1 expr and 1+ statement
- Some(els)
- } else {
- // not a block, don't lint
- return;
- };
-
- let ty = cx.typeck_results().expr_ty(ex);
- if *ty.kind() != ty::Bool || is_lint_allowed(cx, MATCH_BOOL, ex.hir_id) {
- check_single_match_single_pattern(cx, ex, arms, expr, els);
- check_single_match_opt_like(cx, ex, arms, expr, ty, els);
- }
- }
-}
-
-fn check_single_match_single_pattern(
- cx: &LateContext<'_>,
- ex: &Expr<'_>,
- arms: &[Arm<'_>],
- expr: &Expr<'_>,
- els: Option<&Expr<'_>>,
-) {
- if is_wild(arms[1].pat) {
- report_single_match_single_pattern(cx, ex, arms, expr, els);
- }
-}
-
-fn report_single_match_single_pattern(
- cx: &LateContext<'_>,
- ex: &Expr<'_>,
- arms: &[Arm<'_>],
- expr: &Expr<'_>,
- els: Option<&Expr<'_>>,
-) {
- let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
- let els_str = els.map_or(String::new(), |els| {
- format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
- });
-
- let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
- let (msg, sugg) = if_chain! {
- if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
- let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
- if let Some(spe_trait_id) = cx.tcx.lang_items().structural_peq_trait();
- if let Some(pe_trait_id) = cx.tcx.lang_items().eq_trait();
- if ty.is_integral() || ty.is_char() || ty.is_str()
- || (implements_trait(cx, ty, spe_trait_id, &[])
- && implements_trait(cx, ty, pe_trait_id, &[ty.into()]));
- then {
- // scrutinee derives PartialEq and the pattern is a constant.
- let pat_ref_count = match pat.kind {
- // string literals are already a reference.
- PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
- _ => pat_ref_count,
- };
- // References are only implicitly added to the pattern, so no overflow here.
- // e.g. will work: match &Some(_) { Some(_) => () }
- // will not: match Some(_) { &Some(_) => () }
- let ref_count_diff = ty_ref_count - pat_ref_count;
-
- // Try to remove address of expressions first.
- let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
- let ref_count_diff = ref_count_diff - removed;
-
- let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
- let sugg = format!(
- "if {} == {}{} {}{}",
- snippet(cx, ex.span, ".."),
- // PartialEq for different reference counts may not exist.
- "&".repeat(ref_count_diff),
- snippet(cx, arms[0].pat.span, ".."),
- expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
- els_str,
- );
- (msg, sugg)
- } else {
- let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
- let sugg = format!(
- "if let {} = {} {}{}",
- snippet(cx, arms[0].pat.span, ".."),
- snippet(cx, ex.span, ".."),
- expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
- els_str,
- );
- (msg, sugg)
- }
- };
-
- span_lint_and_sugg(
- cx,
- lint,
- expr.span,
- msg,
- "try this",
- sugg,
- Applicability::HasPlaceholders,
- );
-}
-
-fn check_single_match_opt_like<'a>(
- cx: &LateContext<'a>,
- ex: &Expr<'_>,
- arms: &[Arm<'_>],
- expr: &Expr<'_>,
- ty: Ty<'a>,
- els: Option<&Expr<'_>>,
-) {
- // list of candidate `Enum`s we know will never get any more members
- let candidates = &[
- (&paths::COW, "Borrowed"),
- (&paths::COW, "Cow::Borrowed"),
- (&paths::COW, "Cow::Owned"),
- (&paths::COW, "Owned"),
- (&paths::OPTION, "None"),
- (&paths::RESULT, "Err"),
- (&paths::RESULT, "Ok"),
- ];
-
- // We want to suggest to exclude an arm that contains only wildcards or forms the exhaustive
- // match with the second branch, without enum variants in matches.
- if !contains_only_wilds(arms[1].pat) && !form_exhaustive_matches(arms[0].pat, arms[1].pat) {
- return;
- }
-
- let mut paths_and_types = Vec::new();
- if !collect_pat_paths(&mut paths_and_types, cx, arms[1].pat, ty) {
- return;
- }
-
- let in_candidate_enum = |path_info: &(String, &TyS<'_>)| -> bool {
- let (path, ty) = path_info;
- for &(ty_path, pat_path) in candidates {
- if path == pat_path && match_type(cx, ty, ty_path) {
- return true;
- }
- }
- false
- };
- if paths_and_types.iter().all(in_candidate_enum) {
- report_single_match_single_pattern(cx, ex, arms, expr, els);
- }
-}
-
-/// Collects paths and their types from the given patterns. Returns true if the given pattern could
-/// be simplified, false otherwise.
-fn collect_pat_paths<'a>(acc: &mut Vec<(String, Ty<'a>)>, cx: &LateContext<'a>, pat: &Pat<'_>, ty: Ty<'a>) -> bool {
- match pat.kind {
- PatKind::Wild => true,
- PatKind::Tuple(inner, _) => inner.iter().all(|p| {
- let p_ty = cx.typeck_results().pat_ty(p);
- collect_pat_paths(acc, cx, p, p_ty)
- }),
- PatKind::TupleStruct(ref path, ..) => {
- let path = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
- s.print_qpath(path, false);
- });
- acc.push((path, ty));
- true
- },
- PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => {
- acc.push((ident.to_string(), ty));
- true
- },
- PatKind::Path(ref path) => {
- let path = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
- s.print_qpath(path, false);
- });
- acc.push((path, ty));
- true
- },
- _ => false,
- }
-}
-
-/// Returns true if the given arm of pattern matching contains wildcard patterns.
-fn contains_only_wilds(pat: &Pat<'_>) -> bool {
- match pat.kind {
- PatKind::Wild => true,
- PatKind::Tuple(inner, _) | PatKind::TupleStruct(_, inner, ..) => inner.iter().all(contains_only_wilds),
- _ => false,
- }
-}
-
-/// Returns true if the given patterns forms only exhaustive matches that don't contain enum
-/// patterns without a wildcard.
-fn form_exhaustive_matches(left: &Pat<'_>, right: &Pat<'_>) -> bool {
- match (&left.kind, &right.kind) {
- (PatKind::Wild, _) | (_, PatKind::Wild) => true,
- (PatKind::Tuple(left_in, left_pos), PatKind::Tuple(right_in, right_pos)) => {
- // We don't actually know the position and the presence of the `..` (dotdot) operator
- // in the arms, so we need to evaluate the correct offsets here in order to iterate in
- // both arms at the same time.
- let len = max(
- left_in.len() + {
- if left_pos.is_some() { 1 } else { 0 }
- },
- right_in.len() + {
- if right_pos.is_some() { 1 } else { 0 }
- },
- );
- let mut left_pos = left_pos.unwrap_or(usize::MAX);
- let mut right_pos = right_pos.unwrap_or(usize::MAX);
- let mut left_dot_space = 0;
- let mut right_dot_space = 0;
- for i in 0..len {
- let mut found_dotdot = false;
- if i == left_pos {
- left_dot_space += 1;
- if left_dot_space < len - left_in.len() {
- left_pos += 1;
- }
- found_dotdot = true;
- }
- if i == right_pos {
- right_dot_space += 1;
- if right_dot_space < len - right_in.len() {
- right_pos += 1;
- }
- found_dotdot = true;
- }
- if found_dotdot {
- continue;
- }
- if !contains_only_wilds(&left_in[i - left_dot_space])
- && !contains_only_wilds(&right_in[i - right_dot_space])
- {
- return false;
- }
- }
- true
- },
- _ => false,
- }
-}
-
-fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
- // Type of expression is `bool`.
- if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
- span_lint_and_then(
- cx,
- MATCH_BOOL,
- expr.span,
- "you seem to be trying to match on a boolean expression",
- move |diag| {
- if arms.len() == 2 {
- // no guards
- let exprs = if let PatKind::Lit(arm_bool) = arms[0].pat.kind {
- if let ExprKind::Lit(ref lit) = arm_bool.kind {
- match lit.node {
- LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
- LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
- _ => None,
- }
- } else {
- None
- }
- } else {
- None
- };
-
- if let Some((true_expr, false_expr)) = exprs {
- let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
- (false, false) => Some(format!(
- "if {} {} else {}",
- snippet(cx, ex.span, "b"),
- expr_block(cx, true_expr, None, "..", Some(expr.span)),
- expr_block(cx, false_expr, None, "..", Some(expr.span))
- )),
- (false, true) => Some(format!(
- "if {} {}",
- snippet(cx, ex.span, "b"),
- expr_block(cx, true_expr, None, "..", Some(expr.span))
- )),
- (true, false) => {
- let test = Sugg::hir(cx, ex, "..");
- Some(format!(
- "if {} {}",
- !test,
- expr_block(cx, false_expr, None, "..", Some(expr.span))
- ))
- },
- (true, true) => None,
- };
-
- if let Some(sugg) = sugg {
- diag.span_suggestion(
- expr.span,
- "consider using an `if`/`else` expression",
- sugg,
- Applicability::HasPlaceholders,
- );
- }
- }
- }
- },
- );
- }
-}
-
-fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
- if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
- let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
- if !ranges.is_empty() {
- if let Some((start, end)) = overlapping(&ranges) {
- span_lint_and_note(
- cx,
- MATCH_OVERLAPPING_ARM,
- start.span,
- "some ranges overlap",
- Some(end.span),
- "overlaps with this",
- );
- }
- }
- }
-}
-
-fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
- let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
- if is_type_diagnostic_item(cx, ex_ty, sym::Result) {
- for arm in arms {
- if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
- let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
- if path_str == "Err" {
- let mut matching_wild = inner.iter().any(is_wild);
- let mut ident_bind_name = kw::Underscore;
- if !matching_wild {
- // Looking for unused bindings (i.e.: `_e`)
- for pat in inner.iter() {
- if let PatKind::Binding(_, id, ident, None) = pat.kind {
- if ident.as_str().starts_with('_') && !is_local_used(cx, arm.body, id) {
- ident_bind_name = ident.name;
- matching_wild = true;
- }
- }
- }
- }
- if_chain! {
- if matching_wild;
- if let Some(macro_call) = root_macro_call(peel_blocks_with_stmt(arm.body).span);
- if is_panic(cx, macro_call.def_id);
- then {
- // `Err(_)` or `Err(_e)` arm with `panic!` found
- span_lint_and_note(cx,
- MATCH_WILD_ERR_ARM,
- arm.pat.span,
- &format!("`Err({})` matches all errors", ident_bind_name),
- None,
- "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
- );
- }
- }
- }
- }
- }
- }
-}
-
-enum CommonPrefixSearcher<'a> {
- None,
- Path(&'a [PathSegment<'a>]),
- Mixed,
-}
-impl<'a> CommonPrefixSearcher<'a> {
- fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
- match path {
- [path @ .., _] => self.with_prefix(path),
- [] => (),
- }
- }
-
- fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
- match self {
- Self::None => *self = Self::Path(path),
- Self::Path(self_path)
- if path
- .iter()
- .map(|p| p.ident.name)
- .eq(self_path.iter().map(|p| p.ident.name)) => {},
- Self::Path(_) => *self = Self::Mixed,
- Self::Mixed => (),
- }
- }
-}
-
-fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
- let attrs = cx.tcx.get_attrs(variant_def.def_id);
- clippy_utils::attrs::is_doc_hidden(attrs) || clippy_utils::attrs::is_unstable(attrs)
-}
-
-#[allow(clippy::too_many_lines)]
-fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
- let ty = cx.typeck_results().expr_ty(ex).peel_refs();
- let adt_def = match ty.kind() {
- ty::Adt(adt_def, _)
- if adt_def.is_enum()
- && !(is_type_diagnostic_item(cx, ty, sym::Option) || is_type_diagnostic_item(cx, ty, sym::Result)) =>
- {
- adt_def
- },
- _ => return,
- };
-
- // First pass - check for violation, but don't do much book-keeping because this is hopefully
- // the uncommon case, and the book-keeping is slightly expensive.
- let mut wildcard_span = None;
- let mut wildcard_ident = None;
- let mut has_non_wild = false;
- for arm in arms {
- match peel_hir_pat_refs(arm.pat).0.kind {
- PatKind::Wild => wildcard_span = Some(arm.pat.span),
- PatKind::Binding(_, _, ident, None) => {
- wildcard_span = Some(arm.pat.span);
- wildcard_ident = Some(ident);
- },
- _ => has_non_wild = true,
- }
- }
- let wildcard_span = match wildcard_span {
- Some(x) if has_non_wild => x,
- _ => return,
- };
-
- // Accumulate the variants which should be put in place of the wildcard because they're not
- // already covered.
- let has_hidden = adt_def.variants.iter().any(|x| is_hidden(cx, x));
- let mut missing_variants: Vec<_> = adt_def.variants.iter().filter(|x| !is_hidden(cx, x)).collect();
-
- let mut path_prefix = CommonPrefixSearcher::None;
- for arm in arms {
- // Guards mean that this case probably isn't exhaustively covered. Technically
- // this is incorrect, as we should really check whether each variant is exhaustively
- // covered by the set of guards that cover it, but that's really hard to do.
- recurse_or_patterns(arm.pat, |pat| {
- let path = match &peel_hir_pat_refs(pat).0.kind {
- PatKind::Path(path) => {
- #[allow(clippy::match_same_arms)]
- let id = match cx.qpath_res(path, pat.hir_id) {
- Res::Def(
- DefKind::Const | DefKind::ConstParam | DefKind::AnonConst | DefKind::InlineConst,
- _,
- ) => return,
- Res::Def(_, id) => id,
- _ => return,
- };
- if arm.guard.is_none() {
- missing_variants.retain(|e| e.ctor_def_id != Some(id));
- }
- path
- },
- PatKind::TupleStruct(path, patterns, ..) => {
- if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
- if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
- missing_variants.retain(|e| e.ctor_def_id != Some(id));
- }
- }
- path
- },
- PatKind::Struct(path, patterns, ..) => {
- if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
- if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
- missing_variants.retain(|e| e.def_id != id);
- }
- }
- path
- },
- _ => return,
- };
- match path {
- QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
- QPath::TypeRelative(
- hir::Ty {
- kind: TyKind::Path(QPath::Resolved(_, path)),
- ..
- },
- _,
- ) => path_prefix.with_prefix(path.segments),
- _ => (),
- }
- });
- }
-
- let format_suggestion = |variant: &VariantDef| {
- format!(
- "{}{}{}{}",
- if let Some(ident) = wildcard_ident {
- format!("{} @ ", ident.name)
- } else {
- String::new()
- },
- if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
- let mut s = String::new();
- for seg in path_prefix {
- s.push_str(seg.ident.as_str());
- s.push_str("::");
- }
- s
- } else {
- let mut s = cx.tcx.def_path_str(adt_def.did);
- s.push_str("::");
- s
- },
- variant.name,
- match variant.ctor_kind {
- CtorKind::Fn if variant.fields.len() == 1 => "(_)",
- CtorKind::Fn => "(..)",
- CtorKind::Const => "",
- CtorKind::Fictive => "{ .. }",
- }
- )
- };
-
- match missing_variants.as_slice() {
- [] => (),
- [x] if !adt_def.is_variant_list_non_exhaustive() && !has_hidden => span_lint_and_sugg(
- cx,
- MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
- wildcard_span,
- "wildcard matches only a single variant and will also match any future added variants",
- "try this",
- format_suggestion(x),
- Applicability::MaybeIncorrect,
- ),
- variants => {
- let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
- let message = if adt_def.is_variant_list_non_exhaustive() || has_hidden {
- suggestions.push("_".into());
- "wildcard matches known variants and will also match future added variants"
- } else {
- "wildcard match will also match any future added variants"
- };
-
- span_lint_and_sugg(
- cx,
- WILDCARD_ENUM_MATCH_ARM,
- wildcard_span,
- message,
- "try this",
- suggestions.join(" | "),
- Applicability::MaybeIncorrect,
- );
- },
- };
-}
-
-fn check_match_ref_pats<'a, 'b, I>(cx: &LateContext<'_>, ex: &Expr<'_>, pats: I, expr: &Expr<'_>)
-where
- 'b: 'a,
- I: Clone + Iterator<Item = &'a Pat<'b>>,
-{
- if !has_multiple_ref_pats(pats.clone()) {
- return;
- }
-
- let (first_sugg, msg, title);
- let span = ex.span.source_callsite();
- if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
- first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
- msg = "try";
- title = "you don't need to add `&` to both the expression and the patterns";
- } else {
- first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
- msg = "instead of prefixing all patterns with `&`, you can dereference the expression";
- title = "you don't need to add `&` to all patterns";
- }
-
- let remaining_suggs = pats.filter_map(|pat| {
- if let PatKind::Ref(refp, _) = pat.kind {
- Some((pat.span, snippet(cx, refp.span, "..").to_string()))
- } else {
- None
- }
- });
-
- span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
- if !expr.span.from_expansion() {
- multispan_sugg(diag, msg, first_sugg.chain(remaining_suggs));
- }
- });
-}
-
-fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
- if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
- let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
- is_ref_some_arm(cx, &arms[1])
- } else if is_none_arm(cx, &arms[1]) {
- is_ref_some_arm(cx, &arms[0])
- } else {
- None
- };
- if let Some(rb) = arm_ref {
- let suggestion = if rb == BindingAnnotation::Ref {
- "as_ref"
- } else {
- "as_mut"
- };
-
- let output_ty = cx.typeck_results().expr_ty(expr);
- let input_ty = cx.typeck_results().expr_ty(ex);
-
- let cast = if_chain! {
- if let ty::Adt(_, substs) = input_ty.kind();
- let input_ty = substs.type_at(0);
- if let ty::Adt(_, substs) = output_ty.kind();
- let output_ty = substs.type_at(0);
- if let ty::Ref(_, output_ty, _) = *output_ty.kind();
- if input_ty != output_ty;
- then {
- ".map(|x| x as _)"
- } else {
- ""
- }
- };
-
- let mut applicability = Applicability::MachineApplicable;
- span_lint_and_sugg(
- cx,
- MATCH_AS_REF,
- expr.span,
- &format!("use `{}()` instead", suggestion),
- "try this",
- format!(
- "{}.{}(){}",
- snippet_with_applicability(cx, ex.span, "_", &mut applicability),
- suggestion,
- cast,
- ),
- applicability,
- );
- }
- }
-}
-