1 use crate::utils::SpanlessEq;
2 use crate::utils::{get_parent_expr, is_allowed, match_type, paths, span_lint, span_lint_and_sugg, walk_ptrs_ty};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_errors::Applicability;
7 use syntax::source_map::Spanned;
9 /// **What it does:** Checks for string appends of the form `x = x + y` (without
12 /// **Why is this bad?** It's not really bad, but some people think that the
13 /// `.push_str(_)` method is more readable.
15 /// **Known problems:** None.
20 /// let mut x = "Hello".to_owned();
21 /// x = x + ", World";
23 declare_clippy_lint! {
24 pub STRING_ADD_ASSIGN,
26 "using `x = x + ..` where x is a `String` instead of `push_str()`"
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*
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.
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.
43 /// **Known problems:** None.
48 /// let x = "Hello".to_owned();
51 declare_clippy_lint! {
54 "using `x + ..` where x is a `String` instead of `push_str()`"
57 /// **What it does:** Checks for the `as_bytes` method called on string literals
58 /// that contain only ASCII characters.
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()`.
63 /// **Known Problems:** None.
67 /// let bs = "a byte string".as_bytes();
69 declare_clippy_lint! {
70 pub STRING_LIT_AS_BYTES,
72 "calling `as_bytes` on a string literal instead of using a byte string literal"
75 #[derive(Copy, Clone)]
78 impl LintPass for StringAdd {
79 fn get_lints(&self) -> LintArray {
80 lint_array!(STRING_ADD, STRING_ADD_ASSIGN)
83 fn name(&self) -> &'static str {
88 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd {
89 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
90 if let ExprKind::Binary(
92 node: BinOpKind::Add, ..
98 if is_string(cx, left) {
99 if !is_allowed(cx, STRING_ADD_ASSIGN, e.hir_id) {
100 let parent = get_parent_expr(cx, e);
101 if let Some(p) = parent {
102 if let ExprKind::Assign(ref target, _) = p.node {
103 // avoid duplicate matches
104 if SpanlessEq::new(cx).eq_expr(target, left) {
114 "you added something to a string. Consider using `String::push_str()` instead",
117 } else if let ExprKind::Assign(ref target, ref src) = e.node {
118 if is_string(cx, target) && is_add(cx, src, target) {
123 "you assigned the result of adding something to this string. Consider using \
124 `String::push_str()` instead",
131 fn is_string(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
132 match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(e)), &paths::STRING)
135 fn is_add(cx: &LateContext<'_, '_>, src: &Expr, target: &Expr) -> bool {
139 node: BinOpKind::Add, ..
143 ) => SpanlessEq::new(cx).eq_expr(target, left),
144 ExprKind::Block(ref block, _) => {
145 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
151 #[derive(Copy, Clone)]
152 pub struct StringLitAsBytes;
154 impl LintPass for StringLitAsBytes {
155 fn get_lints(&self) -> LintArray {
156 lint_array!(STRING_LIT_AS_BYTES)
159 fn name(&self) -> &'static str {
160 "StringLiteralAsBytes"
164 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringLitAsBytes {
165 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
166 use crate::utils::{in_macro, snippet, snippet_with_applicability};
167 use syntax::ast::{LitKind, StrStyle};
169 if let ExprKind::MethodCall(ref path, _, ref args) = e.node {
170 if path.ident.name == "as_bytes" {
171 if let ExprKind::Lit(ref lit) = args[0].node {
172 if let LitKind::Str(ref lit_content, style) = lit.node {
173 let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
174 let expanded = if let StrStyle::Raw(n) = style {
175 let term = (0..n).map(|_| '#').collect::<String>();
176 format!("r{0}\"{1}\"{0}", term, lit_content.as_str())
178 format!("\"{}\"", lit_content.as_str())
180 let mut applicability = Applicability::MachineApplicable;
181 if callsite.starts_with("include_str!") {
186 "calling `as_bytes()` on `include_str!(..)`",
187 "consider using `include_bytes!(..)` instead",
188 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability).replacen(
195 } else if callsite == expanded
196 && lit_content.as_str().chars().all(|c| c.is_ascii())
197 && !in_macro(args[0].span)
203 "calling `as_bytes()` on a string literal",
204 "consider using a byte string literal instead",
207 snippet_with_applicability(cx, args[0].span, r#""foo""#, &mut applicability)