Skip to content

Commit

Permalink
fix: correctly reconstruct raw strings
Browse files Browse the repository at this point in the history
  • Loading branch information
yaahc committed Oct 26, 2018
1 parent f9020bb commit 19ac2e9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
12 changes: 8 additions & 4 deletions clippy_lints/src/strings.rs
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 @@ -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::<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,
Expand Down
14 changes: 14 additions & 0 deletions tests/ui/strings.stderr
Expand Up @@ -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

0 comments on commit 19ac2e9

Please sign in to comment.