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::SpanlessEq;
5 use clippy_utils::{get_parent_expr, is_lint_allowed, match_function_call, method_calls, paths};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, BorrowKind, Expr, ExprKind, LangItem, QPath};
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Spanned;
16 declare_clippy_lint! {
18 /// Checks for string appends of the form `x = x + y` (without
21 /// ### Why is this bad?
22 /// It's not really bad, but some people think that the
23 /// `.push_str(_)` method is more readable.
27 /// let mut x = "Hello".to_owned();
28 /// x = x + ", World";
32 /// x.push_str(", World");
34 pub STRING_ADD_ASSIGN,
36 "using `x = x + ..` where x is a `String` instead of `push_str()`"
39 declare_clippy_lint! {
41 /// Checks for all instances of `x + _` where `x` is of type
42 /// `String`, but only if [`string_add_assign`](#string_add_assign) does *not*
45 /// ### Why is this bad?
46 /// It's not bad in and of itself. However, this particular
47 /// `Add` implementation is asymmetric (the other operand need not be `String`,
48 /// but `x` does), while addition as mathematically defined is symmetric, also
49 /// the `String::push_str(_)` function is a perfectly good replacement.
50 /// Therefore, some dislike it and wish not to have it in their code.
52 /// That said, other people think that string addition, having a long tradition
53 /// in other languages is actually fine, which is why we decided to make this
54 /// particular lint `allow` by default.
58 /// let x = "Hello".to_owned();
63 "using `x + ..` where x is a `String` instead of `push_str()`"
66 declare_clippy_lint! {
68 /// Checks for the `as_bytes` method called on string literals
69 /// that contain only ASCII characters.
71 /// ### Why is this bad?
72 /// Byte string literals (e.g., `b"foo"`) can be used
73 /// instead. They are shorter but less discoverable than `as_bytes()`.
75 /// ### Known problems
76 /// `"str".as_bytes()` and the suggested replacement of `b"str"` are not
77 /// equivalent because they have different types. The former is `&[u8]`
78 /// while the latter is `&[u8; 3]`. That means in general they will have a
79 /// different set of methods and different trait implementations.
82 /// fn f(v: Vec<u8>) {}
84 /// f("...".as_bytes().to_owned()); // works
85 /// f(b"...".to_owned()); // does not work, because arg is [u8; 3] not Vec<u8>
87 /// fn g(r: impl std::io::Read) {}
89 /// g("...".as_bytes()); // works
90 /// g(b"..."); // does not work
93 /// The actual equivalent of `"str".as_bytes()` with the same type is not
94 /// `b"str"` but `&b"str"[..]`, which is a great deal of punctuation and not
95 /// more readable than a function call.
100 /// let bs = "a byte string".as_bytes();
103 /// let bs = b"a byte string";
105 pub STRING_LIT_AS_BYTES,
107 "calling `as_bytes` on a string literal instead of using a byte string literal"
110 declare_clippy_lint! {
112 /// Checks for slice operations on strings
114 /// ### Why is this bad?
115 /// UTF-8 characters span multiple bytes, and it is easy to inadvertently confuse character
116 /// counts and string indices. This may lead to panics, and should warrant some test cases
117 /// containing wide UTF-8 characters. This lint is most useful in code that should avoid
118 /// panics at all costs.
120 /// ### Known problems
121 /// Probably lots of false positives. If an index comes from a known valid position (e.g.
122 /// obtained via `char_indices` over the same string), it is totally OK.
125 /// ```rust,should_panic
126 /// &"Ölkanne"[1..];
133 declare_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN, STRING_SLICE]);
135 impl<'tcx> LateLintPass<'tcx> for StringAdd {
136 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
137 if in_external_macro(cx.sess(), e.span) {
143 node: BinOpKind::Add, ..
148 if is_string(cx, left) {
149 if !is_lint_allowed(cx, STRING_ADD_ASSIGN, e.hir_id) {
150 let parent = get_parent_expr(cx, e);
151 if let Some(p) = parent {
152 if let ExprKind::Assign(target, _, _) = p.kind {
153 // avoid duplicate matches
154 if SpanlessEq::new(cx).eq_expr(target, left) {
164 "you added something to a string. Consider using `String::push_str()` instead",
168 ExprKind::Assign(target, src, _) => {
169 if is_string(cx, target) && is_add(cx, src, target) {
174 "you assigned the result of adding something to this string. Consider using \
175 `String::push_str()` instead",
179 ExprKind::Index(target, _idx) => {
180 let e_ty = cx.typeck_results().expr_ty(target).peel_refs();
181 if matches!(e_ty.kind(), ty::Str) || is_type_diagnostic_item(cx, e_ty, sym::String) {
186 "indexing into a string may panic if the index is within a UTF-8 character",
195 fn is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
196 is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(e).peel_refs(), sym::String)
199 fn is_add(cx: &LateContext<'_>, src: &Expr<'_>, target: &Expr<'_>) -> bool {
203 node: BinOpKind::Add, ..
207 ) => SpanlessEq::new(cx).eq_expr(target, left),
208 ExprKind::Block(block, _) => {
209 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
215 declare_clippy_lint! {
217 /// Check if the string is transformed to byte array and casted back to string.
219 /// ### Why is this bad?
220 /// It's unnecessary, the string can be used directly.
224 /// let _ = std::str::from_utf8(&"Hello World!".as_bytes()[6..11]).unwrap();
226 /// could be written as
228 /// let _ = &"Hello World!"[6..11];
230 pub STRING_FROM_UTF8_AS_BYTES,
232 "casting string slices to byte slices and back"
235 // Max length a b"foo" string can take
236 const MAX_LENGTH_BYTE_STRING_LIT: usize = 32;
238 declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES, STRING_FROM_UTF8_AS_BYTES]);
240 impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes {
241 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
242 use rustc_ast::LitKind;
245 // Find std::str::converts::from_utf8
246 if let Some(args) = match_function_call(cx, e, &paths::STR_FROM_UTF8);
248 // Find string::as_bytes
249 if let ExprKind::AddrOf(BorrowKind::Ref, _, args) = args[0].kind;
250 if let ExprKind::Index(left, right) = args.kind;
251 let (method_names, expressions, _) = method_calls(left, 1);
252 if method_names.len() == 1;
253 if expressions.len() == 1;
254 if expressions[0].len() == 1;
255 if method_names[0] == sym!(as_bytes);
258 if let ExprKind::Struct(QPath::LangItem(LangItem::Range, _), _, _) = right.kind;
261 let mut applicability = Applicability::MachineApplicable;
262 let string_expression = &expressions[0][0];
264 let snippet_app = snippet_with_applicability(
266 string_expression.span, "..",
272 STRING_FROM_UTF8_AS_BYTES,
274 "calling a slice of `as_bytes()` with `from_utf8` should be not necessary",
276 format!("Some(&{}[{}])", snippet_app, snippet(cx, right.span, "..")),
283 if let ExprKind::MethodCall(path, _, args, _) = &e.kind;
284 if path.ident.name == sym!(as_bytes);
285 if let ExprKind::Lit(lit) = &args[0].kind;
286 if let LitKind::Str(lit_content, _) = &lit.node;
288 let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
289 let mut applicability = Applicability::MachineApplicable;
290 if callsite.starts_with("include_str!") {
295 "calling `as_bytes()` on `include_str!(..)`",
296 "consider using `include_bytes!(..)` instead",
297 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen(
304 } else if lit_content.as_str().is_ascii()
305 && lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT
306 && !args[0].span.from_expansion()
312 "calling `as_bytes()` on a string literal",
313 "consider using a byte string literal instead",
316 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)
325 if let ExprKind::MethodCall(path, _, [recv], _) = &e.kind;
326 if path.ident.name == sym!(into_bytes);
327 if let ExprKind::MethodCall(path, _, [recv], _) = &recv.kind;
328 if matches!(&*path.ident.name.as_str(), "to_owned" | "to_string");
329 if let ExprKind::Lit(lit) = &recv.kind;
330 if let LitKind::Str(lit_content, _) = &lit.node;
332 if lit_content.as_str().is_ascii();
333 if lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT;
334 if !recv.span.from_expansion();
336 let mut applicability = Applicability::MachineApplicable;
342 "calling `into_bytes()` on a string literal",
343 "consider using a byte string literal instead",
346 snippet_with_applicability(cx, recv.span, r#""..""#, &mut applicability)
355 declare_clippy_lint! {
357 /// This lint checks for `.to_string()` method calls on values of type `&str`.
359 /// ### Why is this bad?
360 /// The `to_string` method is also used on other types to convert them to a string.
361 /// When called on a `&str` it turns the `&str` into the owned variant `String`, which can be better
362 /// expressed with `.to_owned()`.
366 /// // example code where clippy issues a warning
367 /// let _ = "str".to_string();
371 /// // example code which does not raise clippy warning
372 /// let _ = "str".to_owned();
376 "using `to_string()` on a `&str`, which should be `to_owned()`"
379 declare_lint_pass!(StrToString => [STR_TO_STRING]);
381 impl LateLintPass<'_> for StrToString {
382 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
384 if let ExprKind::MethodCall(path, _, [self_arg, ..], _) = &expr.kind;
385 if path.ident.name == sym!(to_string);
386 let ty = cx.typeck_results().expr_ty(self_arg);
387 if let ty::Ref(_, ty, ..) = ty.kind();
388 if *ty.kind() == ty::Str;
394 "`to_string()` called on a `&str`",
396 "consider using `.to_owned()`",
403 declare_clippy_lint! {
405 /// This lint checks for `.to_string()` method calls on values of type `String`.
407 /// ### Why is this bad?
408 /// The `to_string` method is also used on other types to convert them to a string.
409 /// When called on a `String` it only clones the `String`, which can be better expressed with `.clone()`.
413 /// // example code where clippy issues a warning
414 /// let msg = String::from("Hello World");
415 /// let _ = msg.to_string();
419 /// // example code which does not raise clippy warning
420 /// let msg = String::from("Hello World");
421 /// let _ = msg.clone();
423 pub STRING_TO_STRING,
425 "using `to_string()` on a `String`, which should be `clone()`"
428 declare_lint_pass!(StringToString => [STRING_TO_STRING]);
430 impl LateLintPass<'_> for StringToString {
431 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
433 if let ExprKind::MethodCall(path, _, [self_arg, ..], _) = &expr.kind;
434 if path.ident.name == sym!(to_string);
435 let ty = cx.typeck_results().expr_ty(self_arg);
436 if is_type_diagnostic_item(cx, ty, sym::String);
442 "`to_string()` called on a `String`",
444 "consider using `.clone()`",