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.
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
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(Spanned { node: BinOpKind::Add, .. }, ref left, _) = e.node {
96 if is_string(cx, left) {
97 if !is_allowed(cx, STRING_ADD_ASSIGN, e.id) {
98 let parent = get_parent_expr(cx, e);
99 if let Some(p) = parent {
100 if let ExprKind::Assign(ref target, _) = p.node {
101 // avoid duplicate matches
102 if SpanlessEq::new(cx).eq_expr(target, left) {
112 "you added something to a string. Consider using `String::push_str()` instead",
115 } else if let ExprKind::Assign(ref target, ref src) = e.node {
116 if is_string(cx, target) && is_add(cx, src, target) {
121 "you assigned the result of adding something to this string. Consider using \
122 `String::push_str()` instead",
129 fn is_string(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
130 match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(e)), &paths::STRING)
133 fn is_add(cx: &LateContext<'_, '_>, src: &Expr, target: &Expr) -> bool {
135 ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, ref left, _) => SpanlessEq::new(cx).eq_expr(target, left),
136 ExprKind::Block(ref block, _) => {
137 block.stmts.is_empty()
141 .map_or(false, |expr| is_add(cx, expr, target))
147 #[derive(Copy, Clone)]
148 pub struct StringLitAsBytes;
150 impl LintPass for StringLitAsBytes {
151 fn get_lints(&self) -> LintArray {
152 lint_array!(STRING_LIT_AS_BYTES)
156 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringLitAsBytes {
157 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
158 use crate::syntax::ast::LitKind;
159 use crate::utils::{in_macro, snippet};
161 if let ExprKind::MethodCall(ref path, _, ref args) = e.node {
162 if path.ident.name == "as_bytes" {
163 if let ExprKind::Lit(ref lit) = args[0].node {
164 if let LitKind::Str(ref lit_content, _) = lit.node {
165 if lit_content.as_str().chars().all(|c| c.is_ascii()) && !in_macro(args[0].span) {
170 "calling `as_bytes()` on a string literal",
171 "consider using a byte string literal instead",
172 format!("b{}", snippet(cx, args[0].span, r#""foo""#)),