]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/strings.rs
clippy: support `QPath::LangItem`
[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, is_type_diagnostic_item, 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     /// // More readable
29     /// x += ", World";
30     /// x.push_str(", World");
31     /// ```
32     pub STRING_ADD_ASSIGN,
33     pedantic,
34     "using `x = x + ..` where x is a `String` instead of `push_str()`"
35 }
36
37 declare_clippy_lint! {
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     pub STRING_ADD,
61     restriction,
62     "using `x + ..` where x is a `String` instead of `push_str()`"
63 }
64
65 declare_clippy_lint! {
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     /// // Bad
77     /// let bs = "a byte string".as_bytes();
78     ///
79     /// // Good
80     /// let bs = b"a byte string";
81     /// ```
82     pub STRING_LIT_AS_BYTES,
83     style,
84     "calling `as_bytes` on a string literal instead of using a byte string literal"
85 }
86
87 declare_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN]);
88
89 impl<'tcx> LateLintPass<'tcx> for StringAdd {
90     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
91         if in_external_macro(cx.sess(), e.span) {
92             return;
93         }
94
95         if let ExprKind::Binary(
96             Spanned {
97                 node: BinOpKind::Add, ..
98             },
99             ref left,
100             _,
101         ) = e.kind
102         {
103             if is_string(cx, left) {
104                 if !is_allowed(cx, STRING_ADD_ASSIGN, e.hir_id) {
105                     let parent = get_parent_expr(cx, e);
106                     if let Some(p) = parent {
107                         if let ExprKind::Assign(ref target, _, _) = p.kind {
108                             // avoid duplicate matches
109                             if SpanlessEq::new(cx).eq_expr(target, left) {
110                                 return;
111                             }
112                         }
113                     }
114                 }
115                 span_lint(
116                     cx,
117                     STRING_ADD,
118                     e.span,
119                     "you added something to a string. Consider using `String::push_str()` instead",
120                 );
121             }
122         } else if let ExprKind::Assign(ref target, ref src, _) = e.kind {
123             if is_string(cx, target) && is_add(cx, src, target) {
124                 span_lint(
125                     cx,
126                     STRING_ADD_ASSIGN,
127                     e.span,
128                     "you assigned the result of adding something to this string. Consider using \
129                      `String::push_str()` instead",
130                 );
131             }
132         }
133     }
134 }
135
136 fn is_string(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
137     is_type_diagnostic_item(cx, walk_ptrs_ty(cx.typeck_results().expr_ty(e)), sym!(string_type))
138 }
139
140 fn is_add(cx: &LateContext<'_>, src: &Expr<'_>, target: &Expr<'_>) -> bool {
141     match src.kind {
142         ExprKind::Binary(
143             Spanned {
144                 node: BinOpKind::Add, ..
145             },
146             ref left,
147             _,
148         ) => SpanlessEq::new(cx).eq_expr(target, left),
149         ExprKind::Block(ref block, _) => {
150             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
151         },
152         _ => false,
153     }
154 }
155
156 // Max length a b"foo" string can take
157 const MAX_LENGTH_BYTE_STRING_LIT: usize = 32;
158
159 declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES]);
160
161 impl<'tcx> LateLintPass<'tcx> for StringLitAsBytes {
162     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
163         use crate::utils::{snippet, snippet_with_applicability};
164         use rustc_ast::ast::LitKind;
165
166         if_chain! {
167             if let ExprKind::MethodCall(path, _, args, _) = &e.kind;
168             if path.ident.name == sym!(as_bytes);
169             if let ExprKind::Lit(lit) = &args[0].kind;
170             if let LitKind::Str(lit_content, _) = &lit.node;
171             then {
172                 let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
173                 let mut applicability = Applicability::MachineApplicable;
174                 if callsite.starts_with("include_str!") {
175                     span_lint_and_sugg(
176                         cx,
177                         STRING_LIT_AS_BYTES,
178                         e.span,
179                         "calling `as_bytes()` on `include_str!(..)`",
180                         "consider using `include_bytes!(..)` instead",
181                         snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen(
182                             "include_str",
183                             "include_bytes",
184                             1,
185                         ),
186                         applicability,
187                     );
188                 } else if lit_content.as_str().is_ascii()
189                     && lit_content.as_str().len() <= MAX_LENGTH_BYTE_STRING_LIT
190                     && !args[0].span.from_expansion()
191                 {
192                     span_lint_and_sugg(
193                         cx,
194                         STRING_LIT_AS_BYTES,
195                         e.span,
196                         "calling `as_bytes()` on a string literal",
197                         "consider using a byte string literal instead",
198                         format!(
199                             "b{}",
200                             snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)
201                         ),
202                         applicability,
203                     );
204                 }
205             }
206         }
207     }
208 }