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::rustc_errors::Applicability;
14 use crate::syntax::source_map::Spanned;
15 use crate::utils::SpanlessEq;
16 use crate::utils::{get_parent_expr, is_allowed, match_type, paths, span_lint, span_lint_and_sugg, walk_ptrs_ty};
18 /// **What it does:** Checks for string appends of the form `x = x + y` (without
21 /// **Why is this bad?** It's not really bad, but some people think that the
22 /// `.push_str(_)` method is more readable.
24 /// **Known problems:** None.
29 /// let mut x = "Hello".to_owned();
30 /// x = x + ", World";
32 declare_clippy_lint! {
33 pub STRING_ADD_ASSIGN,
35 "using `x = x + ..` where x is a `String` instead of `push_str()`"
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*
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.
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.
52 /// **Known problems:** None.
57 /// let x = "Hello".to_owned();
60 declare_clippy_lint! {
63 "using `x + ..` where x is a `String` instead of `push_str()`"
66 /// **What it does:** Checks for the `as_bytes` method called on string literals
67 /// that contain only ASCII characters.
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()`.
72 /// **Known Problems:** None.
76 /// let bs = "a byte string".as_bytes();
78 declare_clippy_lint! {
79 pub STRING_LIT_AS_BYTES,
81 "calling `as_bytes` on a string literal instead of using a byte string literal"
84 #[derive(Copy, Clone)]
87 impl LintPass for StringAdd {
88 fn get_lints(&self) -> LintArray {
89 lint_array!(STRING_ADD, STRING_ADD_ASSIGN)
93 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd {
94 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
95 if let ExprKind::Binary(
97 node: BinOpKind::Add, ..
103 if is_string(cx, left) {
104 if !is_allowed(cx, STRING_ADD_ASSIGN, e.id) {
105 let parent = get_parent_expr(cx, e);
106 if let Some(p) = parent {
107 if let ExprKind::Assign(ref target, _) = p.node {
108 // avoid duplicate matches
109 if SpanlessEq::new(cx).eq_expr(target, left) {
119 "you added something to a string. Consider using `String::push_str()` instead",
122 } else if let ExprKind::Assign(ref target, ref src) = e.node {
123 if is_string(cx, target) && is_add(cx, src, target) {
128 "you assigned the result of adding something to this string. Consider using \
129 `String::push_str()` instead",
136 fn is_string(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
137 match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(e)), &paths::STRING)
140 fn is_add(cx: &LateContext<'_, '_>, src: &Expr, target: &Expr) -> bool {
144 node: BinOpKind::Add, ..
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))
156 #[derive(Copy, Clone)]
157 pub struct StringLitAsBytes;
159 impl LintPass for StringLitAsBytes {
160 fn get_lints(&self) -> LintArray {
161 lint_array!(STRING_LIT_AS_BYTES)
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::syntax::ast::{LitKind, StrStyle};
168 use crate::utils::{in_macro, snippet, snippet_with_applicability};
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)