1 use crate::utils::{last_path_segment, span_lint_and_help};
3 intravisit, Body, Expr, ExprKind, FieldPat, FnDecl, HirId, LocalSource, MatchSource, Mutability, Pat, PatKind,
6 use rustc_lint::{LateContext, LateLintPass, LintContext};
7 use rustc_middle::lint::in_external_macro;
8 use rustc_middle::ty::subst::SubstsRef;
9 use rustc_middle::ty::{AdtDef, FieldDef, Ty, TyKind, VariantDef};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::source_map::Span;
13 declare_clippy_lint! {
14 /// **What it does:** Checks for patterns that aren't exact representations of the types
15 /// they are applied to.
17 /// To satisfy this lint, you will have to adjust either the expression that is matched
18 /// against or the pattern itself, as well as the bindings that are introduced by the
19 /// adjusted patterns. For matching you will have to either dereference the expression
20 /// with the `*` operator, or amend the patterns to explicitly match against `&<pattern>`
21 /// or `&mut <pattern>` depending on the reference mutability. For the bindings you need
22 /// to use the inverse. You can leave them as plain bindings if you wish for the value
23 /// to be copied, but you must use `ref mut <variable>` or `ref <variable>` to construct
24 /// a reference into the matched structure.
26 /// If you are looking for a way to learn about ownership semantics in more detail, it
27 /// is recommended to look at IDE options available to you to highlight types, lifetimes
28 /// and reference semantics in your code. The available tooling would expose these things
29 /// in a general way even outside of the various pattern matching mechanics. Of course
30 /// this lint can still be used to highlight areas of interest and ensure a good understanding
31 /// of ownership semantics.
33 /// **Why is this bad?** It isn't bad in general. But in some contexts it can be desirable
34 /// because it increases ownership hints in the code, and will guard against some changes
37 /// **Known problems:** None.
41 /// This example shows the basic adjustments necessary to satisfy the lint. Note how
42 /// the matched expression is explicitly dereferenced with `*` and the `inner` variable
43 /// is bound to a shared borrow via `ref inner`.
47 /// let value = &Some(Box::new(23));
49 /// Some(inner) => println!("{}", inner),
50 /// None => println!("none"),
54 /// let value = &Some(Box::new(23));
56 /// Some(ref inner) => println!("{}", inner),
57 /// None => println!("none"),
61 /// The following example demonstrates one of the advantages of the more verbose style.
62 /// Note how the second version uses `ref mut a` to explicitly declare `a` a shared mutable
63 /// borrow, while `b` is simply taken by value. This ensures that the loop body cannot
64 /// accidentally modify the wrong part of the structure.
68 /// let mut values = vec![(2, 3), (3, 4)];
69 /// for (a, b) in &mut values {
74 /// let mut values = vec![(2, 3), (3, 4)];
75 /// for &mut (ref mut a, b) in &mut values {
79 pub PATTERN_TYPE_MISMATCH,
81 "type of pattern does not match the expression type"
84 declare_lint_pass!(PatternTypeMismatch => [PATTERN_TYPE_MISMATCH]);
86 impl<'tcx> LateLintPass<'tcx> for PatternTypeMismatch {
87 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
88 if let StmtKind::Local(ref local) = stmt.kind {
89 if let Some(init) = &local.init {
90 if let Some(init_ty) = cx.typeck_results().node_type_opt(init.hir_id) {
92 if in_external_macro(cx.sess(), pat.span) {
95 let deref_possible = match local.source {
96 LocalSource::Normal => DerefPossible::Possible,
97 _ => DerefPossible::Impossible,
99 apply_lint(cx, pat, init_ty, deref_possible);
105 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
106 if let ExprKind::Match(ref expr, arms, source) = expr.kind {
108 MatchSource::Normal | MatchSource::IfLetDesugar { .. } | MatchSource::WhileLetDesugar => {
109 if let Some(expr_ty) = cx.typeck_results().node_type_opt(expr.hir_id) {
110 'pattern_checks: for arm in arms {
112 if in_external_macro(cx.sess(), pat.span) {
113 continue 'pattern_checks;
115 if apply_lint(cx, pat, expr_ty, DerefPossible::Possible) {
116 break 'pattern_checks;
128 cx: &LateContext<'tcx>,
129 _: intravisit::FnKind<'tcx>,
131 body: &'tcx Body<'_>,
135 if let Some(fn_sig) = cx.typeck_results().liberated_fn_sigs().get(hir_id) {
136 for (param, ty) in body.params.iter().zip(fn_sig.inputs().iter()) {
137 apply_lint(cx, ¶m.pat, ty, DerefPossible::Impossible);
143 #[derive(Debug, Clone, Copy)]
149 fn apply_lint<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, expr_ty: Ty<'tcx>, deref_possible: DerefPossible) -> bool {
150 let maybe_mismatch = find_first_mismatch(cx, pat, expr_ty, Level::Top);
151 if let Some((span, mutability, level)) = maybe_mismatch {
154 PATTERN_TYPE_MISMATCH,
156 "type of pattern does not match the expression type",
159 "{}explicitly match against a `{}` pattern and adjust the enclosed variable bindings",
160 match (deref_possible, level) {
161 (DerefPossible::Possible, Level::Top) => "use `*` to dereference the match expression or ",
165 Mutability::Mut => "&mut _",
166 Mutability::Not => "&_",
176 #[derive(Debug, Copy, Clone)]
182 #[allow(rustc::usage_of_ty_tykind)]
183 fn find_first_mismatch<'tcx>(
184 cx: &LateContext<'tcx>,
188 ) -> Option<(Span, Mutability, Level)> {
189 if let PatKind::Ref(ref sub_pat, _) = pat.kind {
190 if let TyKind::Ref(_, sub_ty, _) = ty.kind {
191 return find_first_mismatch(cx, sub_pat, sub_ty, Level::Lower);
195 if let TyKind::Ref(_, _, mutability) = ty.kind {
196 if is_non_ref_pattern(&pat.kind) {
197 return Some((pat.span, mutability, level));
201 if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.kind {
202 if let TyKind::Adt(ref adt_def, ref substs_ref) = ty.kind {
203 if let Some(variant) = get_variant(adt_def, qpath) {
204 let field_defs = &variant.fields;
205 return find_first_mismatch_in_struct(cx, field_pats, field_defs, substs_ref);
210 if let PatKind::TupleStruct(ref qpath, ref pats, _) = pat.kind {
211 if let TyKind::Adt(ref adt_def, ref substs_ref) = ty.kind {
212 if let Some(variant) = get_variant(adt_def, qpath) {
213 let field_defs = &variant.fields;
214 let ty_iter = field_defs.iter().map(|field_def| field_def.ty(cx.tcx, substs_ref));
215 return find_first_mismatch_in_tuple(cx, pats, ty_iter);
220 if let PatKind::Tuple(ref pats, _) = pat.kind {
221 if let TyKind::Tuple(..) = ty.kind {
222 return find_first_mismatch_in_tuple(cx, pats, ty.tuple_fields());
226 if let PatKind::Or(sub_pats) = pat.kind {
227 for pat in sub_pats {
228 let maybe_mismatch = find_first_mismatch(cx, pat, ty, level);
229 if let Some(mismatch) = maybe_mismatch {
230 return Some(mismatch);
238 fn get_variant<'a>(adt_def: &'a AdtDef, qpath: &QPath<'_>) -> Option<&'a VariantDef> {
239 if adt_def.is_struct() {
240 if let Some(variant) = adt_def.variants.iter().next() {
241 return Some(variant);
245 if adt_def.is_enum() {
246 let pat_ident = last_path_segment(qpath).ident;
247 for variant in &adt_def.variants {
248 if variant.ident == pat_ident {
249 return Some(variant);
257 fn find_first_mismatch_in_tuple<'tcx, I>(
258 cx: &LateContext<'tcx>,
261 ) -> Option<(Span, Mutability, Level)>
263 I: IntoIterator<Item = Ty<'tcx>>,
265 let mut field_tys = ty_iter_src.into_iter();
266 'fields: for pat in pats {
267 let field_ty = if let Some(ty) = field_tys.next() {
273 let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
274 if let Some(mismatch) = maybe_mismatch {
275 return Some(mismatch);
282 fn find_first_mismatch_in_struct<'tcx>(
283 cx: &LateContext<'tcx>,
284 field_pats: &[FieldPat<'_>],
285 field_defs: &[FieldDef],
286 substs_ref: SubstsRef<'tcx>,
287 ) -> Option<(Span, Mutability, Level)> {
288 for field_pat in field_pats {
289 'definitions: for field_def in field_defs {
290 if field_pat.ident == field_def.ident {
291 let field_ty = field_def.ty(cx.tcx, substs_ref);
292 let pat = &field_pat.pat;
293 let maybe_mismatch = find_first_mismatch(cx, pat, field_ty, Level::Lower);
294 if let Some(mismatch) = maybe_mismatch {
295 return Some(mismatch);
305 fn is_non_ref_pattern(pat_kind: &PatKind<'_>) -> bool {
307 PatKind::Struct(..) | PatKind::Tuple(..) | PatKind::TupleStruct(..) | PatKind::Path(..) => true,
308 PatKind::Or(sub_pats) => sub_pats.iter().any(|pat| is_non_ref_pattern(&pat.kind)),