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