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