LegalizeAdulthood created this revision.
LegalizeAdulthood added a reviewer: alexfh.
LegalizeAdulthood added a subscriber: cfe-commits.

This check examines string literals and looks for those that could be more 
directly expressed as a raw string literal.

Example:

```
char const *const BackSlash{"goink\\frob"};
```

becomes:

```
char const *const BackSlash{R"(goink\frob)"};
```

Addresses PR24444

http://reviews.llvm.org/D16529

Files:
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tidy/modernize/RawStringLiteralCheck.cpp
  clang-tidy/modernize/RawStringLiteralCheck.h
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-raw-string-literal.rst
  test/clang-tidy/modernize-raw-string-literal.cpp

Index: test/clang-tidy/modernize-raw-string-literal.cpp
===================================================================
--- /dev/null
+++ test/clang-tidy/modernize-raw-string-literal.cpp
@@ -0,0 +1,55 @@
+// RUN: %check_clang_tidy %s modernize-raw-string-literal %t
+
+char const *const BackSlash{"goink\\frob"};
+// CHECK-MESSAGES: :[[@LINE-1]]:29: warning: escaped string literal can be written as a raw string literal [modernize-raw-string-literal]
+// CHECK-FIXES: {{^}}char const *const BackSlash{R"(goink\frob)"};{{$}}
+
+char const *const Bell{"goink\a\\frob"};
+char const *const BackSpace{"goink\b\\frob"};
+char const *const FormFeed{"goink\f\\frob"};
+char const *const CarraigeReturn{"goink\r\\frob"};
+char const *const HorizontalTab{"goink\t\\frob"};
+char const *const VerticalTab{"goink\v\\frob"};
+char const *const OctalNonPrintable{"\003"};
+char const *const HexNonPrintable{"\x03"};
+
+char const *const NewLine{"goink\nfrob"};
+// CHECK-MESSAGES: :[[@LINE-1]]:27: warning: {{.*}} can be written as a raw string literal
+// CHECK-FIXES: {{^}}char const *const NewLine{R"(goink{{$}}
+// CHECK-FIXES-NEXT: {{^}}frob)"};{{$}}
+
+char const *const SingleQuote{"goink\'frob"};
+// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: {{.*}} can be written as a raw string literal
+// CHECK-XFIXES: {{^}}char const *const SingleQuote{R"(goink'frob)"};{{$}}
+
+char const *const DoubleQuote{"goink\"frob"};
+// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: {{.*}} can be written as a raw string literal
+// CHECK-FIXES: {{^}}char const *const DoubleQuote{R"(goink"frob)"};{{$}}
+
+char const *const QuestionMark{"goink\?frob"};
+// CHECK-MESSAGES: :[[@LINE-1]]:32: warning: {{.*}} can be written as a raw string literal
+// CHECK-FIXES: {{^}}char const *const QuestionMark{R"(goink?frob)"};{{$}}
+
+char const *const RegEx{"goink\\(one|two\\)\\\\\\?.*\\nfrob"};
+// CHECK-MESSAGES: :[[@LINE-1]]:25: warning: {{.*}} can be written as a raw string literal
+// CHECK-FIXES: {{^}}char const *const RegEx{R"(goink\(one|two\)\\\?.*\nfrob)"};{{$}}
+
+char const *const Path{"C:\\Program Files\\Vendor\\Application\\Application.exe"};
+// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: {{.*}} can be written as a raw string literal
+// CHECK-FIXES: {{^}}char const *const Path{R"(C:\Program Files\Vendor\Application\Application.exe)"};{{$}}
+
+char const *const ContainsSentinel{"who\\ops)\""};
+// CHECK-MESSAGES: :[[@LINE-1]]:36: warning: {{.*}} can be written as a raw string literal
+// CHECK-FIXES: {{^}}char const *const ContainsSentinel{R"lit(who\ops)")lit"};{{$}}
+
+char const *const ContainsDelim{"whoops)\")lit\""};
+// CHECK-MESSAGES: :[[@LINE-1]]:33: warning: {{.*}} can be written as a raw string literal
+// CHECK-FIXES: {{^}}char const *const ContainsDelim{R"lit1(whoops)")lit")lit1"};{{$}}
+
+char const *const OctalPrintable{"\100\\"};
+// CHECK-MESSAGES: :[[@LINE-1]]:34: warning: {{.*}} can be written as a raw string literal
+// CHECK-FIXES: {{^}}char const *const OctalPrintable{R"(@\)"};{{$}}
+
+char const *const HexPrintable{"\x40\\"};
+// CHECK-MESSAGES: :[[@LINE-1]]:32: warning: {{.*}} can be written as a raw string literal
+// CHECK-FIXES: {{^}}char const *const HexPrintable{R"(@\)"};{{$}}
Index: docs/clang-tidy/checks/modernize-raw-string-literal.rst
===================================================================
--- /dev/null
+++ docs/clang-tidy/checks/modernize-raw-string-literal.rst
@@ -0,0 +1,29 @@
+.. title:: clang-tidy - modernize-raw-string-literal
+
+modernize-raw-string-literal
+============================
+
+This check replaces string literals containing escaped characters with
+raw string literals.
+
+Example:
+
+.. code-blocK:: c++
+
+  const char *const quotes{"embedded \"quotes\""};
+
+becomes
+
+.. code-block:: c++
+
+  const char *const quotes{R"(embedded "quotes")"};
+
+The presence of any of the following escapes cause the string to be
+converted to a raw string literal: ``\\``, ``\'``, ``\"``, ``\?``,
+and octal or hexadecimal escapes for printable ASCII characters.
+
+If an escaped newline is present in a converted string, it is
+replaced with a physical newline.  If an escaped tab or vertical
+tab is present in a string, it prevents the string from being
+converted.  Unlike a physical newline, the presence of a physical
+tab or vertical tab in source code is not visually obvious.
Index: docs/clang-tidy/checks/list.rst
===================================================================
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -69,6 +69,7 @@
    modernize-loop-convert
    modernize-make-unique
    modernize-pass-by-value
