Skip to content

Commit

Permalink
Don't lint slice type annotations for byte strings
Browse files Browse the repository at this point in the history
  • Loading branch information
bpandreotti committed Jan 30, 2024
1 parent 455c07b commit 3106219
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
11 changes: 10 additions & 1 deletion clippy_lints/src/redundant_type_annotations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,6 @@ impl LateLintPass<'_> for RedundantTypeAnnotations {
match init_lit.node {
// In these cases the annotation is redundant
LitKind::Str(..)
| LitKind::ByteStr(..)
| LitKind::Byte(..)
| LitKind::Char(..)
| LitKind::Bool(..)
Expand All @@ -202,6 +201,16 @@ impl LateLintPass<'_> for RedundantTypeAnnotations {
}
},
LitKind::Err => (),
LitKind::ByteStr(..) => {
// We only lint if the type annotation is an array type (e.g. &[u8; 4]).
// If instead it is a slice (e.g. &[u8]) it may not be redundant, so we
// don't lint.
if let hir::TyKind::Ref(_, mut_ty) = ty.kind
&& matches!(mut_ty.ty.kind, hir::TyKind::Array(..))
{
span_lint(cx, REDUNDANT_TYPE_ANNOTATIONS, local.span, "redundant type annotation");
}
},
}
},
_ => (),
Expand Down
7 changes: 6 additions & 1 deletion tests/ui/redundant_type_annotations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,13 +196,18 @@ fn test_simple_types() {
let _var: &str = "test";
//~^ ERROR: redundant type annotation

let _var: &[u8] = b"test";
let _var: &[u8; 4] = b"test";
//~^ ERROR: redundant type annotation

let _var: bool = false;
//~^ ERROR: redundant type annotation
}

fn issue12212() {
// This should not be linted
let _var: &[u8] = b"test";
}

fn issue11190() {}

fn main() {}
4 changes: 2 additions & 2 deletions tests/ui/redundant_type_annotations.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ LL | let _var: &str = "test";
error: redundant type annotation
--> $DIR/redundant_type_annotations.rs:199:5
|
LL | let _var: &[u8] = b"test";
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
LL | let _var: &[u8; 4] = b"test";
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: redundant type annotation
--> $DIR/redundant_type_annotations.rs:202:5
Expand Down

0 comments on commit 3106219

Please sign in to comment.