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