+   modernize-raw-string-literal
    modernize-redundant-void-arg
    modernize-replace-auto-ptr
    modernize-shrink-to-fit
Index: clang-tidy/modernize/RawStringLiteralCheck.h
===================================================================
--- /dev/null
+++ clang-tidy/modernize/RawStringLiteralCheck.h
@@ -0,0 +1,41 @@
+//===--- RawStringLiteralCheck.h - clang-tidy--------------------*- C++ -*-===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_RAW_STRING_LITERAL_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_RAW_STRING_LITERAL_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+/// This check replaces string literals with escaped characters to
+/// raw string literals.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/modernize-raw-string-literal.html
+class RawStringLiteralCheck : public ClangTidyCheck {
+public:
+  RawStringLiteralCheck(StringRef Name, ClangTidyContext *Context)
+      : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+
+private:
+  void
+  preferRawStringLiterals(const ast_matchers::MatchFinder::MatchResult &Result,
+                          const StringLiteral *Literal);
+};
+
+} // namespace modernize
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_RAW_STRING_LITERAL_H
Index: clang-tidy/modernize/RawStringLiteralCheck.cpp
===================================================================
--- /dev/null
+++ clang-tidy/modernize/RawStringLiteralCheck.cpp
@@ -0,0 +1,91 @@
+//===--- RawStringLiteralCheck.cpp - clang-tidy----------------------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "RawStringLiteralCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+#include <sstream>
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+namespace {
+
+bool containsEscapedCharacters(const MatchFinder::MatchResult &Result,
+                               const StringLiteral *Literal) {
+  if (Literal->getBytes().find_first_of("\a\b\f\r\t\v") != StringRef::npos)
+    return false;
+
+  CharSourceRange CharRange = Lexer::makeFileCharRange(
+      CharSourceRange::getTokenRange(Literal->getSourceRange()),
+      *Result.SourceManager, Result.Context->getLangOpts());
+  StringRef Text = Lexer::getSourceText(CharRange, *Result.SourceManager,
+                                        Result.Context->getLangOpts());
+  const bool HasBackSlash = Text.find(R"(\\)") != StringRef::npos;
+  const bool HasNewLine = Text.find(R"(\n)") != StringRef::npos;
+  const bool HasQuote = Text.find(R"(\')") != StringRef::npos;
+  const bool HasDoubleQuote = Text.find(R"(\")") != StringRef::npos;
+  const bool HasQuestion = Text.find(R"(\?)") != StringRef::npos;
+  return HasBackSlash || HasNewLine || HasQuote || HasDoubleQuote ||
+         HasQuestion;
+}
+
+bool containsDelimiter(StringRef Bytes, const std::string &Delimiter) {
+  return Bytes.find(")" + Delimiter + R"(")") != StringRef::npos;
+}
+
+std::string asRawStringLiteral(const StringLiteral *Literal) {
+  const StringRef Bytes = Literal->getBytes();
+  std::string Delimiter;
+  for (int Counter = 0; containsDelimiter(Bytes, Delimiter); ++Counter) {
+    if (Counter == 0) {
+      Delimiter = "lit";
+    } else {
+      std::ostringstream Str;
+      Str << "lit" << Counter;
+      Delimiter = Str.str();
+    }
+  }
+
+  return (R"(R")" + Delimiter + "(" + Bytes + ")" + Delimiter + R"(")").str();
+}
+
+} // namespace
+
+void RawStringLiteralCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(stringLiteral().bind("lit"), this);
+}
+
+void RawStringLiteralCheck::check(const MatchFinder::MatchResult &Result) {
+  if (const auto *Literal = Result.Nodes.getNodeAs<StringLiteral>("lit")) {
+    preferRawStringLiterals(Result, Literal);
+  }
+}
+
+void RawStringLiteralCheck::preferRawStringLiterals(
+    const MatchFinder::MatchResult &Result, const StringLiteral *Literal) {
+  if (containsEscapedCharacters(Result, Literal)) {
+    SourceRange ReplacementRange = Literal->getSourceRange();
+    CharSourceRange CharRange = Lexer::makeFileCharRange(
+        CharSourceRange::getTokenRange(ReplacementRange), *Result.SourceManager,
+        Result.Context->getLangOpts());
+    StringRef Replacement = asRawStringLiteral(Literal);
+    diag(Literal->getLocStart(),
+         "escaped string literal can be written as a raw string literal")
+        << FixItHint::CreateReplacement(CharRange, Replacement);
+  }
+}
+
+} // namespace modernize
+} // namespace tidy
+} // namespace clang
Index: clang-tidy/modernize/ModernizeTidyModule.cpp
===================================================================
--- clang-tidy/modernize/ModernizeTidyModule.cpp
+++ clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -13,6 +13,7 @@
 #include "LoopConvertCheck.h"
 #include "MakeUniqueCheck.h"
 #include "PassByValueCheck.h"
+#include "RawStringLiteralCheck.h"
 #include "RedundantVoidArgCheck.h"
 #include "ReplaceAutoPtrCheck.h"
 #include "ShrinkToFitCheck.h"
@@ -33,6 +34,8 @@
     CheckFactories.registerCheck<LoopConvertCheck>("modernize-loop-convert");
     CheckFactories.registerCheck<MakeUniqueCheck>("modernize-make-unique");
     CheckFactories.registerCheck<PassByValueCheck>("modernize-pass-by-value");
+    CheckFactories.registerCheck<RawStringLiteralCheck>(
+        "modernize-raw-string-literal");
     CheckFactories.registerCheck<RedundantVoidArgCheck>(
         "modernize-redundant-void-arg");
     CheckFactories.registerCheck<ReplaceAutoPtrCheck>(
Index: clang-tidy/modernize/CMakeLists.txt
===================================================================
--- clang-tidy/modernize/CMakeLists.txt
+++ clang-tidy/modernize/CMakeLists.txt
@@ -6,6 +6,7 @@
   MakeUniqueCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
+  RawStringLiteralCheck.cpp
   RedundantVoidArgCheck.cpp
   ReplaceAutoPtrCheck.cpp
   ShrinkToFitCheck.cpp
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to