]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/strings.rs
Rollup merge of #91861 - juniorbassani:use-from-array-in-collections-examples, r...
[rust.git] / src / tools / clippy / clippy_lints / src / strings.rs
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::{BinOpKind, BorrowKind, Expr, ExprKind, LangItem, QPath};
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_middle::ty;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Spanned;
14 use rustc_span::sym;
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Checks for string appends of the form `x = x + y` (without
19     /// `let`!).
20     ///
21     /// ### Why is this bad?
22     /// It's not really bad, but some people think that the
23     /// `.push_str(_)` method is more readable.
24     ///
25     /// ### Example
26     /// ```rust
27     /// let mut x = "Hello".to_owned();
28     /// x = x + ", World";
29     ///
30     /// // More readable
31     /// x += ", World";
32     /// x.push_str(", World");
33     /// ```
34     #[clippy::version = "pre 1.29.0"]
35     pub STRING_ADD_ASSIGN,
36     pedantic,
37     "using `x = x + ..` where x is a `String` instead of `push_str()`"
38 }
39
40 declare_clippy_lint! {
41     /// ### What it does
42     /// Checks for all instances of `x + _` where `x` is of type
43     /// `String`, but only if [`string_add_assign`](#string_add_assign) does *not*
44     /// match.
45     ///
46     /// ### Why is this bad?
47     /// It's not bad in and of itself. However, this particular
48     /// `Add` implementation is asymmetric (the other operand need not be `String`,
49     /// but `x` does), while addition as mathematically defined is symmetric, also
50     /// the `String::push_str(_)` function is a perfectly good replacement.
51     /// Therefore, some dislike it and wish not to have it in their code.
52     ///
53     /// That said, other people think that string addition, having a long tradition
54     /// in other languages is actually fine, which is why we decided to make this
55     /// particular lint `allow` by default.
56     ///
57     /// ### Example
58     /// ```rust
59     /// let x = "Hello".to_owned();
60     /// x + ", World";
61     /// ```
62     #[clippy::version = "pre 1.29.0"]
63     pub STRING_ADD,
64     restriction,
65     "using `x + ..` where x is a `String` instead of `push_str()`"
66 }
67
68 declare_clippy_lint! {
69     /// ### What it does
70     /// Checks for the `as_bytes` method called on string literals
71     /// that contain only ASCII characters.
72     ///
73     /// ### Why is this bad?
74     /// Byte string literals (e.g., `b"foo"`) can be used
75     /// instead. They are shorter but less discoverable than `as_bytes()`.
76     ///
77     /// ### Known problems
78     /// `"str".as_bytes()` and the suggested replacement of `b"str"` are not
79     /// equivalent because they have different types. The former is `&[u8]`
80     /// while the latter is `&[u8; 3]`. That means in general they will have a
81     /// different set of methods and different trait implementations.
82     ///
83     /// ```compile_fail
84     /// fn f(v: Vec<u8>) {}
85     ///
86     /// f("...".as_bytes().to_owned()); // works
87     /// f(b"...".to_owned()); // does not work, because arg is [u8; 3] not Vec<u8>
88     ///
89     /// fn g(r: impl std::io::Read) {}
90     ///
91     /// g("...".as_bytes()); // works
92     /// g(b"..."); // does not work
93     /// ```
94     ///
95     /// The actual equivalent of `"str".as_bytes()` with the same type is not
96     /// `b"str"` but `&b"str"[..]`, which is a great deal of punctuation and not
97     /// more readable than a function call.
98     ///
99     /// ### Example
100     /// ```rust
101     /// // Bad
102     /// let bs = "a byte string".as_bytes();
103     ///
104     /// // Good
105     /// let bs = b"a byte string";
106     /// ```
107     #[clippy::version = "pre 1.29.0"]
108     pub STRING_LIT_AS_BYTES,
109     nursery,
110     "calling `as_bytes` on a string literal instead of using a byte string literal"
111 }
112
113 declare_clippy_lint! {
114     /// ### What it does
115     /// Checks for slice operations on strings
116     ///
117     /// ### Why is this bad?
118     /// UTF-8 characters span multiple bytes, and it is easy to inadvertently confuse character
119     /// counts and string indices. This may lead to panics, and should warrant some test cases
120     /// containing wide UTF-8 characters. This lint is most useful in code that should avoid
121     /// panics at all costs.
122     ///
123     /// ### Known problems
124     /// Probably lots of false positives. If an index comes from a known valid position (e.g.
125     /// obtained via `char_indices` over the same string), it is totally OK.
126     ///
127     /// # Example
128     /// ```rust,should_panic
129     /// &"Ölkanne"[1..];
130     /// ```
131     #[clippy::version = "1.58.0"]
132     pub STRING_SLICE,
133     restriction,
134     "slicing a string"
135 }
136
137 declare_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN, STRING_SLICE]);
138
139 impl<'tcx> LateLintPass<'tcx> for StringAdd {
140     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
141         if in_external_macro(cx.sess(), e.span) {
142             return;
143         }
144         match e.kind {
145             ExprKind::Binary(
146                 Spanned {
147                     node: BinOpKind::Add, ..
148                 },
149                 left,
150                 _,
151             ) => {
152                 if is_string(cx, left) {
153                     if !is_lint_allowed(cx, STRING_ADD_ASSIGN, e.hir_id) {
154                         let parent = get_parent_expr(cx, e);
155                         if let Some(p) = parent {
156                             if let ExprKind::Assign(target, _, _) = p.kind {
157                                 // avoid duplicate matches
158                                 if SpanlessEq::new(cx).eq_expr(target, left) {
159                                     return;
160                                 }
161                             }
162                         }
163                     }
164                     span_lint(
165                         cx,
166                         STRING_ADD,
167                         e.span,
168                         "you added something to a string. Consider using `String::push_str()` instead",
169                     );
170                 }
171             },
172             ExprKind::Assign(target, src, _) => {
173                 if is_string(cx, target) && is_add(cx, src, target) {
174                     span_lint(
175                         cx,
176                         STRING_ADD_ASSIGN,
177                         e.span,
178                         "you assigned the result of adding something to this string. Consider using \
179                          `String::push_str()` instead",
180                     );
181                 }
182             },
183             ExprKind::Index(target, _idx) => {
184                 let e_ty = cx.typeck_results().expr_ty(target).peel_refs();
185                 if matches!(e_ty.kind(), ty::Str) || is_type_diagnostic_item(cx, e_ty, sym::String) {
186                     span_lint(
187                         cx,
188                         STRING_SLICE,
189                         e.span,
190                         "indexing into a string may panic if the index is within a UTF-8 character",
191                     );
192                 }
193             },
194             _ => {},
195         }
196     }
197 }
198
199 fn is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
200     is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(e).peel_refs(), sym::String)
201 }
202
203 fn is_add(cx: &LateContext<'_>, src: &Expr<'_>, target: &Expr<'_>) -> bool {
204     match peel_blocks(src).kind {
205         ExprKind::Binary(
206             Spanned {
207                 node: BinOpKind::Add, ..
208             },
209             left,
210             _,
211         ) => SpanlessEq::new(cx).eq_expr(target, left),
212         _ => false,
213     }
214 }
215
216 declare_clippy_lint! {
217     /// ### What it does
218     /// Check if the string is transformed to byte array and casted back to string.
219     ///
220     /// ### Why is this bad?
221     /// It's unnecessary, the string can be used directly.
222     ///
223     /// ### Example
224     /// ```rust
225     /// let _ = std::str::from_utf8(&"Hello World!".as_bytes()[6..11]).unwrap();
226     /// ```
227     /// could be written as
228     /// ```rust
229     /// let _ = &"Hello World!"[6..11];
230     /// ```
231     #[clippy::version = "1.50.0"]
232     pub STRING_FROM_UTF8_AS_BYTES,
233     complexity,
234     "casting string slices to byte slices and back"
235 }
236
237 // Max length a b"foo" string can take
238 const MAX_LENGTH_BYTE_STRING_LIT: usize = 32;
239
240 declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES, STRING_FROM_UTF8_AS_BYTES]);
241
242 impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes {
243     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
244         use rustc_ast::LitKind;
245
246         if_chain! {
247             // Find std::str::converts::from_utf8
248             if let Some(args) = match_function_call(cx, e, &paths::STR_FROM_UTF8);
249
250             // Find string::as_bytes
251             if let ExprKind::AddrOf(BorrowKind::Ref, _, args) = args[0].kind;
252             if let ExprKind::Index(left, right) = args.kind;
253             let (method_names, expressions, _) = method_calls(left, 1);
254             if method_names.len() == 1;
255             if expressions.len() == 1;
256             if expressions[0].len() == 1;
257             if method_names[0] == sym!(as_bytes);
258
259             // Check for slicer
260             if let ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), _, _) = right.kind;
261
262             then {
263                 let mut applicability = Applicability::MachineApplicable;
264                 let string_expression = &expressions[0][0];
265
266                 let snippet_app = snippet_with_applicability(
267                     cx,
268                     string_expression.span, "..",
269                     &mut applicability,
270                 );
271
272                 span_lint_and_sugg(
273                     cx,
274                     STRING_FROM_UTF8_AS_BYTES,
275                     e.span,
276                     "calling a slice of `as_bytes()` with `from_utf8` should be not necessary",
277                     "try",
278                     format!("Some(&{}[{}])", snippet_app, snippet(cx, right.span, "..")),
279                     applicability
280                 )
281             }
282         }
283
284         if_chain! {
285             if let ExprKind::MethodCall(path, args, _) = &e.kind;
286             if path.ident.name == sym!(as_bytes);
287             if let ExprKind::Lit(lit) = &args[0].kind;
288             if let LitKind::Str(lit_content, _) = &lit.node;
289             then {
290                 let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
291                 let mut applicability = Applicability::MachineApplicable;
292                 if callsite.starts_with("include_str!") {
293                     span_lint_and_sugg(
294                         cx,
295                         STRING_LIT_AS_BYTES,
296                         e.span,
297                         "calling `as_bytes()` on `include_str!(..)`",
298                         "consider using `include_bytes!(..)` instead",
299                         snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen(
300                             "include_str",
301                             "include_bytes",
302                             1,
303                         ),
304                         applicability,
305                     );
306                 } else if lit_content.as_str().is_ascii()
307                     && lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT
308                     && !args[0].span.from_expansion()
309                 {
310                     span_lint_and_sugg(
311                         cx,
312                         STRING_LIT_AS_BYTES,
313                         e.span,
314                         "calling `as_bytes()` on a string literal",
315                         "consider using a byte string literal instead",
316                         format!(
317                             "b{}",
318                             snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)
319                         ),
320                         applicability,
321                     );
322                 }
323             }
324         }
325
326         if_chain! {
327             if let ExprKind::MethodCall(path, [recv], _) = &e.kind;
328             if path.ident.name == sym!(into_bytes);
329             if let ExprKind::MethodCall(path, [recv], _) = &recv.kind;
330             if matches!(path.ident.name.as_str(), "to_owned" | "to_string");
331             if let ExprKind::Lit(lit) = &recv.kind;
332             if let LitKind::Str(lit_content, _) = &lit.node;
333
334             if lit_content.as_str().is_ascii();
335             if lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT;
336             if !recv.span.from_expansion();
337             then {
338                 let mut applicability = Applicability::MachineApplicable;
339
340                 span_lint_and_sugg(
341                     cx,
342                     STRING_LIT_AS_BYTES,
343                     e.span,
344                     "calling `into_bytes()` on a string literal",
345                     "consider using a byte string literal instead",
346                     format!(
347                         "b{}.to_vec()",
348                         snippet_with_applicability(cx, recv.span, r#""..""#, &mut applicability)
349                     ),
350                     applicability,
351                 );
352             }
353         }
354     }
355 }
356
357 declare_clippy_lint! {
358     /// ### What it does
359     /// This lint checks for `.to_string()` method calls on values of type `&str`.
360     ///
361     /// ### Why is this bad?
362     /// The `to_string` method is also used on other types to convert them to a string.
363     /// When called on a `&str` it turns the `&str` into the owned variant `String`, which can be better
364     /// expressed with `.to_owned()`.
365     ///
366     /// ### Example
367     /// ```rust
368     /// // example code where clippy issues a warning
369     /// let _ = "str".to_string();
370     /// ```
371     /// Use instead:
372     /// ```rust
373     /// // example code which does not raise clippy warning
374     /// let _ = "str".to_owned();
375     /// ```
376     #[clippy::version = "pre 1.29.0"]
377     pub STR_TO_STRING,
378     restriction,
379     "using `to_string()` on a `&str`, which should be `to_owned()`"
380 }
381
382 declare_lint_pass!(StrToString => [STR_TO_STRING]);
383
384 impl<'tcx> LateLintPass<'tcx> for StrToString {
385     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
386         if_chain! {
387             if let ExprKind::MethodCall(path, [self_arg, ..], _) = &expr.kind;
388             if path.ident.name == sym!(to_string);
389             let ty = cx.typeck_results().expr_ty(self_arg);
390             if let ty::Ref(_, ty, ..) = ty.kind();
391             if *ty.kind() == ty::Str;
392             then {
393                 span_lint_and_help(
394                     cx,
395                     STR_TO_STRING,
396                     expr.span,
397                     "`to_string()` called on a `&str`",
398                     None,
399                     "consider using `.to_owned()`",
400                 );
401             }
402         }
403     }
404 }
405
406 declare_clippy_lint! {
407     /// ### What it does
408     /// This lint checks for `.to_string()` method calls on values of type `String`.
409     ///
410     /// ### Why is this bad?
411     /// The `to_string` method is also used on other types to convert them to a string.
412     /// When called on a `String` it only clones the `String`, which can be better expressed with `.clone()`.
413     ///
414     /// ### Example
415     /// ```rust
416     /// // example code where clippy issues a warning
417     /// let msg = String::from("Hello World");
418     /// let _ = msg.to_string();
419     /// ```
420     /// Use instead:
421     /// ```rust
422     /// // example code which does not raise clippy warning
423     /// let msg = String::from("Hello World");
424     /// let _ = msg.clone();
425     /// ```
426     #[clippy::version = "pre 1.29.0"]
427     pub STRING_TO_STRING,
428     restriction,
429     "using `to_string()` on a `String`, which should be `clone()`"
430 }
431
432 declare_lint_pass!(StringToString => [STRING_TO_STRING]);
433
434 impl<'tcx> LateLintPass<'tcx> for StringToString {
435     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
436         if_chain! {
437             if let ExprKind::MethodCall(path, [self_arg, ..], _) = &expr.kind;
438             if path.ident.name == sym!(to_string);
439             let ty = cx.typeck_results().expr_ty(self_arg);
440             if is_type_diagnostic_item(cx, ty, sym::String);
441             then {
442                 span_lint_and_help(
443                     cx,
444                     STRING_TO_STRING,
445                     expr.span,
446                     "`to_string()` called on a `String`",
447                     None,
448                     "consider using `.clone()`",
449                 );
450             }
451         }
452     }
453 }