Skip to content

Fix string_lit_as_bytes lint for macros #3217

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 28, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 38 additions & 11 deletions clippy_lints/src/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.


use crate::rustc::hir::*;
use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use crate::rustc::{declare_tool_lint, lint_array};
Expand Down Expand Up @@ -92,7 +91,14 @@ impl LintPass for StringAdd {

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
if let ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, ref left, _) = e.node {
if let ExprKind::Binary(
Spanned {
node: BinOpKind::Add, ..
},
ref left,
_,
) = e.node
{
if is_string(cx, left) {
if !is_allowed(cx, STRING_ADD_ASSIGN, e.id) {
let parent = get_parent_expr(cx, e);
Expand Down Expand Up @@ -132,13 +138,15 @@ fn is_string(cx: &LateContext<'_, '_>, e: &Expr) -> bool {

fn is_add(cx: &LateContext<'_, '_>, src: &Expr, target: &Expr) -> bool {
match src.node {
ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, ref left, _) => SpanlessEq::new(cx).eq_expr(target, left),
ExprKind::Binary(
Spanned {
node: BinOpKind::Add, ..
},
ref left,
_,
) => SpanlessEq::new(cx).eq_expr(target, left),
ExprKind::Block(ref block, _) => {
block.stmts.is_empty()
&& block
.expr
.as_ref()
.map_or(false, |expr| is_add(cx, expr, target))
block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| is_add(cx, expr, target))
},
_ => false,
}
Expand All @@ -155,14 +163,33 @@ impl LintPass for StringLitAsBytes {

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringLitAsBytes {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
use crate::syntax::ast::LitKind;
use crate::syntax::ast::{LitKind, StrStyle};
use crate::utils::{in_macro, snippet};

if let ExprKind::MethodCall(ref path, _, ref args) = e.node {
if path.ident.name == "as_bytes" {
if let ExprKind::Lit(ref lit) = args[0].node {
if let LitKind::Str(ref lit_content, _) = lit.node {
if lit_content.as_str().chars().all(|c| c.is_ascii()) && !in_macro(args[0].span) {
if let LitKind::Str(ref lit_content, style) = lit.node {
let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
let expanded = if let StrStyle::Raw(n) = style {
let term = (0..n).map(|_| '#').collect::<String>();
format!("r{0}\"{1}\"{0}", term, lit_content.as_str())
} else {
format!("\"{}\"", lit_content.as_str())
};
if callsite.starts_with("include_str!") {
span_lint_and_sugg(
cx,
STRING_LIT_AS_BYTES,
e.span,
"calling `as_bytes()` on `include_str!(..)`",
"consider using `include_bytes!(..)` instead",
snippet(cx, args[0].span, r#""foo""#).replacen("include_str", "include_bytes", 1),
);
} else if callsite == expanded
&& lit_content.as_str().chars().all(|c| c.is_ascii())
&& !in_macro(args[0].span)
{
span_lint_and_sugg(
cx,
STRING_LIT_AS_BYTES,
Expand Down
11 changes: 8 additions & 3 deletions tests/ui/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@




#[warn(clippy::string_add)]
#[allow(clippy::string_add_assign)]
fn add_only() { // ignores assignment distinction
fn add_only() {
// ignores assignment distinction
let mut x = "".to_owned();

for _ in 1..3 {
Expand Down Expand Up @@ -59,19 +59,24 @@ fn both() {
fn str_lit_as_bytes() {
let bs = "hello there".as_bytes();

let bs = r###"raw string with three ### in it and some " ""###.as_bytes();

// no warning, because this cannot be written as a byte string literal:
let ubs = "☃".as_bytes();

let strify = stringify!(foobar).as_bytes();

let includestr = include_str!("entry.rs").as_bytes();
}

#[allow(clippy::assign_op_pattern)]
fn main() {
add_only();
add_assign_only();
both();

// the add is only caught for `String`
let mut x = 1;
; x = x + 1;
x = x + 1;
assert_eq!(2, x);
}
14 changes: 7 additions & 7 deletions tests/ui/strings.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,16 @@ error: calling `as_bytes()` on a string literal
= note: `-D clippy::string-lit-as-bytes` implied by `-D warnings`

error: calling `as_bytes()` on a string literal
--> $DIR/strings.rs:65:18
--> $DIR/strings.rs:62:14
|
65 | let strify = stringify!(foobar).as_bytes();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using a byte string literal instead: `bstringify!(foobar)`
62 | let bs = r###"raw string with three ### in it and some " ""###.as_bytes();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using a byte string literal instead: `br###"raw string with three ### in it and some " ""###`

error: manual implementation of an assign operation
--> $DIR/strings.rs:75:7
error: calling `as_bytes()` on `include_str!(..)`
--> $DIR/strings.rs:69:22
|
75 | ; x = x + 1;
| ^^^^^^^^^ help: replace it with: `x += 1`
69 | let includestr = include_str!("entry.rs").as_bytes();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `include_bytes!(..)` instead: `include_bytes!("entry.rs")`

error: aborting due to 11 previous errors