]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/strings.rs
Merge pull request #3285 from devonhollowood/pedantic-dogfood-items-after-statements
[rust.git] / clippy_lints / src / strings.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::syntax::source_map::Spanned;
15 use crate::utils::SpanlessEq;
16 use crate::utils::{get_parent_expr, is_allowed, match_type, paths, span_lint, span_lint_and_sugg, walk_ptrs_ty};
17
18 /// **What it does:** Checks for string appends of the form `x = x + y` (without
19 /// `let`!).
20 ///
21 /// **Why is this bad?** It's not really bad, but some people think that the
22 /// `.push_str(_)` method is more readable.
23 ///
24 /// **Known problems:** None.
25 ///
26 /// **Example:**
27 ///
28 /// ```rust
29 /// let mut x = "Hello".to_owned();
30 /// x = x + ", World";
31 /// ```
32 declare_clippy_lint! {
33     pub STRING_ADD_ASSIGN,
34     pedantic,
35     "using `x = x + ..` where x is a `String` instead of `push_str()`"
36 }
37
38 /// **What it does:** Checks for all instances of `x + _` where `x` is of type
39 /// `String`, but only if [`string_add_assign`](#string_add_assign) does *not*
40 /// match.
41 ///
42 /// **Why is this bad?** It's not bad in and of itself. However, this particular
43 /// `Add` implementation is asymmetric (the other operand need not be `String`,
44 /// but `x` does), while addition as mathematically defined is symmetric, also
45 /// the `String::push_str(_)` function is a perfectly good replacement.
46 /// Therefore some dislike it and wish not to have it in their code.
47 ///
48 /// That said, other people think that string addition, having a long tradition
49 /// in other languages is actually fine, which is why we decided to make this
50 /// particular lint `allow` by default.
51 ///
52 /// **Known problems:** None.
53 ///
54 /// **Example:**
55 ///
56 /// ```rust
57 /// let x = "Hello".to_owned();
58 /// x + ", World"
59 /// ```
60 declare_clippy_lint! {
61     pub STRING_ADD,
62     restriction,
63     "using `x + ..` where x is a `String` instead of `push_str()`"
64 }
65
66 /// **What it does:** Checks for the `as_bytes` method called on string literals
67 /// that contain only ASCII characters.
68 ///
69 /// **Why is this bad?** Byte string literals (e.g. `b"foo"`) can be used
70 /// instead. They are shorter but less discoverable than `as_bytes()`.
71 ///
72 /// **Known Problems:** None.
73 ///
74 /// **Example:**
75 /// ```rust
76 /// let bs = "a byte string".as_bytes();
77 /// ```
78 declare_clippy_lint! {
79     pub STRING_LIT_AS_BYTES,
80     style,
81     "calling `as_bytes` on a string literal instead of using a byte string literal"
82 }
83
84 #[derive(Copy, Clone)]
85 pub struct StringAdd;
86
87 impl LintPass for StringAdd {
88     fn get_lints(&self) -> LintArray {
89         lint_array!(STRING_ADD, STRING_ADD_ASSIGN)
90     }
91 }
92
93 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd {
94     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
95         if let ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, ref left, _) = e.node {
96             if is_string(cx, left) {
97                 if !is_allowed(cx, STRING_ADD_ASSIGN, e.id) {
98                     let parent = get_parent_expr(cx, e);
99                     if let Some(p) = parent {
100                         if let ExprKind::Assign(ref target, _) = p.node {
101                             // avoid duplicate matches
102                             if SpanlessEq::new(cx).eq_expr(target, left) {
103                                 return;
104                             }
105                         }
106                     }
107                 }
108                 span_lint(
109                     cx,
110                     STRING_ADD,
111                     e.span,
112                     "you added something to a string. Consider using `String::push_str()` instead",
113                 );
114             }
115         } else if let ExprKind::Assign(ref target, ref src) = e.node {
116             if is_string(cx, target) && is_add(cx, src, target) {
117                 span_lint(
118                     cx,
119                     STRING_ADD_ASSIGN,
120                     e.span,
121                     "you assigned the result of adding something to this string. Consider using \
122                      `String::push_str()` instead",
123                 );
124             }
125         }
126     }
127 }
128
129 fn is_string(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
130     match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(e)), &paths::STRING)
131 }
132
133 fn is_add(cx: &LateContext<'_, '_>, src: &Expr, target: &Expr) -> bool {
134     match src.node {
135         ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, ref left, _) => SpanlessEq::new(cx).eq_expr(target, left),
136         ExprKind::Block(ref block, _) => {
137             block.stmts.is_empty()
138                 && block
139                     .expr
140                     .as_ref()
141                     .map_or(false, |expr| is_add(cx, expr, target))
142         },
143         _ => false,
144     }
145 }
146
147 #[derive(Copy, Clone)]
148 pub struct StringLitAsBytes;
149
150 impl LintPass for StringLitAsBytes {
151     fn get_lints(&self) -> LintArray {
152         lint_array!(STRING_LIT_AS_BYTES)
153     }
154 }
155
156 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringLitAsBytes {
157     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
158         use crate::syntax::ast::LitKind;
159         use crate::utils::{in_macro, snippet};
160
161         if let ExprKind::MethodCall(ref path, _, ref args) = e.node {
162             if path.ident.name == "as_bytes" {
163                 if let ExprKind::Lit(ref lit) = args[0].node {
164                     if let LitKind::Str(ref lit_content, _) = lit.node {
165                         if lit_content.as_str().chars().all(|c| c.is_ascii()) && !in_macro(args[0].span) {
166                             span_lint_and_sugg(
167                                 cx,
168                                 STRING_LIT_AS_BYTES,
169                                 e.span,
170                                 "calling `as_bytes()` on a string literal",
171                                 "consider using a byte string literal instead",
172                                 format!("b{}", snippet(cx, args[0].span, r#""foo""#)),
173                             );
174                         }
175                     }
176                 }
177             }
178         }
179     }
180 }