blob: 02a97839f151843b6f33cf8ed8b3e8de18f09473 [file] [log] [blame]
Eric Liu495b2112016-09-19 17:40:32 +00001//===-- ClangIncludeFixer.cpp - Standalone change namespace ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// This tool can be used to change the surrounding namespaces of class/function
10// definitions.
11//
12// Example: test.cc
13// namespace na {
14// class X {};
15// namespace nb {
16// class Y { X x; };
17// } // namespace nb
18// } // namespace na
19// To move the definition of class Y from namespace "na::nb" to "x::y", run:
20// clang-change-namespace --old_namespace "na::nb" \
21// --new_namespace "x::y" --file_pattern "test.cc" test.cc --
22// Output:
23// namespace na {
24// class X {};
25// } // namespace na
26// namespace x {
27// namespace y {
28// class Y { na::X x; };
29// } // namespace y
30// } // namespace x
31
32#include "ChangeNamespace.h"
Eric Liu77b0c1a2016-09-19 20:41:39 +000033#include "clang/ASTMatchers/ASTMatchFinder.h"
Eric Liu495b2112016-09-19 17:40:32 +000034#include "clang/Frontend/FrontendActions.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
36#include "clang/Rewrite/Core/Rewriter.h"
37#include "clang/Tooling/CommonOptionsParser.h"
38#include "clang/Tooling/Refactoring.h"
39#include "clang/Tooling/Tooling.h"
40#include "llvm/Support/CommandLine.h"
Eric Liu3db05212016-10-13 18:56:14 +000041#include "llvm/Support/Signals.h"
Eric Liua13c4192017-02-13 17:24:14 +000042#include "llvm/Support/YAMLTraits.h"
Eric Liu495b2112016-09-19 17:40:32 +000043
44using namespace clang;
45using namespace llvm;
46
47namespace {
48
49cl::OptionCategory ChangeNamespaceCategory("Change namespace.");
50
51cl::opt<std::string> OldNamespace("old_namespace", cl::Required,
52 cl::desc("Old namespace."),
53 cl::cat(ChangeNamespaceCategory));
54
55cl::opt<std::string> NewNamespace("new_namespace", cl::Required,
56 cl::desc("New namespace."),
57 cl::cat(ChangeNamespaceCategory));
58
59cl::opt<std::string> FilePattern(
60 "file_pattern", cl::Required,
61 cl::desc("Only rename namespaces in files that match the given pattern."),
62 cl::cat(ChangeNamespaceCategory));
63
64cl::opt<bool> Inplace("i", cl::desc("Inplace edit <file>s, if specified."),
65 cl::cat(ChangeNamespaceCategory));
66
Eric Liua13c4192017-02-13 17:24:14 +000067cl::opt<bool>
68 DumpYAML("dump_result",
69 cl::desc("Dump new file contents in YAML, if specified."),
70 cl::cat(ChangeNamespaceCategory));
71
Eric Liu495b2112016-09-19 17:40:32 +000072cl::opt<std::string> Style("style",
73 cl::desc("The style name used for reformatting."),
74 cl::init("LLVM"), cl::cat(ChangeNamespaceCategory));
75
Eric Liu7fccc992017-02-24 11:54:45 +000076cl::opt<std::string> WhiteListFile(
77 "whitelist_file",
78 cl::desc("A file containing regexes of symbol names that are not expected "
79 "to be updated when changing namespaces around them."),
80 cl::init(""), cl::cat(ChangeNamespaceCategory));
81
82llvm::ErrorOr<std::vector<std::string>> GetWhiteListedSymbolPatterns() {
83 llvm::SmallVector<StringRef, 8> Lines;
84 if (!WhiteListFile.empty()) {
85 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
86 llvm::MemoryBuffer::getFile(WhiteListFile);
87 if (!File)
88 return File.getError();
89 llvm::StringRef Content = File.get()->getBuffer();
90 Content.split(Lines, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
91 }
92 return std::vector<std::string>(Lines.begin(), Lines.end());
93}
94
Eric Liu495b2112016-09-19 17:40:32 +000095} // anonymous namespace
96
97int main(int argc, const char **argv) {
Eric Liu3db05212016-10-13 18:56:14 +000098 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
Eric Liu495b2112016-09-19 17:40:32 +000099 tooling::CommonOptionsParser OptionsParser(argc, argv,
100 ChangeNamespaceCategory);
101 const auto &Files = OptionsParser.getSourcePathList();
102 tooling::RefactoringTool Tool(OptionsParser.getCompilations(), Files);
Eric Liu7fccc992017-02-24 11:54:45 +0000103 llvm::ErrorOr<std::vector<std::string>> WhiteListPatterns =
104 GetWhiteListedSymbolPatterns();
105 if (!WhiteListPatterns) {
106 llvm::errs() << "Failed to open whitelist file " << WhiteListFile << ". "
107 << WhiteListPatterns.getError().message() << "\n";
108 return 1;
109 }
Eric Liu495b2112016-09-19 17:40:32 +0000110 change_namespace::ChangeNamespaceTool NamespaceTool(
Eric Liu7fccc992017-02-24 11:54:45 +0000111 OldNamespace, NewNamespace, FilePattern, *WhiteListPatterns,
112 &Tool.getReplacements(), Style);
Eric Liu495b2112016-09-19 17:40:32 +0000113 ast_matchers::MatchFinder Finder;
114 NamespaceTool.registerMatchers(&Finder);
115 std::unique_ptr<tooling::FrontendActionFactory> Factory =
116 tooling::newFrontendActionFactory(&Finder);
117
118 if (int Result = Tool.run(Factory.get()))
119 return Result;
120 LangOptions DefaultLangOptions;
121 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
122 clang::TextDiagnosticPrinter DiagnosticPrinter(errs(), &*DiagOpts);
123 DiagnosticsEngine Diagnostics(
124 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
125 &DiagnosticPrinter, false);
126 auto &FileMgr = Tool.getFiles();
127 SourceManager Sources(Diagnostics, FileMgr);
128 Rewriter Rewrite(Sources, DefaultLangOptions);
129
130 if (!formatAndApplyAllReplacements(Tool.getReplacements(), Rewrite, Style)) {
131 llvm::errs() << "Failed applying all replacements.\n";
132 return 1;
133 }
134 if (Inplace)
135 return Rewrite.overwriteChangedFiles();
136
Eric Liua13c4192017-02-13 17:24:14 +0000137 std::set<llvm::StringRef> ChangedFiles;
138 for (const auto &it : Tool.getReplacements())
139 ChangedFiles.insert(it.first);
140
141 if (DumpYAML) {
142 auto WriteToYAML = [&](llvm::raw_ostream &OS) {
143 OS << "[\n";
144 for (auto I = ChangedFiles.begin(), E = ChangedFiles.end(); I != E; ++I) {
145 OS << " {\n";
146 OS << " \"FilePath\": \"" << *I << "\",\n";
147 const auto *Entry = FileMgr.getFile(*I);
148 auto ID = Sources.getOrCreateFileID(Entry, SrcMgr::C_User);
149 std::string Content;
150 llvm::raw_string_ostream ContentStream(Content);
151 Rewrite.getEditBuffer(ID).write(ContentStream);
152 OS << " \"SourceText\": \""
153 << llvm::yaml::escape(ContentStream.str()) << "\"\n";
154 OS << " }";
155 if (I != std::prev(E))
156 OS << ",\n";
157 }
158 OS << "\n]\n";
159 };
160 WriteToYAML(llvm::outs());
161 return 0;
162 }
163
164 for (const auto &File : ChangedFiles) {
Eric Liu495b2112016-09-19 17:40:32 +0000165 const auto *Entry = FileMgr.getFile(File);
166
167 auto ID = Sources.getOrCreateFileID(Entry, SrcMgr::C_User);
Eric Liu495b2112016-09-19 17:40:32 +0000168 outs() << "============== " << File << " ==============\n";
169 Rewrite.getEditBuffer(ID).write(llvm::outs());
170 outs() << "\n============================================\n";
171 }
Eric Liua13c4192017-02-13 17:24:14 +0000172
Eric Liu495b2112016-09-19 17:40:32 +0000173 return 0;
174}