LegalizeAdulthood updated this revision to Diff 46101.
LegalizeAdulthood marked 2 inline comments as done.
LegalizeAdulthood added a comment.

Update from comments:

- leave existing raw string literals unchanged
- don't change UTF-8, UTF-16, UTF-32 or wide character string literals
- apply changes only to C++11 or later source files
- improve detection of strings with control characters


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,65 @@
+// 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 Delete{"\\\177"};
+char const *const AlreadyRaw{R"(foobie\\bletch)"};
+char const *const UTF8Literal{u8"foobie\\bletch"};
+char const *const UTF8RawLiteral{u8R"(foobie\\bletch)"};
+char16_t const *const UTF16Literal{u"foobie\\bletch"};
+char16_t const *const UTF16RawLiteral{uR"(foobie\\bletch)"};
+char32_t const *const UTF32Literal{U"foobie\\bletch"};
+char32_t const *const UTF32RawLiteral{UR"(foobie\\bletch)"};
+wchar_t const *const WideLiteral{L"foobie\\bletch"};
+wchar_t const *const WideRawLiteral{LR"(foobie\\bletch)"};
+
+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,126 @@
+//===--- 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) {
+  // we only transform ASCII string literals
+  if (!Literal->isAscii())
+    return false;
+
+  StringRef Bytes = Literal->getBytes();
+  // non-printing escapes except newline disqualify this literal
+  // \007 = \a bell
+  // \010 = \b backspace
+  // \011 = \t horizontal tab
+  // \012 = \n new line
+  // \013 = \v vertical tab
+  // \014 = \f form feed
+  // \015 = \r carriage return
+  // \177 = delete
+  if (Bytes.find_first_of("\001\002\003\004\005\006\a"
+                          "\b\t\v\f\r\016\017"
+                          "\020\021\022\023\024\025\026\027"
+                          "\030\031\032\033\034\035\036\037"
+                          "\177") != StringRef::npos)
+    return false;
+
+  // \000 = NUL
+  if (Bytes.find_first_of(StringRef("\000", 1)) != 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());
+
+  // already a raw string literal if R comes before "
+  if (Text.find_first_of("R") < Text.find_first_of(R"(")"))
+    return false;
+
+  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) {
+  const LangOptions &Options = Result.Context->getLangOpts();
+  // can't do this for non C++ code
+  if (!Options.CPlusPlus)
+    return;
+
+  // raw string literals require C++11 or later
+  if (!Options.CPlusPlus11 && !Options.CPlusPlus14 && !Options.CPlusPlus1z)
+    return;
+
+  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