]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/strings.rs
Rollup merge of #89839 - jkugelman:must-use-mem-ptr-functions, r=joshtriplett
[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_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN]);
111
112 impl<'tcx> LateLintPass<'tcx> for StringAdd {
113     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
114         if in_external_macro(cx.sess(), e.span) {
115             return;
116         }
117
118         if let ExprKind::Binary(
119             Spanned {
120                 node: BinOpKind::Add, ..
121             },
122             left,
123             _,
124         ) = e.kind
125         {
126             if is_string(cx, left) {
127                 if !is_lint_allowed(cx, STRING_ADD_ASSIGN, e.hir_id) {
128                     let parent = get_parent_expr(cx, e);
129                     if let Some(p) = parent {
130                         if let ExprKind::Assign(target, _, _) = p.kind {
131                             // avoid duplicate matches
132                             if SpanlessEq::new(cx).eq_expr(target, left) {
133                                 return;
134                             }
135                         }
136                     }
137                 }
138                 span_lint(
139                     cx,
140                     STRING_ADD,
141                     e.span,
142                     "you added something to a string. Consider using `String::push_str()` instead",
143                 );
144             }
145         } else if let ExprKind::Assign(target, src, _) = e.kind {
146             if is_string(cx, target) && is_add(cx, src, target) {
147                 span_lint(
148                     cx,
149                     STRING_ADD_ASSIGN,
150                     e.span,
151                     "you assigned the result of adding something to this string. Consider using \
152                      `String::push_str()` instead",
153                 );
154             }
155         }
156     }
157 }
158
159 fn is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
160     is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(e).peel_refs(), sym::String)
161 }
162
163 fn is_add(cx: &LateContext<'_>, src: &Expr<'_>, target: &Expr<'_>) -> bool {
164     match src.kind {
165         ExprKind::Binary(
166             Spanned {
167                 node: BinOpKind::Add, ..
168             },
169             left,
170             _,
171         ) => SpanlessEq::new(cx).eq_expr(target, left),
172         ExprKind::Block(block, _) => {
173             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
174         },
175         _ => false,
176     }
177 }
178
179 declare_clippy_lint! {
180     /// ### What it does
181     /// Check if the string is transformed to byte array and casted back to string.
182     ///
183     /// ### Why is this bad?
184     /// It's unnecessary, the string can be used directly.
185     ///
186     /// ### Example
187     /// ```rust
188     /// let _ = std::str::from_utf8(&"Hello World!".as_bytes()[6..11]).unwrap();
189     /// ```
190     /// could be written as
191     /// ```rust
192     /// let _ = &"Hello World!"[6..11];
193     /// ```
194     pub STRING_FROM_UTF8_AS_BYTES,
195     complexity,
196     "casting string slices to byte slices and back"
197 }
198
199 // Max length a b"foo" string can take
200 const MAX_LENGTH_BYTE_STRING_LIT: usize = 32;
201
202 declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES, STRING_FROM_UTF8_AS_BYTES]);
203
204 impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes {
205     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
206         use rustc_ast::LitKind;
207
208         if_chain! {
209             // Find std::str::converts::from_utf8
210             if let Some(args) = match_function_call(cx, e, &paths::STR_FROM_UTF8);
211
212             // Find string::as_bytes
213             if let ExprKind::AddrOf(BorrowKind::Ref, _, args) = args[0].kind;
214             if let ExprKind::Index(left, right) = args.kind;
215             let (method_names, expressions, _) = method_calls(left, 1);
216             if method_names.len() == 1;
217             if expressions.len() == 1;
218             if expressions[0].len() == 1;
219             if method_names[0] == sym!(as_bytes);
220
221             // Check for slicer
222             if let ExprKind::Struct(QPath::LangItem(LangItem::Range, _), _, _) = right.kind;
223
224             then {
225                 let mut applicability = Applicability::MachineApplicable;
226                 let string_expression = &expressions[0][0];
227
228                 let snippet_app = snippet_with_applicability(
229                     cx,
230                     string_expression.span, "..",
231                     &mut applicability,
232                 );
233
234                 span_lint_and_sugg(
235                     cx,
236                     STRING_FROM_UTF8_AS_BYTES,
237                     e.span,
238                     "calling a slice of `as_bytes()` with `from_utf8` should be not necessary",
239                     "try",
240                     format!("Some(&{}[{}])", snippet_app, snippet(cx, right.span, "..")),
241                     applicability
242                 )
243             }
244         }
245
246         if_chain! {
247             if let ExprKind::MethodCall(path, _, args, _) = &e.kind;
248             if path.ident.name == sym!(as_bytes);
249             if let ExprKind::Lit(lit) = &args[0].kind;
250             if let LitKind::Str(lit_content, _) = &lit.node;
251             then {
252                 let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
253                 let mut applicability = Applicability::MachineApplicable;
254                 if callsite.starts_with("include_str!") {
255                     span_lint_and_sugg(
256                         cx,
257                         STRING_LIT_AS_BYTES,
258                         e.span,
259                         "calling `as_bytes()` on `include_str!(..)`",
260                         "consider using `include_bytes!(..)` instead",
261                         snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen(
262                             "include_str",
263                             "include_bytes",
264                             1,
265                         ),
266                         applicability,
267                     );
268                 } else if lit_content.as_str().is_ascii()
269                     && lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT
270                     && !args[0].span.from_expansion()
271                 {
272                     span_lint_and_sugg(
273                         cx,
274                         STRING_LIT_AS_BYTES,
275                         e.span,
276                         "calling `as_bytes()` on a string literal",
277                         "consider using a byte string literal instead",
278                         format!(
279                             "b{}",
280                             snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)
281                         ),
282                         applicability,
283                     );
284                 }
285             }
286         }
287
288         if_chain! {
289             if let ExprKind::MethodCall(path, _, [recv], _) = &e.kind;
290             if path.ident.name == sym!(into_bytes);
291             if let ExprKind::MethodCall(path, _, [recv], _) = &recv.kind;
292             if matches!(&*path.ident.name.as_str(), "to_owned" | "to_string");
293             if let ExprKind::Lit(lit) = &recv.kind;
294             if let LitKind::Str(lit_content, _) = &lit.node;
295
296             if lit_content.as_str().is_ascii();
297             if lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT;
298             if !recv.span.from_expansion();
299             then {
300                 let mut applicability = Applicability::MachineApplicable;
301
302                 span_lint_and_sugg(
303                     cx,
304                     STRING_LIT_AS_BYTES,
305                     e.span,
306                     "calling `into_bytes()` on a string literal",
307                     "consider using a byte string literal instead",
308                     format!(
309                         "b{}.to_vec()",
310                         snippet_with_applicability(cx, recv.span, r#""..""#, &mut applicability)
311                     ),
312                     applicability,
313                 );
314             }
315         }
316     }
317 }
318
319 declare_clippy_lint! {
320     /// ### What it does
321     /// This lint checks for `.to_string()` method calls on values of type `&str`.
322     ///
323     /// ### Why is this bad?
324     /// The `to_string` method is also used on other types to convert them to a string.
325     /// When called on a `&str` it turns the `&str` into the owned variant `String`, which can be better
326     /// expressed with `.to_owned()`.
327     ///
328     /// ### Example
329     /// ```rust
330     /// // example code where clippy issues a warning
331     /// let _ = "str".to_string();
332     /// ```
333     /// Use instead:
334     /// ```rust
335     /// // example code which does not raise clippy warning
336     /// let _ = "str".to_owned();
337     /// ```
338     pub STR_TO_STRING,
339     restriction,
340     "using `to_string()` on a `&str`, which should be `to_owned()`"
341 }
342
343 declare_lint_pass!(StrToString => [STR_TO_STRING]);
344
345 impl LateLintPass<'_> for StrToString {
346     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
347         if_chain! {
348             if let ExprKind::MethodCall(path, _, [self_arg, ..], _) = &expr.kind;
349             if path.ident.name == sym!(to_string);
350             let ty = cx.typeck_results().expr_ty(self_arg);
351             if let ty::Ref(_, ty, ..) = ty.kind();
352             if *ty.kind() == ty::Str;
353             then {
354                 span_lint_and_help(
355                     cx,
356                     STR_TO_STRING,
357                     expr.span,
358                     "`to_string()` called on a `&str`",
359                     None,
360                     "consider using `.to_owned()`",
361                 );
362             }
363         }
364     }
365 }
366
367 declare_clippy_lint! {
368     /// ### What it does
369     /// This lint checks for `.to_string()` method calls on values of type `String`.
370     ///
371     /// ### Why is this bad?
372     /// The `to_string` method is also used on other types to convert them to a string.
373     /// When called on a `String` it only clones the `String`, which can be better expressed with `.clone()`.
374     ///
375     /// ### Example
376     /// ```rust
377     /// // example code where clippy issues a warning
378     /// let msg = String::from("Hello World");
379     /// let _ = msg.to_string();
380     /// ```
381     /// Use instead:
382     /// ```rust
383     /// // example code which does not raise clippy warning
384     /// let msg = String::from("Hello World");
385     /// let _ = msg.clone();
386     /// ```
387     pub STRING_TO_STRING,
388     restriction,
389     "using `to_string()` on a `String`, which should be `clone()`"
390 }
391
392 declare_lint_pass!(StringToString => [STRING_TO_STRING]);
393
394 impl LateLintPass<'_> for StringToString {
395     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'_>) {
396         if_chain! {
397             if let ExprKind::MethodCall(path, _, [self_arg, ..], _) = &expr.kind;
398             if path.ident.name == sym!(to_string);
399             let ty = cx.typeck_results().expr_ty(self_arg);
400             if is_type_diagnostic_item(cx, ty, sym::String);
401             then {
402                 span_lint_and_help(
403                     cx,
404                     STRING_TO_STRING,
405                     expr.span,
406                     "`to_string()` called on a `String`",
407                     None,
408                     "consider using `.clone()`",
409                 );
410             }
411         }
412     }
413 }