Skip to content

Commit

Permalink
Auto merge of #13281 - alex-semenyuk:string_slice_fix, r=y21
Browse files Browse the repository at this point in the history
 Trigger [`string_slice`] if expression is reference to `&str`

Close #12708
changelog: [`string_slice`]: trigger lint if expression is reference to `&str`
  • Loading branch information
bors committed Aug 19, 2024
2 parents e7d9fcf + 7b7cf44 commit d0e637d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
2 changes: 1 addition & 1 deletion clippy_lints/src/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ impl<'tcx> LateLintPass<'tcx> for StringAdd {
}
},
ExprKind::Index(target, _idx, _) => {
let e_ty = cx.typeck_results().expr_ty(target).peel_refs();
let e_ty = cx.typeck_results().expr_ty_adjusted(target).peel_refs();
if e_ty.is_str() || is_type_lang_item(cx, e_ty, LangItem::String) {
span_lint(
cx,
Expand Down
5 changes: 5 additions & 0 deletions tests/ui/string_slice.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

#[warn(clippy::string_slice)]
#[allow(clippy::no_effect)]

Expand All @@ -11,4 +13,7 @@ fn main() {
let s = String::from(m);
&s[0..2];
//~^ ERROR: indexing into a string may panic if the index is within a UTF-8 character
let a = Cow::Borrowed("foo");
&a[0..3];
//~^ ERROR: indexing into a string may panic if the index is within a UTF-8 character
}
14 changes: 10 additions & 4 deletions tests/ui/string_slice.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: indexing into a string may panic if the index is within a UTF-8 character
--> tests/ui/string_slice.rs:5:6
--> tests/ui/string_slice.rs:7:6
|
LL | &"Ölkanne"[1..];
| ^^^^^^^^^^^^^^
Expand All @@ -8,16 +8,22 @@ LL | &"Ölkanne"[1..];
= help: to override `-D warnings` add `#[allow(clippy::string_slice)]`

error: indexing into a string may panic if the index is within a UTF-8 character
--> tests/ui/string_slice.rs:9:6
--> tests/ui/string_slice.rs:11:6
|
LL | &m[2..5];
| ^^^^^^^

error: indexing into a string may panic if the index is within a UTF-8 character
--> tests/ui/string_slice.rs:12:6
--> tests/ui/string_slice.rs:14:6
|
LL | &s[0..2];
| ^^^^^^^

error: aborting due to 3 previous errors
error: indexing into a string may panic if the index is within a UTF-8 character
--> tests/ui/string_slice.rs:17:6
|
LL | &a[0..3];
| ^^^^^^^

error: aborting due to 4 previous errors

0 comments on commit d0e637d

Please sign in to comment.