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;
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 declare_lint_pass!(StringAdd => [STRING_ADD, STRING_ADD_ASSIGN]);
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(
82 node: BinOpKind::Add, ..
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.kind {
93 // avoid duplicate matches
94 if SpanlessEq::new(cx).eq_expr(target, left) {
104 "you added something to a string. Consider using `String::push_str()` instead",
107 } else if let ExprKind::Assign(ref target, ref src) = e.kind {
108 if is_string(cx, target) && is_add(cx, src, target) {
113 "you assigned the result of adding something to this string. Consider using \
114 `String::push_str()` instead",
121 fn is_string(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
122 match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(e)), &paths::STRING)
125 fn is_add(cx: &LateContext<'_, '_>, src: &Expr, target: &Expr) -> bool {
129 node: BinOpKind::Add, ..
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))
141 // Max length a b"foo" string can take
142 const MAX_LENGTH_BYTE_STRING_LIT: usize = 32;
144 declare_lint_pass!(StringLitAsBytes => [STRING_LIT_AS_BYTES]);
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::{snippet, snippet_with_applicability};
149 use syntax::ast::{LitKind, StrStyle};
151 if let ExprKind::MethodCall(ref path, _, ref args) = e.kind {
152 if path.ident.name == sym!(as_bytes) {
153 if let ExprKind::Lit(ref lit) = args[0].kind {
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 = "#".repeat(usize::from(n));
158 format!("r{0}\"{1}\"{0}", term, lit_content.as_str())
160 format!("\"{}\"", lit_content.as_str())
162 let mut applicability = Applicability::MachineApplicable;
163 if callsite.starts_with("include_str!") {
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(
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 && !args[0].span.from_expansion()
186 "calling `as_bytes()` on a string literal",
187 "consider using a byte string literal instead",
190 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)