1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir::*;
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::syntax::source_map::Spanned;
14 use crate::utils::SpanlessEq;
15 use crate::utils::{get_parent_expr, is_allowed, match_type, paths, span_lint, span_lint_and_sugg, walk_ptrs_ty};
17 /// **What it does:** Checks for string appends of the form `x = x + y` (without
20 /// **Why is this bad?** It's not really bad, but some people think that the
21 /// `.push_str(_)` method is more readable.
23 /// **Known problems:** None.
28 /// let mut x = "Hello".to_owned();
29 /// x = x + ", World";
31 declare_clippy_lint! {
32 pub STRING_ADD_ASSIGN,
34 "using `x = x + ..` where x is a `String` instead of `push_str()`"
37 /// **What it does:** Checks for all instances of `x + _` where `x` is of type
38 /// `String`, but only if [`string_add_assign`](#string_add_assign) does *not*
41 /// **Why is this bad?** It's not bad in and of itself. However, this particular
42 /// `Add` implementation is asymmetric (the other operand need not be `String`,
43 /// but `x` does), while addition as mathematically defined is symmetric, also
44 /// the `String::push_str(_)` function is a perfectly good replacement.
45 /// Therefore some dislike it and wish not to have it in their code.
47 /// That said, other people think that string addition, having a long tradition
48 /// in other languages is actually fine, which is why we decided to make this
49 /// particular lint `allow` by default.
51 /// **Known problems:** None.
56 /// let x = "Hello".to_owned();
59 declare_clippy_lint! {
62 "using `x + ..` where x is a `String` instead of `push_str()`"
65 /// **What it does:** Checks for the `as_bytes` method called on string literals
66 /// that contain only ASCII characters.
68 /// **Why is this bad?** Byte string literals (e.g. `b"foo"`) can be used
69 /// instead. They are shorter but less discoverable than `as_bytes()`.
71 /// **Known Problems:** None.
75 /// let bs = "a byte string".as_bytes();
77 declare_clippy_lint! {
78 pub STRING_LIT_AS_BYTES,
80 "calling `as_bytes` on a string literal instead of using a byte string literal"
83 #[derive(Copy, Clone)]
86 impl LintPass for StringAdd {
87 fn get_lints(&self) -> LintArray {
88 lint_array!(STRING_ADD, STRING_ADD_ASSIGN)
92 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd {
93 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
94 if let ExprKind::Binary(
96 node: BinOpKind::Add, ..
102 if is_string(cx, left) {
103 if !is_allowed(cx, STRING_ADD_ASSIGN, e.id) {
104 let parent = get_parent_expr(cx, e);
105 if let Some(p) = parent {
106 if let ExprKind::Assign(ref target, _) = p.node {
107 // avoid duplicate matches
108 if SpanlessEq::new(cx).eq_expr(target, left) {
118 "you added something to a string. Consider using `String::push_str()` instead",
121 } else if let ExprKind::Assign(ref target, ref src) = e.node {
122 if is_string(cx, target) && is_add(cx, src, target) {
127 "you assigned the result of adding something to this string. Consider using \
128 `String::push_str()` instead",
135 fn is_string(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
136 match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(e)), &paths::STRING)
139 fn is_add(cx: &LateContext<'_, '_>, src: &Expr, target: &Expr) -> bool {
143 node: BinOpKind::Add, ..
147 ) => SpanlessEq::new(cx).eq_expr(target, left),
148 ExprKind::Block(ref block, _) => {
149 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
155 #[derive(Copy, Clone)]
156 pub struct StringLitAsBytes;
158 impl LintPass for StringLitAsBytes {
159 fn get_lints(&self) -> LintArray {
160 lint_array!(STRING_LIT_AS_BYTES)
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::syntax::ast::{LitKind, StrStyle};
167 use crate::utils::{in_macro, snippet};
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 if callsite.starts_with("include_str!") {
185 "calling `as_bytes()` on `include_str!(..)`",
186 "consider using `include_bytes!(..)` instead",
187 snippet(cx, args[0].span, r#""foo""#).replacen("include_str", "include_bytes", 1),
189 } else if callsite == expanded
190 && lit_content.as_str().chars().all(|c| c.is_ascii())
191 && !in_macro(args[0].span)
197 "calling `as_bytes()` on a string literal",
198 "consider using a byte string literal instead",
199 format!("b{}", snippet(cx, args[0].span, r#""foo""#)),