Skip to content

Commit 19ac2e9

Browse files
committed
fix: correctly reconstruct raw strings
1 parent f9020bb commit 19ac2e9

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

clippy_lints/src/strings.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
// option. This file may not be copied, modified, or distributed
88
// except according to those terms.
99

10-
1110
use crate::rustc::hir::*;
1211
use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
1312
use crate::rustc::{declare_tool_lint, lint_array};
@@ -164,15 +163,20 @@ impl LintPass for StringLitAsBytes {
164163

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

170169
if let ExprKind::MethodCall(ref path, _, ref args) = e.node {
171170
if path.ident.name == "as_bytes" {
172171
if let ExprKind::Lit(ref lit) = args[0].node {
173-
if let LitKind::Str(ref lit_content, _) = lit.node {
172+
if let LitKind::Str(ref lit_content, style) = lit.node {
174173
let callsite = snippet(cx, args[0].span.source_callsite(), r#""foo""#);
175-
let expanded = format!("\"{}\"", lit_content.as_str());
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())
177+
} else {
178+
format!("\"{}\"", lit_content.as_str())
179+
};
176180
if callsite.starts_with("include_str!") {
177181
span_lint_and_sugg(
178182
cx,

tests/ui/strings.stderr

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,17 @@ error: calling `as_bytes()` on a string literal
6060
|
6161
= note: `-D clippy::string-lit-as-bytes` implied by `-D warnings`
6262

63+
error: calling `as_bytes()` on a string literal
64+
--> $DIR/strings.rs:62:14
65+
|
66+
62 | let bs = r###"raw string with three ### in it and some " ""###.as_bytes();
67+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using a byte string literal instead: `br###"raw string with three ### in it and some " ""###`
68+
69+
error: calling `as_bytes()` on `include_str!(..)`
70+
--> $DIR/strings.rs:69:22
71+
|
72+
69 | let includestr = include_str!("entry.rs").as_bytes();
73+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `include_bytes!(..)` instead: `include_bytes!("entry.rs")`
74+
75+
error: aborting due to 11 previous errors
76+

0 commit comments

Comments
 (0)