]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/strings.rs
Merge commit 'ea199bacef07213dbe008841b89c450e3bf0c638' into rustfmt-sync
[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::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;
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     pub STRING_ADD_ASSIGN,
35     pedantic,
36     "using `x = x + ..` where x is a `String` instead of `push_str()`"
37 }
38
39 declare_clippy_lint! {
40     /// ### What it does
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*
43     /// match.
44     ///
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.
51     ///
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.
55     ///
56     /// ### Example
57     /// ```rust
58     /// let x = "Hello".to_owned();
59     /// x + ", World";
60     /// ```
61     pub STRING_ADD,
62     restriction,
63     "using `x + ..` where x is a `String` instead of `push_str()`"
64 }
65
66 declare_clippy_lint! {
67     /// ### What it does
68     /// Checks for the `as_bytes` method called on string literals
69     /// that contain only ASCII characters.
70     ///
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()`.
74     ///
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.
80     ///
81     /// ```compile_fail
82     /// fn f(v: Vec<u8>) {}
83     ///
84     /// f("...".as_bytes().to_owned()); // works
85     /// f(b"...".to_owned()); // does not work, because arg is [u8; 3] not Vec<u8>
86     ///
87     /// fn g(r: impl std::io::Read) {}
88     ///
89     /// g("...".as_bytes()); // works
90     /// g(b"..."); // does not work
91     /// ```
92     ///
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.
96     ///
97     /// ### Example
98     /// ```rust
99     /// // Bad
100     /// let bs = "a byte string".as_bytes();
101     ///
102     /// // Good
103     /// let bs = b"a byte string";
104     /// ```
105     pub STRING_LIT_AS_BYTES,
106     nursery,
107     "calling `as_bytes` on a string literal instead of using a byte string literal"
108 }
109
110 declare_clippy_lint! {
111     /// ### What it does
112     /// Checks for slice operations on strings
113     ///
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.
119     ///
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.
123     ///
124     /// # Example
125     /// ```rust,should_panic
126     /// &"Ölkanne"[1..];
127     /// ```
128     pub STRING_SLICE,
129     restriction,
130     "slicing a string"
131 }
132
133 declare_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN, STRING_SLICE]);
134
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) {
138             return;
139         }
140         match e.kind {
141             ExprKind::Binary(
142                 Spanned {
143                     node: BinOpKind::Add, ..
144                 },
145                 left,
146                 _,
147             ) => {
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) {
155                                     return;
156                                 }
157                             }
158                         }
159                     }
160                     span_lint(
161                         cx,
162                         STRING_ADD,
163                         e.span,
164                         "you added something to a string. Consider using `String::push_str()` instead",
165                     );
166                 }
167             },
168             ExprKind::Assign(target, src, _) => {
169                 if is_string(cx, target) && is_add(cx, src, target) {
170                     span_lint(
171                         cx,
172                         STRING_ADD_ASSIGN,
173                         e.span,
174                         "you assigned the result of adding something to this string. Consider using \
175                          `String::push_str()` instead",
176                     );
177                 }
178             },
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) {
182                     span_lint(
183                         cx,
184                         STRING_SLICE,
185                         e.span,
186                         "indexing into a string may panic if the index is within a UTF-8 character",
187                     );
188                 }
189             },
190             _ => {},
191         }
192     }
193 }
194
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)
197 }
198
199 fn is_add(cx: &LateContext<'_>, src: &Expr<'_>, target: &Expr<'_>) -> bool {
200     match src.kind {
201         ExprKind::Binary(
202             Spanned {
203                 node: BinOpKind::Add, ..
204             },
205             left,
206             _,
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))
210         },
211         _ => false,
212     }
213 }
214
215 declare_clippy_lint! {
216     /// ### What it does
217     /// Check if the string is transformed to byte array and casted back to string.
218     ///
219     /// ### Why is this bad?
220     /// It's unnecessary, the string can be used directly.
221     ///
222     /// ### Example
223     /// ```rust
224     /// let _ = std::str::from_utf8(&"Hello World!".as_bytes()[6..11]).unwrap();
225     /// ```
226     /// could be written as
227     /// ```rust
228     /// let _ = &"Hello World!"[6..11];
229     /// ```
230     pub STRING_FROM_UTF8_AS_BYTES,
231     complexity,
232     "casting string slices to byte slices and back"
233 }
234
235 // Max length a b"foo" string can take
236 const MAX_LENGTH_BYTE_STRING_LIT: usize = 32;
237
238 declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES, STRING_FROM_UTF8_AS_BYTES]);
239
240 impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes {
241     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
242         use rustc_ast::LitKind;
243
244         if_chain! {
245             // Find std::str::converts::from_utf8
246             if let Some(args) = match_function_call(cx, e, &paths::STR_FROM_UTF8);
247
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);
256
257             // Check for slicer
258             if let ExprKind::Struct(QPath::LangItem(LangItem::Range, _), _, _) = right.kind;
259
260             then {
261                 let mut applicability = Applicability::MachineApplicable;
262                 let string_expression = &expressions[0][0];
263
264                 let snippet_app = snippet_with_applicability(
265                     cx,
266                     string_expression.span, "..",
267                     &mut applicability,
268                 );
269
270                 span_lint_and_sugg(
271                     cx,
272                     STRING_FROM_UTF8_AS_BYTES,
273                     e.span,
274                     "calling a slice of `as_bytes()` with `from_utf8` should be not necessary",
275                     "try",
276                     format!("Some(&{}[{}])", snippet_app, snippet(cx, right.span, "..")),
277                     applicability
278                 )
279             }
280         }
281
282         if_chain! {
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;
287             then {
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!") {
291                     span_lint_and_sugg(
292                         cx,
293                         STRING_LIT_AS_BYTES,
294                         e.span,
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(
298                             "include_str",
299                             "include_bytes",
300                             1,
301                         ),
302                         applicability,
303                     );
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()
307                 {
308                     span_lint_and_sugg(
309                         cx,
310                         STRING_LIT_AS_BYTES,
311                         e.span,
312                         "calling `as_bytes()` on a string literal",
313                         "consider using a byte string literal instead",
314                         format!(
315                             "b{}",
316                             snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)
317                         ),
318                         applicability,
319                     );
320                 }
321             }
322         }
323
324         if_chain! {
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;
331
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();
335             then {
336                 let mut applicability = Applicability::MachineApplicable;
337
338                 span_lint_and_sugg(
339                     cx,
340                     STRING_LIT_AS_BYTES,
341                     e.span,
342                     "calling `into_bytes()` on a string literal",
343                     "consider using a byte string literal instead",
344                     format!(
345                         "b{}.to_vec()",
346                         snippet_with_applicability(cx, recv.span, r#""..""#, &mut applicability)
347                     ),
348                     applicability,
349                 );
350             }
351         }
352     }
353 }
354
355 declare_clippy_lint! {
356     /// ### What it does
357     /// This lint checks for `.to_string()` method calls on values of type `&str`.
358     ///
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()`.
363     ///
364     /// ### Example
365     /// ```rust
366     /// // example code where clippy issues a warning
367     /// let _ = "str".to_string();
368     /// ```
369     /// Use instead:
370     /// ```rust
371     /// // example code which does not raise clippy warning
372     /// let _ = "str".to_owned();
373     /// ```
374     pub STR_TO_STRING,
375     restriction,
376     "using `to_string()` on a `&str`, which should be `to_owned()`"
377 }
378
379 declare_lint_pass!(StrToString => [STR_TO_STRING]);
380
381 impl LateLintPass<'_> for StrToString {
382     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
383         if_chain! {
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;
389             then {
390                 span_lint_and_help(
391                     cx,
392                     STR_TO_STRING,
393                     expr.span,
394                     "`to_string()` called on a `&str`",
395                     None,
396                     "consider using `.to_owned()`",
397                 );
398             }
399         }
400     }
401 }
402
403 declare_clippy_lint! {
404     /// ### What it does
405     /// This lint checks for `.to_string()` method calls on values of type `String`.
406     ///
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()`.
410     ///
411     /// ### Example
412     /// ```rust
413     /// // example code where clippy issues a warning
414     /// let msg = String::from("Hello World");
415     /// let _ = msg.to_string();
416     /// ```
417     /// Use instead:
418     /// ```rust
419     /// // example code which does not raise clippy warning
420     /// let msg = String::from("Hello World");
421     /// let _ = msg.clone();
422     /// ```
423     pub STRING_TO_STRING,
424     restriction,
425     "using `to_string()` on a `String`, which should be `clone()`"
426 }
427
428 declare_lint_pass!(StringToString => [STRING_TO_STRING]);
429
430 impl LateLintPass<'_> for StringToString {
431     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
432         if_chain! {
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);
437             then {
438                 span_lint_and_help(
439                     cx,
440                     STRING_TO_STRING,
441                     expr.span,
442                     "`to_string()` called on a `String`",
443                     None,
444                     "consider using `.clone()`",
445                 );
446             }
447         }
448     }
449 }