Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/tools/clang-rename/ClangRename.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- tools/extra/clang-rename/ClangRename.cpp - Clang rename tool -----===//
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
///
9
/// \file
10
/// This file implements a clang-rename tool that automatically finds and
11
/// renames symbols in C++ code.
12
///
13
//===----------------------------------------------------------------------===//
14
15
#include "clang/Basic/Diagnostic.h"
16
#include "clang/Basic/DiagnosticOptions.h"
17
#include "clang/Basic/FileManager.h"
18
#include "clang/Basic/IdentifierTable.h"
19
#include "clang/Basic/LangOptions.h"
20
#include "clang/Basic/SourceManager.h"
21
#include "clang/Basic/TokenKinds.h"
22
#include "clang/Frontend/TextDiagnosticPrinter.h"
23
#include "clang/Rewrite/Core/Rewriter.h"
24
#include "clang/Tooling/CommonOptionsParser.h"
25
#include "clang/Tooling/Refactoring.h"
26
#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
27
#include "clang/Tooling/Refactoring/Rename/USRFindingAction.h"
28
#include "clang/Tooling/ReplacementsYaml.h"
29
#include "clang/Tooling/Tooling.h"
30
#include "llvm/ADT/IntrusiveRefCntPtr.h"
31
#include "llvm/Support/CommandLine.h"
32
#include "llvm/Support/FileSystem.h"
33
#include "llvm/Support/YAMLTraits.h"
34
#include "llvm/Support/raw_ostream.h"
35
#include <string>
36
#include <system_error>
37
38
using namespace llvm;
39
using namespace clang;
40
41
/// An oldname -> newname rename.
42
struct RenameAllInfo {
43
  unsigned Offset = 0;
44
  std::string QualifiedName;
45
  std::string NewName;
46
};
47
48
LLVM_YAML_IS_SEQUENCE_VECTOR(RenameAllInfo)
49
50
namespace llvm {
51
namespace yaml {
52
53
/// Specialized MappingTraits to describe how a RenameAllInfo is
54
/// (de)serialized.
55
template <> struct MappingTraits<RenameAllInfo> {
56
4
  static void mapping(IO &IO, RenameAllInfo &Info) {
57
4
    IO.mapOptional("Offset", Info.Offset);
58
4
    IO.mapOptional("QualifiedName", Info.QualifiedName);
59
4
    IO.mapRequired("NewName", Info.NewName);
60
4
  }
61
};
62
63
} // end namespace yaml
64
} // end namespace llvm
65
66
static cl::OptionCategory ClangRenameOptions("clang-rename common options");
67
68
static cl::list<unsigned> SymbolOffsets(
69
    "offset",
70
    cl::desc("Locates the symbol by offset as opposed to <line>:<column>."),
71
    cl::ZeroOrMore, cl::cat(ClangRenameOptions));
72
static cl::opt<bool> Inplace("i", cl::desc("Overwrite edited <file>s."),
73
                             cl::cat(ClangRenameOptions));
74
static cl::list<std::string>
75
    QualifiedNames("qualified-name",
76
                   cl::desc("The fully qualified name of the symbol."),
77
                   cl::ZeroOrMore, cl::cat(ClangRenameOptions));
78
79
static cl::list<std::string>
80
    NewNames("new-name", cl::desc("The new name to change the symbol to."),
81
             cl::ZeroOrMore, cl::cat(ClangRenameOptions));
82
static cl::opt<bool> PrintName(
83
    "pn",
84
    cl::desc("Print the found symbol's name prior to renaming to stderr."),
85
    cl::cat(ClangRenameOptions));
86
static cl::opt<bool> PrintLocations(
87
    "pl", cl::desc("Print the locations affected by renaming to stderr."),
88
    cl::cat(ClangRenameOptions));
89
static cl::opt<std::string>
90
    ExportFixes("export-fixes",
91
                cl::desc("YAML file to store suggested fixes in."),
92
                cl::value_desc("filename"), cl::cat(ClangRenameOptions));
93
static cl::opt<std::string>
94
    Input("input", cl::desc("YAML file to load oldname-newname pairs from."),
95
          cl::Optional, cl::cat(ClangRenameOptions));
96
static cl::opt<bool> Force("force",
97
                           cl::desc("Ignore nonexistent qualified names."),
98
                           cl::cat(ClangRenameOptions));
