From 19ac2e94c6cb12ae4f9fb410f165e2aa5309e124 Mon Sep 17 00:00:00 2001 From: Jane Lusby Date: Fri, 26 Oct 2018 09:10:20 -0700 Subject: [PATCH] fix: correctly reconstruct raw strings --- clippy_lints/src/strings.rs | 12 ++++++++---- tests/ui/strings.stderr | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/clippy_lints/src/strings.rs b/clippy_lints/src/strings.rs index fe3d461ab43..e07b1649a46 100644 --- a/clippy_lints/src/strings.rs +++ b/clippy_lints/src/strings.rs @@ -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}; @@ -164,15 +163,20 @@ 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 let LitKind::Str(ref lit_content, style) = lit.node { let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#); - let expanded = format!("\"{}\"", lit_content.as_str()); + let expanded = if let StrStyle::Raw(n) = style { + let term = (0..n).map(|_| '#').collect::(); + 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, diff --git a/tests/ui/strings.stderr b/tests/ui/strings.stderr index 2496270ba0d..21115d8e97e 100644 --- a/tests/ui/strings.stderr +++ b/tests/ui/strings.stderr @@ -60,3 +60,17 @@ 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:62:14 + | +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: calling `as_bytes()` on `include_str!(..)` + --> $DIR/strings.rs:69:22 + | +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 +