1 //===--- RawStringLiteral.cpp ------------------------------------*- C++-*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "ParsedAST.h"
9 #include "SourceCode.h"
10 #include "refactor/Tweak.h"
11 #include "support/Logger.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/RecursiveASTVisitor.h"
14 #include "clang/AST/Stmt.h"
15 #include "clang/Basic/LangOptions.h"
16 #include "clang/Basic/SourceLocation.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/Lexer.h"
19 #include "clang/Tooling/Core/Replacement.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Error.h"
26 
27 namespace clang {
28 namespace clangd {
29 namespace {
30 /// Converts a string literal to a raw string.
31 /// Before:
32 ///   printf("\"a\"\nb");
33 ///          ^^^^^^^^^
34 /// After:
35 ///   printf(R"("a"
36 /// b)");
37 class RawStringLiteral : public Tweak {
38 public:
39   const char *id() const override final;
40 
41   bool prepare(const Selection &Inputs) override;
42   Expected<Effect> apply(const Selection &Inputs) override;
title() const43   std::string title() const override { return "Convert to raw string"; }
kind() const44   llvm::StringLiteral kind() const override {
45     return CodeAction::REFACTOR_KIND;
46   }
47 
48 private:
49   const clang::StringLiteral *Str = nullptr;
50 };
51 
REGISTER_TWEAK(RawStringLiteral)52 REGISTER_TWEAK(RawStringLiteral)
53 
54 static bool isNormalString(const StringLiteral &Str, SourceLocation Cursor,
55                           SourceManager &SM) {
56   // All chunks must be normal ASCII strings, not u8"..." etc.
57   if (!Str.isAscii())
58     return false;
59   SourceLocation LastTokenBeforeCursor;
60   for (auto I = Str.tokloc_begin(), E = Str.tokloc_end(); I != E; ++I) {
61     if (I->isMacroID()) // No tokens in the string may be macro expansions.
62       return false;
63     if (SM.isBeforeInTranslationUnit(*I, Cursor) || *I == Cursor)
64       LastTokenBeforeCursor = *I;
65   }
66   // Token we care about must be a normal "string": not raw, u8, etc.
67   const char* Data = SM.getCharacterData(LastTokenBeforeCursor);
68   return Data && *Data == '"';
69 }
70 
needsRaw(llvm::StringRef Content)71 static bool needsRaw(llvm::StringRef Content) {
72   return Content.find_first_of("\"\n\t") != StringRef::npos;
73 }
74 
canBeRaw(llvm::StringRef Content)75 static bool canBeRaw(llvm::StringRef Content) {
76   for (char C : Content)
77     if (!llvm::isPrint(C) && C != '\n' && C != '\t')
78       return false;
79   return !Content.contains(")\"");
80 }
81 
prepare(const Selection & Inputs)82 bool RawStringLiteral::prepare(const Selection &Inputs) {
83   const SelectionTree::Node *N = Inputs.ASTSelection.commonAncestor();
84   if (!N)
85     return false;
86   Str = dyn_cast_or_null<StringLiteral>(N->ASTNode.get<Stmt>());
87   return Str &&
88          isNormalString(*Str, Inputs.Cursor, Inputs.AST->getSourceManager()) &&
89          needsRaw(Str->getBytes()) && canBeRaw(Str->getBytes());
90 }
91 
apply(const Selection & Inputs)92 Expected<Tweak::Effect> RawStringLiteral::apply(const Selection &Inputs) {
93   auto &SM = Inputs.AST->getSourceManager();
94   auto Reps = tooling::Replacements(
95       tooling::Replacement(SM, Str, ("R\"(" + Str->getBytes() + ")\"").str(),
96                            Inputs.AST->getLangOpts()));
97   return Effect::mainFileEdit(SM, std::move(Reps));
98 }
99 
100 } // namespace
101 } // namespace clangd
102 } // namespace clang
103