]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/strings.rs
Rustup to rust-lang/rust#67806
[rust.git] / clippy_lints / src / strings.rs
1 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintContext};
2 use rustc_errors::Applicability;
3 use rustc_hir::*;
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5 use rustc_span::source_map::Spanned;
6
7 use if_chain::if_chain;
8
9 use crate::utils::SpanlessEq;
10 use crate::utils::{get_parent_expr, is_allowed, match_type, paths, span_lint, span_lint_and_sugg, walk_ptrs_ty};
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for string appends of the form `x = x + y` (without
14     /// `let`!).
15     ///
16     /// **Why is this bad?** It's not really bad, but some people think that the
17     /// `.push_str(_)` method is more readable.
18     ///
19     /// **Known problems:** None.
20     ///
21     /// **Example:**
22     ///
23     /// ```rust
24     /// let mut x = "Hello".to_owned();
25     /// x = x + ", World";
26     /// ```
27     pub STRING_ADD_ASSIGN,
28     pedantic,
29     "using `x = x + ..` where x is a `String` instead of `push_str()`"
30 }
31
32 declare_clippy_lint! {
33     /// **What it does:** Checks for all instances of `x + _` where `x` is of type
34     /// `String`, but only if [`string_add_assign`](#string_add_assign) does *not*
35     /// match.
36     ///
37     /// **Why is this bad?** It's not bad in and of itself. However, this particular
38     /// `Add` implementation is asymmetric (the other operand need not be `String`,
39     /// but `x` does), while addition as mathematically defined is symmetric, also
40     /// the `String::push_str(_)` function is a perfectly good replacement.
41     /// Therefore, some dislike it and wish not to have it in their code.
42     ///
43     /// That said, other people think that string addition, having a long tradition
44     /// in other languages is actually fine, which is why we decided to make this
45     /// particular lint `allow` by default.
46     ///
47     /// **Known problems:** None.
48     ///
49     /// **Example:**
50     ///
51     /// ```rust
52     /// let x = "Hello".to_owned();
53     /// x + ", World";
54     /// ```
55     pub STRING_ADD,
56     restriction,
57     "using `x + ..` where x is a `String` instead of `push_str()`"
58 }
59
60 declare_clippy_lint! {
61     /// **What it does:** Checks for the `as_bytes` method called on string literals
62     /// that contain only ASCII characters.
63     ///
64     /// **Why is this bad?** Byte string literals (e.g., `b"foo"`) can be used
65     /// instead. They are shorter but less discoverable than `as_bytes()`.
66     ///
67     /// **Known Problems:** None.
68     ///
69     /// **Example:**
70     /// ```rust
71     /// let bs = "a byte string".as_bytes();
72     /// ```
73     pub STRING_LIT_AS_BYTES,
74     style,
75     "calling `as_bytes` on a string literal instead of using a byte string literal"
76 }
77
78 declare_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN]);
79
80 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd {
81     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
82         if in_external_macro(cx.sess(), e.span) {
83             return;
84         }
85
86         if let ExprKind::Binary(
87             Spanned {
88                 node: BinOpKind::Add, ..
89             },
90             ref left,
91             _,
92         ) = e.kind
93         {
94             if is_string(cx, left) {
95                 if !is_allowed(cx, STRING_ADD_ASSIGN, e.hir_id) {
96                     let parent = get_parent_expr(cx, e);
97                     if let Some(p) = parent {
98                         if let ExprKind::Assign(ref target, _, _) = p.kind {
99                             // avoid duplicate matches
100                             if SpanlessEq::new(cx).eq_expr(target, left) {
101                                 return;
102                             }
103                         }
104                     }
105                 }
106                 span_lint(
107                     cx,
108                     STRING_ADD,
109                     e.span,
110                     "you added something to a string. Consider using `String::push_str()` instead",
111                 );
112             }
113         } else if let ExprKind::Assign(ref target, ref src, _) = e.kind {
114             if is_string(cx, target) && is_add(cx, src, target) {
115                 span_lint(
116                     cx,
117                     STRING_ADD_ASSIGN,
118                     e.span,
119                     "you assigned the result of adding something to this string. Consider using \
120                      `String::push_str()` instead",
121                 );
122             }
123         }
124     }
125 }
126
127 fn is_string(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool {
128     match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(e)), &paths::STRING)
129 }
130
131 fn is_add(cx: &LateContext<'_, '_>, src: &Expr<'_>, target: &Expr<'_>) -> bool {
132     match src.kind {
133         ExprKind::Binary(
134             Spanned {
135                 node: BinOpKind::Add, ..
136             },
137             ref left,
138             _,
139         ) => SpanlessEq::new(cx).eq_expr(target, left),
140         ExprKind::Block(ref block, _) => {
141             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
142         },
143         _ => false,
144     }
145 }
146
147 // Max length a b"foo" string can take
148 const MAX_LENGTH_BYTE_STRING_LIT: usize = 32;
149
150 declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES]);
151
152 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringLitAsBytes {
153     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
154         use crate::utils::{snippet, snippet_with_applicability};
155         use syntax::ast::LitKind;
156
157         if_chain! {
158             if let ExprKind::MethodCall(path, _, args) = &e.kind;
159             if path.ident.name == sym!(as_bytes);
160             if let ExprKind::Lit(lit) = &args[0].kind;
161             if let LitKind::Str(lit_content, _) = &lit.node;
162             then {
163                 let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
164                 let mut applicability = Applicability::MachineApplicable;
165                 if callsite.starts_with("include_str!") {
166                     span_lint_and_sugg(
167                         cx,
168                         STRING_LIT_AS_BYTES,
169                         e.span,
170                         "calling `as_bytes()` on `include_str!(..)`",
171                         "consider using `include_bytes!(..)` instead",
172                         snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen(
173                             "include_str",
174                             "include_bytes",
175                             1,
176                         ),
177                         applicability,
178                     );
179                 } else if lit_content.as_str().is_ascii()
180                     && lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT
181                     && !args[0].span.from_expansion()
182                 {
183                     span_lint_and_sugg(
184                         cx,
185                         STRING_LIT_AS_BYTES,
186                         e.span,
187                         "calling `as_bytes()` on a string literal",
188                         "consider using a byte string literal instead",
189                         format!(
190                             "b{}",
191                             snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)
192                         ),
193                         applicability,
194                     );
195                 }
196             }
197         }
198     }
199 }