99
100
64
int main(int argc, const char **argv) {
101
64
  tooling::CommonOptionsParser OP(argc, argv, ClangRenameOptions);
102
64
103
64
  if (!Input.empty()) {
104
2
    // Populate QualifiedNames and NewNames from a YAML file.
105
2
    ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
106
2
        llvm::MemoryBuffer::getFile(Input);
107
2
    if (!Buffer) {
108
0
      errs() << "clang-rename: failed to read " << Input << ": "
109
0
             << Buffer.getError().message() << "\n";
110
0
      return 1;
111
0
    }
112
2
113
2
    std::vector<RenameAllInfo> Infos;
114
2
    llvm::yaml::Input YAML(Buffer.get()->getBuffer());
115
2
    YAML >> Infos;
116
4
    for (const auto &Info : Infos) {
117
4
      if (!Info.QualifiedName.empty())
118
2
        QualifiedNames.push_back(Info.QualifiedName);
119
2
      else
120
2
        SymbolOffsets.push_back(Info.Offset);
121
4
      NewNames.push_back(Info.NewName);
122
4
    }
123
2
  }
124
64
125
64
  // Check the arguments for correctness.
126
64
  if (NewNames.empty()) {
127
1
    errs() << "clang-rename: -new-name must be specified.\n\n";
128
1
    return 1;
129
1
  }
130
63
131
63
  if (SymbolOffsets.empty() == QualifiedNames.empty()) {
132
0
    errs() << "clang-rename: -offset and -qualified-name can't be present at "
133
0
              "the same time.\n";
134
0
    return 1;
135
0
  }
136
63
137
63
  // Check if NewNames is a valid identifier in C++17.
138
63
  LangOptions Options;
139
63
  Options.CPlusPlus = true;
140
63
  Options.CPlusPlus17 = true;
141
63
  IdentifierTable Table(Options);
142
68
  for (const auto &NewName : NewNames) {
143
68
    auto NewNameTokKind = Table.get(NewName).getTokenID();
144
68
    if (!tok::isAnyIdentifier(NewNameTokKind)) {
145
1
      errs() << "ERROR: new name is not a valid identifier in C++17.\n\n";
146
1
      return 1;
147
1
    }
148
68
  }
149
63
150
63
  
if (62
SymbolOffsets.size() + QualifiedNames.size() != NewNames.size()62
) {
151
0
    errs() << "clang-rename: number of symbol offsets(" << SymbolOffsets.size()
152
0
           << ") + number of qualified names (" << QualifiedNames.size()
153
0
           << ") must be equal to number of new names(" << NewNames.size()
154
0
           << ").\n\n";
155
0
    cl::PrintHelpMessage();
156
0
    return 1;
157
0
  }
158
62
159
62
  auto Files = OP.getSourcePathList();
160
62
  tooling::RefactoringTool Tool(OP.getCompilations(), Files);
161
62
  tooling::USRFindingAction FindingAction(SymbolOffsets, QualifiedNames, Force);
162
62
  Tool.run(tooling::newFrontendActionFactory(&FindingAction).get());
163
62
  const std::vector<std::vector<std::string>> &USRList =
164
62
      FindingAction.getUSRList();
165
62
  const std::vector<std::string> &PrevNames = FindingAction.getUSRSpellings();
166
62
  if (PrintName) {
167
0
    for (const auto &PrevName : PrevNames) {
168
0
      outs() << "clang-rename found name: " << PrevName << '\n';
169
0
    }
170
0
  }
171
62
172
62
  if (FindingAction.errorOccurred()) {
173
1
    // Diagnostics are already issued at this point.
174
1
    return 1;
175
1
  }
176
61
177
61
  // Perform the renaming.
178
61
  tooling::RenamingAction RenameAction(NewNames, PrevNames, USRList,
179
61
                                       Tool.getReplacements(), PrintLocations);
180
61
  std::unique_ptr<tooling::FrontendActionFactory> Factory =
181
61
      tooling::newFrontendActionFactory(&RenameAction);
182
61
  int ExitCode;
183
61
184
61
  if (Inplace) {
185
0
    ExitCode = Tool.runAndSave(Factory.get());
186
61
  } else {
187
61
    ExitCode = Tool.run(Factory.get());
188
61
189
61
    if (!ExportFixes.empty()) {
190
0
      std::error_code EC;
191
0
      llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::OF_None);
192
0
      if (EC) {
193
0
        llvm::errs() << "Error opening output file: " << EC.message() << '\n';
194
0
        return 1;
195
0
      }
196
0
197
0
      // Export replacements.
198
0
      tooling::TranslationUnitReplacements TUR;
199
0
      const auto &FileToReplacements = Tool.getReplacements();
200
0
      for (const auto &Entry : FileToReplacements)
201
0
        TUR.Replacements.insert(TUR.Replacements.end(), Entry.second.begin(),
202
0
                                Entry.second.end());
203
0
204
0
      yaml::Output YAML(OS);
205
0
      YAML << TUR;
206
0
      OS.close();
207
0
      return 0;
208
0
    }
209
61
210
61
    // Write every file to stdout. Right now we just barf the files without any
211
61
    // indication of which files start where, other than that we print the files
212
61
    // in the same order we see them.
213
61
    LangOptions DefaultLangOptions;
214
61
    IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
215
61
    TextDiagnosticPrinter DiagnosticPrinter(errs(), &*DiagOpts);
216
61
    DiagnosticsEngine Diagnostics(
217
61
        IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
218
61
        &DiagnosticPrinter, false);
219
61
    auto &FileMgr = Tool.getFiles();
220
61
    SourceManager Sources(Diagnostics, FileMgr);
221
61
    Rewriter Rewrite(Sources, DefaultLangOptions);
222
61
223
61
    Tool.applyAllReplacements(Rewrite);
224
61
    for (const auto &File : Files) {
225
61
      auto Entry = FileMgr.getFile(File);
226
61
      const auto ID = Sources.getOrCreateFileID(*Entry, SrcMgr::C_User);
227
61
      Rewrite.getEditBuffer(ID).write(outs());
228
61
    }
229
61
  }
230
61
231
61
  return ExitCode;
232
61
}