blob: 0877519478cbc9172783efb6a567ded93b58a6d6 [file] [log] [blame]
Eric Liu495b2112016-09-19 17:40:32 +00001//===-- ChangeNamespace.cpp - Change namespace implementation -------------===//
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#include "ChangeNamespace.h"
10#include "clang/Format/Format.h"
11#include "clang/Lex/Lexer.h"
Eric Liuff51f012016-11-16 16:54:53 +000012#include "llvm/Support/ErrorHandling.h"
Eric Liu495b2112016-09-19 17:40:32 +000013
14using namespace clang::ast_matchers;
15
16namespace clang {
17namespace change_namespace {
18
19namespace {
20
21inline std::string
22joinNamespaces(const llvm::SmallVectorImpl<StringRef> &Namespaces) {
23 if (Namespaces.empty())
24 return "";
25 std::string Result = Namespaces.front();
26 for (auto I = Namespaces.begin() + 1, E = Namespaces.end(); I != E; ++I)
27 Result += ("::" + *I).str();
28 return Result;
29}
30
31SourceLocation startLocationForType(TypeLoc TLoc) {
32 // For elaborated types (e.g. `struct a::A`) we want the portion after the
33 // `struct` but including the namespace qualifier, `a::`.
34 if (TLoc.getTypeLocClass() == TypeLoc::Elaborated) {
35 NestedNameSpecifierLoc NestedNameSpecifier =
36 TLoc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
37 if (NestedNameSpecifier.getNestedNameSpecifier())
38 return NestedNameSpecifier.getBeginLoc();
39 TLoc = TLoc.getNextTypeLoc();
40 }
41 return TLoc.getLocStart();
42}
43
Eric Liuc265b022016-12-01 17:25:55 +000044SourceLocation endLocationForType(TypeLoc TLoc) {
Eric Liu495b2112016-09-19 17:40:32 +000045 // Dig past any namespace or keyword qualifications.
46 while (TLoc.getTypeLocClass() == TypeLoc::Elaborated ||
47 TLoc.getTypeLocClass() == TypeLoc::Qualified)
48 TLoc = TLoc.getNextTypeLoc();
49
50 // The location for template specializations (e.g. Foo<int>) includes the
51 // templated types in its location range. We want to restrict this to just
52 // before the `<` character.
53 if (TLoc.getTypeLocClass() == TypeLoc::TemplateSpecialization)
54 return TLoc.castAs<TemplateSpecializationTypeLoc>()
55 .getLAngleLoc()
56 .getLocWithOffset(-1);
57 return TLoc.getEndLoc();
58}
59
60// Returns the containing namespace of `InnerNs` by skipping `PartialNsName`.
Eric Liu6aa94162016-11-10 18:29:01 +000061// If the `InnerNs` does not have `PartialNsName` as suffix, or `PartialNsName`
62// is empty, nullptr is returned.
Eric Liu495b2112016-09-19 17:40:32 +000063// For example, if `InnerNs` is "a::b::c" and `PartialNsName` is "b::c", then
64// the NamespaceDecl of namespace "a" will be returned.
65const NamespaceDecl *getOuterNamespace(const NamespaceDecl *InnerNs,
66 llvm::StringRef PartialNsName) {
Eric Liu6aa94162016-11-10 18:29:01 +000067 if (!InnerNs || PartialNsName.empty())
68 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +000069 const auto *CurrentContext = llvm::cast<DeclContext>(InnerNs);
70 const auto *CurrentNs = InnerNs;
71 llvm::SmallVector<llvm::StringRef, 4> PartialNsNameSplitted;
Eric Liu6aa94162016-11-10 18:29:01 +000072 PartialNsName.split(PartialNsNameSplitted, "::", /*MaxSplit=*/-1,
73 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32 +000074 while (!PartialNsNameSplitted.empty()) {
75 // Get the inner-most namespace in CurrentContext.
76 while (CurrentContext && !llvm::isa<NamespaceDecl>(CurrentContext))
77 CurrentContext = CurrentContext->getParent();
78 if (!CurrentContext)
79 return nullptr;
80 CurrentNs = llvm::cast<NamespaceDecl>(CurrentContext);
81 if (PartialNsNameSplitted.back() != CurrentNs->getNameAsString())
82 return nullptr;
83 PartialNsNameSplitted.pop_back();
84 CurrentContext = CurrentContext->getParent();
85 }
86 return CurrentNs;
87}
88
Eric Liu73f49fd2016-10-12 12:34:18 +000089static std::unique_ptr<Lexer>
90getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM,
91 const LangOptions &LangOpts) {
Eric Liu495b2112016-09-19 17:40:32 +000092 if (Loc.isMacroID() &&
93 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eric Liu73f49fd2016-10-12 12:34:18 +000094 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +000095 // Break down the source location.
96 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
97 // Try to load the file buffer.
98 bool InvalidTemp = false;
99 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
100 if (InvalidTemp)
Eric Liu73f49fd2016-10-12 12:34:18 +0000101 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +0000102
103 const char *TokBegin = File.data() + LocInfo.second;
104 // Lex from the start of the given location.
Eric Liu73f49fd2016-10-12 12:34:18 +0000105 return llvm::make_unique<Lexer>(SM.getLocForStartOfFile(LocInfo.first),
106 LangOpts, File.begin(), TokBegin, File.end());
107}
Eric Liu495b2112016-09-19 17:40:32 +0000108
Eric Liu73f49fd2016-10-12 12:34:18 +0000109// FIXME: get rid of this helper function if this is supported in clang-refactor
110// library.
111static SourceLocation getStartOfNextLine(SourceLocation Loc,
112 const SourceManager &SM,
113 const LangOptions &LangOpts) {
114 std::unique_ptr<Lexer> Lex = getLexerStartingFromLoc(Loc, SM, LangOpts);
115 if (!Lex.get())
116 return SourceLocation();
Eric Liu495b2112016-09-19 17:40:32 +0000117 llvm::SmallVector<char, 16> Line;
118 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
Eric Liu73f49fd2016-10-12 12:34:18 +0000119 Lex->setParsingPreprocessorDirective(true);
120 Lex->ReadToEndOfLine(&Line);
Haojian Wuef8a6dc2016-10-04 10:35:53 +0000121 auto End = Loc.getLocWithOffset(Line.size());
Eric Liu73f49fd2016-10-12 12:34:18 +0000122 return SM.getLocForEndOfFile(SM.getDecomposedLoc(Loc).first) == End
123 ? End
124 : End.getLocWithOffset(1);
Eric Liu495b2112016-09-19 17:40:32 +0000125}
126
127// Returns `R` with new range that refers to code after `Replaces` being
128// applied.
129tooling::Replacement
130getReplacementInChangedCode(const tooling::Replacements &Replaces,
131 const tooling::Replacement &R) {
132 unsigned NewStart = Replaces.getShiftedCodePosition(R.getOffset());
133 unsigned NewEnd =
134 Replaces.getShiftedCodePosition(R.getOffset() + R.getLength());
135 return tooling::Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
136 R.getReplacementText());
137}
138
139// Adds a replacement `R` into `Replaces` or merges it into `Replaces` by
140// applying all existing Replaces first if there is conflict.
141void addOrMergeReplacement(const tooling::Replacement &R,
142 tooling::Replacements *Replaces) {
143 auto Err = Replaces->add(R);
144 if (Err) {
145 llvm::consumeError(std::move(Err));
146 auto Replace = getReplacementInChangedCode(*Replaces, R);
147 *Replaces = Replaces->merge(tooling::Replacements(Replace));
148 }
149}
150
151tooling::Replacement createReplacement(SourceLocation Start, SourceLocation End,
152 llvm::StringRef ReplacementText,
153 const SourceManager &SM) {
154 if (!Start.isValid() || !End.isValid()) {
155 llvm::errs() << "start or end location were invalid\n";
156 return tooling::Replacement();
157 }
158 if (SM.getDecomposedLoc(Start).first != SM.getDecomposedLoc(End).first) {
159 llvm::errs()
160 << "start or end location were in different macro expansions\n";
161 return tooling::Replacement();
162 }
163 Start = SM.getSpellingLoc(Start);
164 End = SM.getSpellingLoc(End);
165 if (SM.getFileID(Start) != SM.getFileID(End)) {
166 llvm::errs() << "start or end location were in different files\n";
167 return tooling::Replacement();
168 }
169 return tooling::Replacement(
170 SM, CharSourceRange::getTokenRange(SM.getSpellingLoc(Start),
171 SM.getSpellingLoc(End)),
172 ReplacementText);
173}
174
Eric Liu4fe99e12016-12-14 17:01:52 +0000175void addReplacementOrDie(
176 SourceLocation Start, SourceLocation End, llvm::StringRef ReplacementText,
177 const SourceManager &SM,
178 std::map<std::string, tooling::Replacements> *FileToReplacements) {
179 const auto R = createReplacement(Start, End, ReplacementText, SM);
180 auto Err = (*FileToReplacements)[R.getFilePath()].add(R);
181 if (Err)
182 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
183}
184
Eric Liu495b2112016-09-19 17:40:32 +0000185tooling::Replacement createInsertion(SourceLocation Loc,
186 llvm::StringRef InsertText,
187 const SourceManager &SM) {
188 if (Loc.isInvalid()) {
189 llvm::errs() << "insert Location is invalid.\n";
190 return tooling::Replacement();
191 }
192 Loc = SM.getSpellingLoc(Loc);
193 return tooling::Replacement(SM, Loc, 0, InsertText);
194}
195
196// Returns the shortest qualified name for declaration `DeclName` in the
197// namespace `NsName`. For example, if `DeclName` is "a::b::X" and `NsName`
198// is "a::c::d", then "b::X" will be returned.
Eric Liu447164d2016-10-05 15:52:39 +0000199// \param DeclName A fully qualified name, "::a::b::X" or "a::b::X".
200// \param NsName A fully qualified name, "::a::b" or "a::b". Global namespace
201// will have empty name.
Eric Liu495b2112016-09-19 17:40:32 +0000202std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
203 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39 +0000204 DeclName = DeclName.ltrim(':');
205 NsName = NsName.ltrim(':');
Eric Liu447164d2016-10-05 15:52:39 +0000206 if (DeclName.find(':') == llvm::StringRef::npos)
Eric Liub9bf1b52016-11-08 22:44:17 +0000207 return DeclName;
Eric Liu447164d2016-10-05 15:52:39 +0000208
209 while (!DeclName.consume_front((NsName + "::").str())) {
Eric Liu495b2112016-09-19 17:40:32 +0000210 const auto Pos = NsName.find_last_of(':');
211 if (Pos == llvm::StringRef::npos)
212 return DeclName;
Eric Liu447164d2016-10-05 15:52:39 +0000213 assert(Pos > 0);
214 NsName = NsName.substr(0, Pos - 1);
Eric Liu495b2112016-09-19 17:40:32 +0000215 }
216 return DeclName;
217}
218
219std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) {
220 if (Code.back() != '\n')
221 Code += "\n";
222 llvm::SmallVector<StringRef, 4> NsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04 +0000223 NestedNs.split(NsSplitted, "::", /*MaxSplit=*/-1,
224 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32 +0000225 while (!NsSplitted.empty()) {
226 // FIXME: consider code style for comments.
227 Code = ("namespace " + NsSplitted.back() + " {\n" + Code +
228 "} // namespace " + NsSplitted.back() + "\n")
229 .str();
230 NsSplitted.pop_back();
231 }
232 return Code;
233}
234
Eric Liub9bf1b52016-11-08 22:44:17 +0000235// Returns true if \p D is a nested DeclContext in \p Context
236bool isNestedDeclContext(const DeclContext *D, const DeclContext *Context) {
237 while (D) {
238 if (D == Context)
239 return true;
240 D = D->getParent();
241 }
242 return false;
243}
244
245// Returns true if \p D is visible at \p Loc with DeclContext \p DeclCtx.
246bool isDeclVisibleAtLocation(const SourceManager &SM, const Decl *D,
247 const DeclContext *DeclCtx, SourceLocation Loc) {
248 SourceLocation DeclLoc = SM.getSpellingLoc(D->getLocation());
249 Loc = SM.getSpellingLoc(Loc);
250 return SM.isBeforeInTranslationUnit(DeclLoc, Loc) &&
251 (SM.getFileID(DeclLoc) == SM.getFileID(Loc) &&
252 isNestedDeclContext(DeclCtx, D->getDeclContext()));
253}
254
Eric Liu495b2112016-09-19 17:40:32 +0000255} // anonymous namespace
256
257ChangeNamespaceTool::ChangeNamespaceTool(
258 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
259 std::map<std::string, tooling::Replacements> *FileToReplacements,
260 llvm::StringRef FallbackStyle)
261 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
262 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
Eric Liuc265b022016-12-01 17:25:55 +0000263 FilePattern(FilePattern), FilePatternRE(FilePattern) {
Eric Liu495b2112016-09-19 17:40:32 +0000264 FileToReplacements->clear();
265 llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted;
266 llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted;
267 llvm::StringRef(OldNamespace).split(OldNsSplitted, "::");
268 llvm::StringRef(NewNamespace).split(NewNsSplitted, "::");
269 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
270 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
271 OldNsSplitted.front() == NewNsSplitted.front()) {
272 OldNsSplitted.erase(OldNsSplitted.begin());
273 NewNsSplitted.erase(NewNsSplitted.begin());
274 }
275 DiffOldNamespace = joinNamespaces(OldNsSplitted);
276 DiffNewNamespace = joinNamespaces(NewNsSplitted);
277}
278
Eric Liu495b2112016-09-19 17:40:32 +0000279void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32 +0000280 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17 +0000281 // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the
282 // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will
283 // be "a::b". Declarations in this namespace will not be visible in the new
284 // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-".
285 llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04 +0000286 llvm::StringRef(DiffOldNamespace)
287 .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1,
288 /*KeepEmpty=*/false);
Eric Liub9bf1b52016-11-08 22:44:17 +0000289 std::string Prefix = "-";
290 if (!DiffOldNsSplitted.empty())
291 Prefix = (StringRef(FullOldNs).drop_back(DiffOldNamespace.size()) +
292 DiffOldNsSplitted.front())
293 .str();
294 auto IsInMovedNs =
295 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
296 isExpansionInFileMatching(FilePattern));
297 auto IsVisibleInNewNs = anyOf(
298 IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Prefix)))));
299 // Match using declarations.
300 Finder->addMatcher(
301 usingDecl(isExpansionInFileMatching(FilePattern), IsVisibleInNewNs)
302 .bind("using"),
303 this);
304 // Match using namespace declarations.
305 Finder->addMatcher(usingDirectiveDecl(isExpansionInFileMatching(FilePattern),
306 IsVisibleInNewNs)
307 .bind("using_namespace"),
308 this);
309
310 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32 +0000311 Finder->addMatcher(
312 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
313 .bind("old_ns"),
314 this);
315
Eric Liu41552d62016-12-07 14:20:52 +0000316 // Match class forward-declarations in the old namespace.
317 // Note that forward-declarations in classes are not matched.
318 Finder->addMatcher(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())),
319 IsInMovedNs, hasParent(namespaceDecl()))
320 .bind("class_fwd_decl"),
321 this);
322
323 // Match template class forward-declarations in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000324 Finder->addMatcher(
Eric Liu41552d62016-12-07 14:20:52 +0000325 classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))),
326 IsInMovedNs, hasParent(namespaceDecl()))
327 .bind("template_class_fwd_decl"),
Eric Liu495b2112016-09-19 17:40:32 +0000328 this);
329
330 // Match references to types that are not defined in the old namespace.
331 // Forward-declarations in the old namespace are also matched since they will
332 // be moved back to the old namespace.
333 auto DeclMatcher = namedDecl(
334 hasAncestor(namespaceDecl()),
335 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48 +0000336 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32 +0000337 hasAncestor(cxxRecordDecl()),
338 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48 +0000339
Eric Liu8685c762016-12-07 17:04:07 +0000340 // Using shadow declarations in classes always refers to base class, which
341 // does not need to be qualified since it can be inferred from inheritance.
342 // Note that this does not match using alias declarations.
343 auto UsingShadowDeclInClass =
344 usingDecl(hasAnyUsingShadowDecl(decl()), hasParent(cxxRecordDecl()));
345
Eric Liu495b2112016-09-19 17:40:32 +0000346 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29 +0000347 // TypeLoc and template specialization arguments (which are not outermost)
348 // that are directly linked to types matching `DeclMatcher`. Nested name
349 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32 +0000350 Finder->addMatcher(
351 typeLoc(IsInMovedNs,
352 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29 +0000353 unless(anyOf(hasParent(typeLoc(loc(qualType(
354 allOf(hasDeclaration(DeclMatcher),
355 unless(templateSpecializationType())))))),
Eric Liu8685c762016-12-07 17:04:07 +0000356 hasParent(nestedNameSpecifierLoc()),
357 hasAncestor(isImplicit()),
358 hasAncestor(UsingShadowDeclInClass))),
Eric Liu495b2112016-09-19 17:40:32 +0000359 hasAncestor(decl().bind("dc")))
360 .bind("type"),
361 this);
Eric Liu912d0392016-09-27 12:54:48 +0000362
Eric Liu68765a82016-09-21 15:06:12 +0000363 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
364 // special case it.
Eric Liu8685c762016-12-07 17:04:07 +0000365 // Since using declarations inside classes must have the base class in the
366 // nested name specifier, we leave it to the nested name specifier matcher.
367 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()),
368 unless(UsingShadowDeclInClass))
Eric Liub9bf1b52016-11-08 22:44:17 +0000369 .bind("using_with_shadow"),
370 this);
Eric Liu912d0392016-09-27 12:54:48 +0000371
Eric Liuff51f012016-11-16 16:54:53 +0000372 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
373 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
374 // "A::A" would have already been fixed.
Eric Liu8685c762016-12-07 17:04:07 +0000375 Finder->addMatcher(
376 nestedNameSpecifierLoc(
377 hasAncestor(decl(IsInMovedNs).bind("dc")),
378 loc(nestedNameSpecifier(
379 specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
380 unless(anyOf(hasAncestor(isImplicit()),
381 hasAncestor(UsingShadowDeclInClass),
382 hasAncestor(typeLoc(loc(qualType(hasDeclaration(
383 decl(equalsBoundNode("from_decl"))))))))))
384 .bind("nested_specifier_loc"),
385 this);
Eric Liu12068d82016-09-22 11:54:00 +0000386
Eric Liuff51f012016-11-16 16:54:53 +0000387 // Matches base class initializers in constructors. TypeLocs of base class
388 // initializers do not need to be fixed. For example,
389 // class X : public a::b::Y {
390 // public:
391 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
392 // };
393 Finder->addMatcher(
394 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
395
Eric Liu12068d82016-09-22 11:54:00 +0000396 // Handle function.
Eric Liu912d0392016-09-27 12:54:48 +0000397 // Only handle functions that are defined in a namespace excluding member
398 // function, static methods (qualified by nested specifier), and functions
399 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00 +0000400 // Note that the matcher does not exclude calls to out-of-line static method
401 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48 +0000402 auto FuncMatcher =
403 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
404 hasAncestor(namespaceDecl(isAnonymous())),
405 hasAncestor(cxxRecordDecl()))),
406 hasParent(namespaceDecl()));
Eric Liuda22b3c2016-11-29 14:15:14 +0000407 Finder->addMatcher(decl(forEachDescendant(expr(anyOf(
408 callExpr(callee(FuncMatcher)).bind("call"),
409 declRefExpr(to(FuncMatcher.bind("func_decl")))
410 .bind("func_ref")))),
411 IsInMovedNs, unless(isImplicit()))
412 .bind("dc"),
413 this);
Eric Liu159f0132016-09-30 04:32:39 +0000414
415 auto GlobalVarMatcher = varDecl(
416 hasGlobalStorage(), hasParent(namespaceDecl()),
417 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
418 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
419 to(GlobalVarMatcher.bind("var_decl")))
420 .bind("var_ref"),
421 this);
Eric Liu495b2112016-09-19 17:40:32 +0000422}
423
424void ChangeNamespaceTool::run(
425 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17 +0000426 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
427 UsingDecls.insert(Using);
428 } else if (const auto *UsingNamespace =
429 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
430 "using_namespace")) {
431 UsingNamespaceDecls.insert(UsingNamespace);
432 } else if (const auto *NsDecl =
433 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32 +0000434 moveOldNamespace(Result, NsDecl);
435 } else if (const auto *FwdDecl =
Eric Liu41552d62016-12-07 14:20:52 +0000436 Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) {
437 moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl));
438 } else if (const auto *TemplateFwdDecl =
439 Result.Nodes.getNodeAs<ClassTemplateDecl>(
440 "template_class_fwd_decl")) {
441 moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl));
Eric Liub9bf1b52016-11-08 22:44:17 +0000442 } else if (const auto *UsingWithShadow =
443 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
444 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12 +0000445 } else if (const auto *Specifier =
446 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
447 "nested_specifier_loc")) {
448 SourceLocation Start = Specifier->getBeginLoc();
Eric Liuc265b022016-12-01 17:25:55 +0000449 SourceLocation End = endLocationForType(Specifier->getTypeLoc());
Eric Liu68765a82016-09-21 15:06:12 +0000450 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53 +0000451 } else if (const auto *BaseInitializer =
452 Result.Nodes.getNodeAs<CXXCtorInitializer>(
453 "base_initializer")) {
454 BaseCtorInitializerTypeLocs.push_back(
455 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00 +0000456 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu26cf68a2016-12-15 10:42:35 +0000457 // This avoids fixing types with record types as qualifier, which is not
458 // filtered by matchers in some cases, e.g. the type is templated. We should
459 // handle the record type qualifier instead.
Eric Liu0c0aea02016-12-15 13:02:41 +0000460 TypeLoc Loc = *TLoc;
461 while (Loc.getTypeLocClass() == TypeLoc::Qualified)
462 Loc = Loc.getNextTypeLoc();
463 if (Loc.getTypeLocClass() == TypeLoc::Elaborated) {
Eric Liu26cf68a2016-12-15 10:42:35 +0000464 NestedNameSpecifierLoc NestedNameSpecifier =
Eric Liu0c0aea02016-12-15 13:02:41 +0000465 Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
Eric Liu26cf68a2016-12-15 10:42:35 +0000466 const Type *SpecifierType =
467 NestedNameSpecifier.getNestedNameSpecifier()->getAsType();
468 if (SpecifierType && SpecifierType->isRecordType())
469 return;
470 }
Eric Liu0c0aea02016-12-15 13:02:41 +0000471 fixTypeLoc(Result, startLocationForType(Loc), endLocationForType(Loc), Loc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000472 } else if (const auto *VarRef =
473 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39 +0000474 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
475 assert(Var);
476 if (Var->getCanonicalDecl()->isStaticDataMember())
477 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000478 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu159f0132016-09-30 04:32:39 +0000479 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000480 fixDeclRefExpr(Result, Context->getDeclContext(),
481 llvm::cast<NamedDecl>(Var), VarRef);
482 } else if (const auto *FuncRef =
483 Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) {
Eric Liue3f35e42016-12-20 14:39:04 +0000484 // If this reference has been processed as a function call, we do not
485 // process it again.
486 if (ProcessedFuncRefs.count(FuncRef))
487 return;
488 ProcessedFuncRefs.insert(FuncRef);
Eric Liuda22b3c2016-11-29 14:15:14 +0000489 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
490 assert(Func);
491 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
492 assert(Context && "Empty decl context.");
493 fixDeclRefExpr(Result, Context->getDeclContext(),
494 llvm::cast<NamedDecl>(Func), FuncRef);
Eric Liu12068d82016-09-22 11:54:00 +0000495 } else {
Eric Liuda22b3c2016-11-29 14:15:14 +0000496 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000497 assert(Call != nullptr && "Expecting callback for CallExpr.");
Eric Liue3f35e42016-12-20 14:39:04 +0000498 const auto *CalleeFuncRef =
499 llvm::cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit());
500 ProcessedFuncRefs.insert(CalleeFuncRef);
Eric Liuda22b3c2016-11-29 14:15:14 +0000501 const FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00 +0000502 assert(Func != nullptr);
Eric Liue3f35e42016-12-20 14:39:04 +0000503 // FIXME: ignore overloaded operators. This would miss cases where operators
504 // are called by qualified names (i.e. "ns::operator <"). Ignore such
505 // cases for now.
506 if (Func->isOverloadedOperator())
507 return;
Eric Liu12068d82016-09-22 11:54:00 +0000508 // Ignore out-of-line static methods since they will be handled by nested
509 // name specifiers.
510 if (Func->getCanonicalDecl()->getStorageClass() ==
Eric Liuda22b3c2016-11-29 14:15:14 +0000511 StorageClass::SC_Static &&
Eric Liu12068d82016-09-22 11:54:00 +0000512 Func->isOutOfLine())
513 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000514 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu12068d82016-09-22 11:54:00 +0000515 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000516 SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17 +0000517 replaceQualifiedSymbolInDeclContext(
518 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34 +0000519 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32 +0000520 }
521}
522
Eric Liu73f49fd2016-10-12 12:34:18 +0000523static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
524 const SourceManager &SM,
525 const LangOptions &LangOpts) {
526 std::unique_ptr<Lexer> Lex =
527 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
528 assert(Lex.get() &&
529 "Failed to create lexer from the beginning of namespace.");
530 if (!Lex.get())
531 return SourceLocation();
532 Token Tok;
533 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
534 }
535 return Tok.isNot(tok::TokenKind::l_brace)
536 ? SourceLocation()
537 : Tok.getEndLoc().getLocWithOffset(1);
538}
539
Eric Liu495b2112016-09-19 17:40:32 +0000540// Stores information about a moved namespace in `MoveNamespaces` and leaves
541// the actual movement to `onEndOfTranslationUnit()`.
542void ChangeNamespaceTool::moveOldNamespace(
543 const ast_matchers::MatchFinder::MatchResult &Result,
544 const NamespaceDecl *NsDecl) {
545 // If the namespace is empty, do nothing.
546 if (Decl::castToDeclContext(NsDecl)->decls_empty())
547 return;
548
549 // Get the range of the code in the old namespace.
Eric Liu73f49fd2016-10-12 12:34:18 +0000550 SourceLocation Start = getLocAfterNamespaceLBrace(
551 NsDecl, *Result.SourceManager, Result.Context->getLangOpts());
552 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32 +0000553 SourceLocation End = NsDecl->getRBraceLoc().getLocWithOffset(-1);
554 // Create a replacement that deletes the code in the old namespace merely for
555 // retrieving offset and length from it.
556 const auto R = createReplacement(Start, End, "", *Result.SourceManager);
557 MoveNamespace MoveNs;
558 MoveNs.Offset = R.getOffset();
559 MoveNs.Length = R.getLength();
560
561 // Insert the new namespace after `DiffOldNamespace`. For example, if
562 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
563 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
564 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
565 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01 +0000566 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
567 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000568 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01 +0000569 SourceLocation InsertionLoc = Start;
570 if (OuterNs) {
571 SourceLocation LocAfterNs =
572 getStartOfNextLine(OuterNs->getRBraceLoc(), *Result.SourceManager,
573 Result.Context->getLangOpts());
574 assert(LocAfterNs.isValid() &&
575 "Failed to get location after DiffOldNamespace");
576 InsertionLoc = LocAfterNs;
577 }
Eric Liu495b2112016-09-19 17:40:32 +0000578 MoveNs.InsertionOffset = Result.SourceManager->getFileOffset(
Eric Liu6aa94162016-11-10 18:29:01 +0000579 Result.SourceManager->getSpellingLoc(InsertionLoc));
Eric Liucc83c662016-09-19 17:58:59 +0000580 MoveNs.FID = Result.SourceManager->getFileID(Start);
581 MoveNs.SourceMgr = Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32 +0000582 MoveNamespaces[R.getFilePath()].push_back(MoveNs);
583}
584
585// Removes a class forward declaration from the code in the moved namespace and
586// creates an `InsertForwardDeclaration` to insert the forward declaration back
587// into the old namespace after moving code from the old namespace to the new
588// namespace.
589// For example, changing "a" to "x":
590// Old code:
591// namespace a {
592// class FWD;
593// class A { FWD *fwd; }
594// } // a
595// New code:
596// namespace a {
597// class FWD;
598// } // a
599// namespace x {
600// class A { a::FWD *fwd; }
601// } // x
602void ChangeNamespaceTool::moveClassForwardDeclaration(
603 const ast_matchers::MatchFinder::MatchResult &Result,
Eric Liu41552d62016-12-07 14:20:52 +0000604 const NamedDecl *FwdDecl) {
Eric Liu495b2112016-09-19 17:40:32 +0000605 SourceLocation Start = FwdDecl->getLocStart();
606 SourceLocation End = FwdDecl->getLocEnd();
607 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
608 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
609 /*SkipTrailingWhitespaceAndNewLine=*/true);
610 if (AfterSemi.isValid())
611 End = AfterSemi.getLocWithOffset(-1);
612 // Delete the forward declaration from the code to be moved.
Eric Liu4fe99e12016-12-14 17:01:52 +0000613 addReplacementOrDie(Start, End, "", *Result.SourceManager,
614 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32 +0000615 llvm::StringRef Code = Lexer::getSourceText(
616 CharSourceRange::getTokenRange(
617 Result.SourceManager->getSpellingLoc(Start),
618 Result.SourceManager->getSpellingLoc(End)),
619 *Result.SourceManager, Result.Context->getLangOpts());
620 // Insert the forward declaration back into the old namespace after moving the
621 // code from old namespace to new namespace.
622 // Insertion information is stored in `InsertFwdDecls` and actual
623 // insertion will be performed in `onEndOfTranslationUnit`.
624 // Get the (old) namespace that contains the forward declaration.
625 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
626 // The namespace contains the forward declaration, so it must not be empty.
627 assert(!NsDecl->decls_empty());
628 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
629 Code, *Result.SourceManager);
630 InsertForwardDeclaration InsertFwd;
631 InsertFwd.InsertionOffset = Insertion.getOffset();
632 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
633 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
634}
635
Eric Liub9bf1b52016-11-08 22:44:17 +0000636// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
637// FromDecl with the shortest qualified name possible when the reference is in
638// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32 +0000639void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17 +0000640 const ast_matchers::MatchFinder::MatchResult &Result,
641 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
642 const NamedDecl *FromDecl) {
643 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu4fe99e12016-12-14 17:01:52 +0000644 if (llvm::isa<TranslationUnitDecl>(NsDeclContext)) {
645 // This should not happen in usual unless the TypeLoc is in function type
646 // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of
647 // `T` will be the translation unit. We simply use fully-qualified name
648 // here.
649 // Note that `FromDecl` must not be defined in the old namespace (according
650 // to `DeclMatcher`), so its fully-qualified name will not change after
651 // changing the namespace.
652 addReplacementOrDie(Start, End, FromDecl->getQualifiedNameAsString(),
653 *Result.SourceManager, &FileToReplacements);
654 return;
655 }
Eric Liu231c6552016-11-10 18:15:34 +0000656 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32 +0000657 // Calculate the name of the `NsDecl` after it is moved to new namespace.
658 std::string OldNs = NsDecl->getQualifiedNameAsString();
659 llvm::StringRef Postfix = OldNs;
660 bool Consumed = Postfix.consume_front(OldNamespace);
661 assert(Consumed && "Expect OldNS to start with OldNamespace.");
662 (void)Consumed;
663 const std::string NewNs = (NewNamespace + Postfix).str();
664
665 llvm::StringRef NestedName = Lexer::getSourceText(
666 CharSourceRange::getTokenRange(
667 Result.SourceManager->getSpellingLoc(Start),
668 Result.SourceManager->getSpellingLoc(End)),
669 *Result.SourceManager, Result.Context->getLangOpts());
670 // If the symbol is already fully qualified, no change needs to be make.
671 if (NestedName.startswith("::"))
672 return;
Eric Liub9bf1b52016-11-08 22:44:17 +0000673 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu495b2112016-09-19 17:40:32 +0000674 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17 +0000675 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
676 // Checks if there is any using namespace declarations that can shorten the
677 // qualified name.
678 for (const auto *UsingNamespace : UsingNamespaceDecls) {
679 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
680 Start))
681 continue;
682 StringRef FromDeclNameRef = FromDeclName;
683 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
684 ->getQualifiedNameAsString())) {
685 FromDeclNameRef = FromDeclNameRef.drop_front(2);
686 if (FromDeclNameRef.size() < ReplaceName.size())
687 ReplaceName = FromDeclNameRef;
688 }
689 }
690 // Checks if there is any using shadow declarations that can shorten the
691 // qualified name.
692 bool Matched = false;
693 for (const UsingDecl *Using : UsingDecls) {
694 if (Matched)
695 break;
696 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
697 for (const auto *UsingShadow : Using->shadows()) {
698 const auto *TargetDecl = UsingShadow->getTargetDecl();
699 if (TargetDecl == FromDecl) {
700 ReplaceName = FromDecl->getNameAsString();
701 Matched = true;
702 break;
703 }
704 }
705 }
706 }
Eric Liu495b2112016-09-19 17:40:32 +0000707 // If the new nested name in the new namespace is the same as it was in the
708 // old namespace, we don't create replacement.
709 if (NestedName == ReplaceName)
710 return;
Eric Liu97f87ad2016-12-07 20:08:02 +0000711 // If the reference need to be fully-qualified, add a leading "::" unless
712 // NewNamespace is the global namespace.
713 if (ReplaceName == FromDeclName && !NewNamespace.empty())
714 ReplaceName = "::" + ReplaceName;
Eric Liu4fe99e12016-12-14 17:01:52 +0000715 addReplacementOrDie(Start, End, ReplaceName, *Result.SourceManager,
716 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32 +0000717}
718
719// Replace the [Start, End] of `Type` with the shortest qualified name when the
720// `Type` is in `NewNamespace`.
721void ChangeNamespaceTool::fixTypeLoc(
722 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
723 SourceLocation End, TypeLoc Type) {
724 // FIXME: do not rename template parameter.
725 if (Start.isInvalid() || End.isInvalid())
726 return;
Eric Liuff51f012016-11-16 16:54:53 +0000727 // Types of CXXCtorInitializers do not need to be fixed.
728 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
729 return;
Eric Liu495b2112016-09-19 17:40:32 +0000730 // The declaration which this TypeLoc refers to.
731 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
732 // `hasDeclaration` gives underlying declaration, but if the type is
733 // a typedef type, we need to use the typedef type instead.
Eric Liu26cf68a2016-12-15 10:42:35 +0000734 auto IsInMovedNs = [&](const NamedDecl *D) {
735 if (!llvm::StringRef(D->getQualifiedNameAsString())
736 .startswith(OldNamespace + "::"))
737 return false;
738 auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getLocStart());
739 if (ExpansionLoc.isInvalid())
740 return false;
741 llvm::StringRef Filename = Result.SourceManager->getFilename(ExpansionLoc);
742 return FilePatternRE.match(Filename);
743 };
744 // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if
745 // `Type` is an alias type, we make `FromDecl` the type alias declaration.
746 // Also, don't fix the \p Type if it refers to a type alias decl in the moved
747 // namespace since the alias decl will be moved along with the type reference.
Eric Liu32158862016-11-14 19:37:55 +0000748 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32 +0000749 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55 +0000750 if (IsInMovedNs(FromDecl))
751 return;
Eric Liu26cf68a2016-12-15 10:42:35 +0000752 } else if (auto *TemplateType =
753 Type.getType()->getAs<TemplateSpecializationType>()) {
754 if (TemplateType->isTypeAlias()) {
755 FromDecl = TemplateType->getTemplateName().getAsTemplateDecl();
756 if (IsInMovedNs(FromDecl))
757 return;
758 }
Eric Liu32158862016-11-14 19:37:55 +0000759 }
Piotr Padlewski08124b12016-12-14 15:29:23 +0000760 const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu495b2112016-09-19 17:40:32 +0000761 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17 +0000762 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
763 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32 +0000764}
765
Eric Liu68765a82016-09-21 15:06:12 +0000766void ChangeNamespaceTool::fixUsingShadowDecl(
767 const ast_matchers::MatchFinder::MatchResult &Result,
768 const UsingDecl *UsingDeclaration) {
769 SourceLocation Start = UsingDeclaration->getLocStart();
770 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000771 if (Start.isInvalid() || End.isInvalid())
772 return;
Eric Liu68765a82016-09-21 15:06:12 +0000773
774 assert(UsingDeclaration->shadow_size() > 0);
775 // FIXME: it might not be always accurate to use the first using-decl.
776 const NamedDecl *TargetDecl =
777 UsingDeclaration->shadow_begin()->getTargetDecl();
778 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
779 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
780 // sense. If this happens, we need to use name with the new namespace.
781 // Use fully qualified name in UsingDecl for now.
Eric Liu4fe99e12016-12-14 17:01:52 +0000782 addReplacementOrDie(Start, End, "using ::" + TargetDeclName,
783 *Result.SourceManager, &FileToReplacements);
Eric Liu68765a82016-09-21 15:06:12 +0000784}
785
Eric Liuda22b3c2016-11-29 14:15:14 +0000786void ChangeNamespaceTool::fixDeclRefExpr(
787 const ast_matchers::MatchFinder::MatchResult &Result,
788 const DeclContext *UseContext, const NamedDecl *From,
789 const DeclRefExpr *Ref) {
790 SourceRange RefRange = Ref->getSourceRange();
791 replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(),
792 RefRange.getEnd(), From);
793}
794
Eric Liu495b2112016-09-19 17:40:32 +0000795void ChangeNamespaceTool::onEndOfTranslationUnit() {
796 // Move namespace blocks and insert forward declaration to old namespace.
797 for (const auto &FileAndNsMoves : MoveNamespaces) {
798 auto &NsMoves = FileAndNsMoves.second;
799 if (NsMoves.empty())
800 continue;
801 const std::string &FilePath = FileAndNsMoves.first;
802 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59 +0000803 auto &SM = *NsMoves.begin()->SourceMgr;
804 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32 +0000805 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
806 if (!ChangedCode) {
807 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
808 continue;
809 }
810 // Replacements on the changed code for moving namespaces and inserting
811 // forward declarations to old namespaces.
812 tooling::Replacements NewReplacements;
813 // Cut the changed code from the old namespace and paste the code in the new
814 // namespace.
815 for (const auto &NsMove : NsMoves) {
816 // Calculate the range of the old namespace block in the changed
817 // code.
818 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
819 const unsigned NewLength =
820 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
821 NewOffset;
822 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
823 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
824 std::string MovedCodeWrappedInNewNs =
825 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
826 // Calculate the new offset at which the code will be inserted in the
827 // changed code.
828 unsigned NewInsertionOffset =
829 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
830 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
831 MovedCodeWrappedInNewNs);
832 addOrMergeReplacement(Deletion, &NewReplacements);
833 addOrMergeReplacement(Insertion, &NewReplacements);
834 }
835 // After moving namespaces, insert forward declarations back to old
836 // namespaces.
837 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
838 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
839 unsigned NewInsertionOffset =
840 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
841 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
842 FwdDeclInsertion.ForwardDeclText);
843 addOrMergeReplacement(Insertion, &NewReplacements);
844 }
845 // Add replacements referring to the changed code to existing replacements,
846 // which refers to the original code.
847 Replaces = Replaces.merge(NewReplacements);
848 format::FormatStyle Style =
849 format::getStyle("file", FilePath, FallbackStyle);
850 // Clean up old namespaces if there is nothing in it after moving.
851 auto CleanReplacements =
852 format::cleanupAroundReplacements(Code, Replaces, Style);
853 if (!CleanReplacements) {
854 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
855 continue;
856 }
857 FileToReplacements[FilePath] = *CleanReplacements;
858 }
Eric Liuc265b022016-12-01 17:25:55 +0000859
860 // Make sure we don't generate replacements for files that do not match
861 // FilePattern.
862 for (auto &Entry : FileToReplacements)
863 if (!FilePatternRE.match(Entry.first))
864 Entry.second.clear();
Eric Liu495b2112016-09-19 17:40:32 +0000865}
866
867} // namespace change_namespace
868} // namespace clang