1 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::source::{snippet, snippet_with_applicability};
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use clippy_utils::{get_parent_expr, is_lint_allowed, match_function_call, method_calls, paths};
5 use clippy_utils::{peel_blocks, SpanlessEq};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::def_id::DefId;
9 use rustc_hir::{BinOpKind, BorrowKind, Expr, ExprKind, LangItem, QPath};
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_middle::lint::in_external_macro;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::source_map::Spanned;
17 declare_clippy_lint! {
19 /// Checks for string appends of the form `x = x + y` (without
22 /// ### Why is this bad?
23 /// It's not really bad, but some people think that the
24 /// `.push_str(_)` method is more readable.
28 /// let mut x = "Hello".to_owned();
29 /// x = x + ", World";
33 /// x.push_str(", World");
35 #[clippy::version = "pre 1.29.0"]
36 pub STRING_ADD_ASSIGN,
38 "using `x = x + ..` where x is a `String` instead of `push_str()`"
41 declare_clippy_lint! {
43 /// Checks for all instances of `x + _` where `x` is of type
44 /// `String`, but only if [`string_add_assign`](#string_add_assign) does *not*
47 /// ### Why is this bad?
48 /// It's not bad in and of itself. However, this particular
49 /// `Add` implementation is asymmetric (the other operand need not be `String`,
50 /// but `x` does), while addition as mathematically defined is symmetric, also
51 /// the `String::push_str(_)` function is a perfectly good replacement.
52 /// Therefore, some dislike it and wish not to have it in their code.
54 /// That said, other people think that string addition, having a long tradition
55 /// in other languages is actually fine, which is why we decided to make this
56 /// particular lint `allow` by default.
60 /// let x = "Hello".to_owned();
63 #[clippy::version = "pre 1.29.0"]
66 "using `x + ..` where x is a `String` instead of `push_str()`"
69 declare_clippy_lint! {
71 /// Checks for the `as_bytes` method called on string literals
72 /// that contain only ASCII characters.
74 /// ### Why is this bad?
75 /// Byte string literals (e.g., `b"foo"`) can be used
76 /// instead. They are shorter but less discoverable than `as_bytes()`.
78 /// ### Known problems
79 /// `"str".as_bytes()` and the suggested replacement of `b"str"` are not
80 /// equivalent because they have different types. The former is `&[u8]`
81 /// while the latter is `&[u8; 3]`. That means in general they will have a
82 /// different set of methods and different trait implementations.
85 /// fn f(v: Vec<u8>) {}
87 /// f("...".as_bytes().to_owned()); // works
88 /// f(b"...".to_owned()); // does not work, because arg is [u8; 3] not Vec<u8>
90 /// fn g(r: impl std::io::Read) {}
92 /// g("...".as_bytes()); // works
93 /// g(b"..."); // does not work
96 /// The actual equivalent of `"str".as_bytes()` with the same type is not
97 /// `b"str"` but `&b"str"[..]`, which is a great deal of punctuation and not
98 /// more readable than a function call.
102 /// let bstr = "a byte string".as_bytes();
107 /// let bstr = b"a byte string";
109 #[clippy::version = "pre 1.29.0"]
110 pub STRING_LIT_AS_BYTES,
112 "calling `as_bytes` on a string literal instead of using a byte string literal"
115 declare_clippy_lint! {
117 /// Checks for slice operations on strings
119 /// ### Why is this bad?
120 /// UTF-8 characters span multiple bytes, and it is easy to inadvertently confuse character
121 /// counts and string indices. This may lead to panics, and should warrant some test cases
122 /// containing wide UTF-8 characters. This lint is most useful in code that should avoid
123 /// panics at all costs.
125 /// ### Known problems
126 /// Probably lots of false positives. If an index comes from a known valid position (e.g.
127 /// obtained via `char_indices` over the same string), it is totally OK.
130 /// ```rust,should_panic
131 /// &"Ölkanne"[1..];
133 #[clippy::version = "1.58.0"]
139 declare_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN, STRING_SLICE]);
141 impl<'tcx> LateLintPass<'tcx> for StringAdd {
142 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
143 if in_external_macro(cx.sess(), e.span) {
149 node: BinOpKind::Add, ..
154 if is_string(cx, left) {
155 if !is_lint_allowed(cx, STRING_ADD_ASSIGN, e.hir_id) {
156 let parent = get_parent_expr(cx, e);
157 if let Some(p) = parent {
158 if let ExprKind::Assign(target, _, _) = p.kind {
159 // avoid duplicate matches
160 if SpanlessEq::new(cx).eq_expr(target, left) {
170 "you added something to a string. Consider using `String::push_str()` instead",
174 ExprKind::Assign(target, src, _) => {
175 if is_string(cx, target) && is_add(cx, src, target) {
180 "you assigned the result of adding something to this string. Consider using \
181 `String::push_str()` instead",
185 ExprKind::Index(target, _idx) => {
186 let e_ty = cx.typeck_results().expr_ty(target).peel_refs();
187 if matches!(e_ty.kind(), ty::Str) || is_type_diagnostic_item(cx, e_ty, sym::String) {
192 "indexing into a string may panic if the index is within a UTF-8 character",
201 fn is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
202 is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(e).peel_refs(), sym::String)
205 fn is_add(cx: &LateContext<'_>, src: &Expr<'_>, target: &Expr<'_>) -> bool {
206 match peel_blocks(src).kind {
209 node: BinOpKind::Add, ..
213 ) => SpanlessEq::new(cx).eq_expr(target, left),
218 declare_clippy_lint! {
220 /// Check if the string is transformed to byte array and casted back to string.
222 /// ### Why is this bad?
223 /// It's unnecessary, the string can be used directly.
227 /// std::str::from_utf8(&"Hello World!".as_bytes()[6..11]).unwrap();
232 /// &"Hello World!"[6..11];
234 #[clippy::version = "1.50.0"]
235 pub STRING_FROM_UTF8_AS_BYTES,
237 "casting string slices to byte slices and back"
240 // Max length a b"foo" string can take
241 const MAX_LENGTH_BYTE_STRING_LIT: usize = 32;
243 declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES, STRING_FROM_UTF8_AS_BYTES]);
245 impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes {
246 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
247 use rustc_ast::LitKind;
250 // Find std::str::converts::from_utf8
251 if let Some(args) = match_function_call(cx, e, &paths::STR_FROM_UTF8);
253 // Find string::as_bytes
254 if let ExprKind::AddrOf(BorrowKind::Ref, _, args) = args[0].kind;
255 if let ExprKind::Index(left, right) = args.kind;
256 let (method_names, expressions, _) = method_calls(left, 1);
257 if method_names.len() == 1;
258 if expressions.len() == 1;
259 if expressions[0].len() == 1;
260 if method_names[0] == sym!(as_bytes);
263 if let ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), _, _) = right.kind;
266 let mut applicability = Applicability::MachineApplicable;
267 let string_expression = &expressions[0][0];
269 let snippet_app = snippet_with_applicability(
271 string_expression.span, "..",
277 STRING_FROM_UTF8_AS_BYTES,
279 "calling a slice of `as_bytes()` with `from_utf8` should be not necessary",
281 format!("Some(&{}[{}])", snippet_app, snippet(cx, right.span, "..")),
288 if let ExprKind::MethodCall(path, args, _) = &e.kind;
289 if path.ident.name == sym!(as_bytes);
290 if let ExprKind::Lit(lit) = &args[0].kind;
291 if let LitKind::Str(lit_content, _) = &lit.node;
293 let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
294 let mut applicability = Applicability::MachineApplicable;
295 if callsite.starts_with("include_str!") {
300 "calling `as_bytes()` on `include_str!(..)`",
301 "consider using `include_bytes!(..)` instead",
302 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen(
309 } else if lit_content.as_str().is_ascii()
310 && lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT
311 && !args[0].span.from_expansion()
317 "calling `as_bytes()` on a string literal",
318 "consider using a byte string literal instead",
321 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)
330 if let ExprKind::MethodCall(path, [recv], _) = &e.kind;
331 if path.ident.name == sym!(into_bytes);
332 if let ExprKind::MethodCall(path, [recv], _) = &recv.kind;
333 if matches!(path.ident.name.as_str(), "to_owned" | "to_string");
334 if let ExprKind::Lit(lit) = &recv.kind;
335 if let LitKind::Str(lit_content, _) = &lit.node;
337 if lit_content.as_str().is_ascii();
338 if lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT;
339 if !recv.span.from_expansion();
341 let mut applicability = Applicability::MachineApplicable;
347 "calling `into_bytes()` on a string literal",
348 "consider using a byte string literal instead",
351 snippet_with_applicability(cx, recv.span, r#""..""#, &mut applicability)
360 declare_clippy_lint! {
362 /// This lint checks for `.to_string()` method calls on values of type `&str`.
364 /// ### Why is this bad?
365 /// The `to_string` method is also used on other types to convert them to a string.
366 /// When called on a `&str` it turns the `&str` into the owned variant `String`, which can be better
367 /// expressed with `.to_owned()`.
371 /// // example code where clippy issues a warning
372 /// let _ = "str".to_string();
376 /// // example code which does not raise clippy warning
377 /// let _ = "str".to_owned();
379 #[clippy::version = "pre 1.29.0"]
382 "using `to_string()` on a `&str`, which should be `to_owned()`"
385 declare_lint_pass!(StrToString => [STR_TO_STRING]);
387 impl<'tcx> LateLintPass<'tcx> for StrToString {
388 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
390 if let ExprKind::MethodCall(path, [self_arg, ..], _) = &expr.kind;
391 if path.ident.name == sym!(to_string);
392 let ty = cx.typeck_results().expr_ty(self_arg);
393 if let ty::Ref(_, ty, ..) = ty.kind();
394 if *ty.kind() == ty::Str;
400 "`to_string()` called on a `&str`",
402 "consider using `.to_owned()`",
409 declare_clippy_lint! {
411 /// This lint checks for `.to_string()` method calls on values of type `String`.
413 /// ### Why is this bad?
414 /// The `to_string` method is also used on other types to convert them to a string.
415 /// When called on a `String` it only clones the `String`, which can be better expressed with `.clone()`.
419 /// // example code where clippy issues a warning
420 /// let msg = String::from("Hello World");
421 /// let _ = msg.to_string();
425 /// // example code which does not raise clippy warning
426 /// let msg = String::from("Hello World");
427 /// let _ = msg.clone();
429 #[clippy::version = "pre 1.29.0"]
430 pub STRING_TO_STRING,
432 "using `to_string()` on a `String`, which should be `clone()`"
435 declare_lint_pass!(StringToString => [STRING_TO_STRING]);
437 impl<'tcx> LateLintPass<'tcx> for StringToString {
438 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
440 if let ExprKind::MethodCall(path, [self_arg, ..], _) = &expr.kind;
441 if path.ident.name == sym!(to_string);
442 let ty = cx.typeck_results().expr_ty(self_arg);
443 if is_type_diagnostic_item(cx, ty, sym::String);
449 "`to_string()` called on a `String`",
451 "consider using `.clone()`",
458 declare_clippy_lint! {
460 /// Warns about calling `str::trim` (or variants) before `str::split_whitespace`.
462 /// ### Why is this bad?
463 /// `split_whitespace` already ignores leading and trailing whitespace.
467 /// " A B C ".trim().split_whitespace();
471 /// " A B C ".split_whitespace();
473 #[clippy::version = "1.62.0"]
474 pub TRIM_SPLIT_WHITESPACE,
476 "using `str::trim()` or alike before `str::split_whitespace`"
478 declare_lint_pass!(TrimSplitWhitespace => [TRIM_SPLIT_WHITESPACE]);
480 impl<'tcx> LateLintPass<'tcx> for TrimSplitWhitespace {
481 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
482 let tyckres = cx.typeck_results();
484 if let ExprKind::MethodCall(path, [split_recv], split_ws_span) = expr.kind;
485 if path.ident.name == sym!(split_whitespace);
486 if let Some(split_ws_def_id) = tyckres.type_dependent_def_id(expr.hir_id);
487 if cx.tcx.is_diagnostic_item(sym::str_split_whitespace, split_ws_def_id);
488 if let ExprKind::MethodCall(path, [_trim_recv], trim_span) = split_recv.kind;
489 if let trim_fn_name @ ("trim" | "trim_start" | "trim_end") = path.ident.name.as_str();
490 if let Some(trim_def_id) = tyckres.type_dependent_def_id(split_recv.hir_id);
491 if is_one_of_trim_diagnostic_items(cx, trim_def_id);
495 TRIM_SPLIT_WHITESPACE,
496 trim_span.with_hi(split_ws_span.lo()),
497 &format!("found call to `str::{}` before `str::split_whitespace`", trim_fn_name),
498 &format!("remove `{}()`", trim_fn_name),
500 Applicability::MachineApplicable,
507 fn is_one_of_trim_diagnostic_items(cx: &LateContext<'_>, trim_def_id: DefId) -> bool {
508 cx.tcx.is_diagnostic_item(sym::str_trim, trim_def_id)
509 || cx.tcx.is_diagnostic_item(sym::str_trim_start, trim_def_id)
510 || cx.tcx.is_diagnostic_item(sym::str_trim_end, trim_def_id)