2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
4 use rustc_errors::Applicability;
5 use syntax::source_map::Spanned;
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};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for string appends of the form `x = x + y` (without
14 /// **Why is this bad?** It's not really bad, but some people think that the
15 /// `.push_str(_)` method is more readable.
17 /// **Known problems:** None.
22 /// let mut x = "Hello".to_owned();
23 /// x = x + ", World";
25 pub STRING_ADD_ASSIGN,
27 "using `x = x + ..` where x is a `String` instead of `push_str()`"
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*
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.
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.
45 /// **Known problems:** None.
50 /// let x = "Hello".to_owned();
55 "using `x + ..` where x is a `String` instead of `push_str()`"
58 declare_clippy_lint! {
59 /// **What it does:** Checks for the `as_bytes` method called on string literals
60 /// that contain only ASCII characters.
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()`.
65 /// **Known Problems:** None.
69 /// let bs = "a byte string".as_bytes();
71 pub STRING_LIT_AS_BYTES,
73 "calling `as_bytes` on a string literal instead of using a byte string literal"
76 #[derive(Copy, Clone)]
79 impl LintPass for StringAdd {
80 fn get_lints(&self) -> LintArray {
81 lint_array!(STRING_ADD, STRING_ADD_ASSIGN)
84 fn name(&self) -> &'static str {
89 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd {
90 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
91 if let ExprKind::Binary(
93 node: BinOpKind::Add, ..
99 if is_string(cx, left) {
100 if !is_allowed(cx, STRING_ADD_ASSIGN, e.hir_id) {
101 let parent = get_parent_expr(cx, e);
102 if let Some(p) = parent {
103 if let ExprKind::Assign(ref target, _) = p.node {
104 // avoid duplicate matches
105 if SpanlessEq::new(cx).eq_expr(target, left) {
115 "you added something to a string. Consider using `String::push_str()` instead",
118 } else if let ExprKind::Assign(ref target, ref src) = e.node {
119 if is_string(cx, target) && is_add(cx, src, target) {
124 "you assigned the result of adding something to this string. Consider using \
125 `String::push_str()` instead",
132 fn is_string(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
133 match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(e)), &paths::STRING)
136 fn is_add(cx: &LateContext<'_, '_>, src: &Expr, target: &Expr) -> bool {
140 node: BinOpKind::Add, ..
144 ) => SpanlessEq::new(cx).eq_expr(target, left),
145 ExprKind::Block(ref block, _) => {
146 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
152 #[derive(Copy, Clone)]
153 pub struct StringLitAsBytes;
155 impl LintPass for StringLitAsBytes {
156 fn get_lints(&self) -> LintArray {
157 lint_array!(STRING_LIT_AS_BYTES)
160 fn name(&self) -> &'static str {
161 "StringLiteralAsBytes"
165 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringLitAsBytes {
166 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
167 use crate::utils::{in_macro, snippet, snippet_with_applicability};
168 use syntax::ast::{LitKind, StrStyle};
170 if let ExprKind::MethodCall(ref path, _, ref args) = e.node {
171 if path.ident.name == "as_bytes" {
172 if let ExprKind::Lit(ref lit) = args[0].node {
173 if let LitKind::Str(ref lit_content, style) = lit.node {
174 let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
175 let expanded = if let StrStyle::Raw(n) = style {
176 let term = (0..n).map(|_| '#').collect::<String>();
177 format!("r{0}\"{1}\"{0}", term, lit_content.as_str())
179 format!("\"{}\"", lit_content.as_str())
181 let mut applicability = Applicability::MachineApplicable;
182 if callsite.starts_with("include_str!") {
187 "calling `as_bytes()` on `include_str!(..)`",
188 "consider using `include_bytes!(..)` instead",
189 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen(
196 } else if callsite == expanded
197 && lit_content.as_str().chars().all(|c| c.is_ascii())
198 && !in_macro(args[0].span)
204 "calling `as_bytes()` on a string literal",
205 "consider using a byte string literal instead",
208 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)