blob: 274c9acf4d015dec949d7b99c4c889a46c2c0dd0 [file] [log] [blame]
Eric Liu495b2112016-09-19 17:40:321//===-- 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"
12
13using namespace clang::ast_matchers;
14
15namespace clang {
16namespace change_namespace {
17
18namespace {
19
20inline std::string
21joinNamespaces(const llvm::SmallVectorImpl<StringRef> &Namespaces) {
22 if (Namespaces.empty())
23 return "";
24 std::string Result = Namespaces.front();
25 for (auto I = Namespaces.begin() + 1, E = Namespaces.end(); I != E; ++I)
26 Result += ("::" + *I).str();
27 return Result;
28}
29
30SourceLocation startLocationForType(TypeLoc TLoc) {
31 // For elaborated types (e.g. `struct a::A`) we want the portion after the
32 // `struct` but including the namespace qualifier, `a::`.
33 if (TLoc.getTypeLocClass() == TypeLoc::Elaborated) {
34 NestedNameSpecifierLoc NestedNameSpecifier =
35 TLoc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
36 if (NestedNameSpecifier.getNestedNameSpecifier())
37 return NestedNameSpecifier.getBeginLoc();
38 TLoc = TLoc.getNextTypeLoc();
39 }
40 return TLoc.getLocStart();
41}
42
43SourceLocation EndLocationForType(TypeLoc TLoc) {
44 // Dig past any namespace or keyword qualifications.
45 while (TLoc.getTypeLocClass() == TypeLoc::Elaborated ||
46 TLoc.getTypeLocClass() == TypeLoc::Qualified)
47 TLoc = TLoc.getNextTypeLoc();
48
49 // The location for template specializations (e.g. Foo<int>) includes the
50 // templated types in its location range. We want to restrict this to just
51 // before the `<` character.
52 if (TLoc.getTypeLocClass() == TypeLoc::TemplateSpecialization)
53 return TLoc.castAs<TemplateSpecializationTypeLoc>()
54 .getLAngleLoc()
55 .getLocWithOffset(-1);
56 return TLoc.getEndLoc();
57}
58
59// Returns the containing namespace of `InnerNs` by skipping `PartialNsName`.
60// If the `InnerNs` does not have `PartialNsName` as suffix, nullptr is
61// returned.
62// For example, if `InnerNs` is "a::b::c" and `PartialNsName` is "b::c", then
63// the NamespaceDecl of namespace "a" will be returned.
64const NamespaceDecl *getOuterNamespace(const NamespaceDecl *InnerNs,
65 llvm::StringRef PartialNsName) {
66 const auto *CurrentContext = llvm::cast<DeclContext>(InnerNs);
67 const auto *CurrentNs = InnerNs;
68 llvm::SmallVector<llvm::StringRef, 4> PartialNsNameSplitted;
69 PartialNsName.split(PartialNsNameSplitted, "::");
70 while (!PartialNsNameSplitted.empty()) {
71 // Get the inner-most namespace in CurrentContext.
72 while (CurrentContext && !llvm::isa<NamespaceDecl>(CurrentContext))
73 CurrentContext = CurrentContext->getParent();
74 if (!CurrentContext)
75 return nullptr;
76 CurrentNs = llvm::cast<NamespaceDecl>(CurrentContext);
77 if (PartialNsNameSplitted.back() != CurrentNs->getNameAsString())
78 return nullptr;
79 PartialNsNameSplitted.pop_back();
80 CurrentContext = CurrentContext->getParent();
81 }
82 return CurrentNs;
83}
84
85// FIXME: get rid of this helper function if this is supported in clang-refactor
86// library.
87SourceLocation getStartOfNextLine(SourceLocation Loc, const SourceManager &SM,
88 const LangOptions &LangOpts) {
89 if (Loc.isMacroID() &&
90 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
91 return SourceLocation();
92 // Break down the source location.
93 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
94 // Try to load the file buffer.
95 bool InvalidTemp = false;
96 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
97 if (InvalidTemp)
98 return SourceLocation();
99
100 const char *TokBegin = File.data() + LocInfo.second;
101 // Lex from the start of the given location.
102 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
103 TokBegin, File.end());
104
105 llvm::SmallVector<char, 16> Line;
106 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
107 Lex.setParsingPreprocessorDirective(true);
108 Lex.ReadToEndOfLine(&Line);
109 // FIXME: should not +1 at EOF.
110 return Loc.getLocWithOffset(Line.size() + 1);
111}
112
113// Returns `R` with new range that refers to code after `Replaces` being
114// applied.
115tooling::Replacement
116getReplacementInChangedCode(const tooling::Replacements &Replaces,
117 const tooling::Replacement &R) {
118 unsigned NewStart = Replaces.getShiftedCodePosition(R.getOffset());
119 unsigned NewEnd =
120 Replaces.getShiftedCodePosition(R.getOffset() + R.getLength());
121 return tooling::Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
122 R.getReplacementText());
123}
124
125// Adds a replacement `R` into `Replaces` or merges it into `Replaces` by
126// applying all existing Replaces first if there is conflict.
127void addOrMergeReplacement(const tooling::Replacement &R,
128 tooling::Replacements *Replaces) {
129 auto Err = Replaces->add(R);
130 if (Err) {
131 llvm::consumeError(std::move(Err));
132 auto Replace = getReplacementInChangedCode(*Replaces, R);
133 *Replaces = Replaces->merge(tooling::Replacements(Replace));
134 }
135}
136
137tooling::Replacement createReplacement(SourceLocation Start, SourceLocation End,
138 llvm::StringRef ReplacementText,
139 const SourceManager &SM) {
140 if (!Start.isValid() || !End.isValid()) {
141 llvm::errs() << "start or end location were invalid\n";
142 return tooling::Replacement();
143 }
144 if (SM.getDecomposedLoc(Start).first != SM.getDecomposedLoc(End).first) {
145 llvm::errs()
146 << "start or end location were in different macro expansions\n";
147 return tooling::Replacement();
148 }
149 Start = SM.getSpellingLoc(Start);
150 End = SM.getSpellingLoc(End);
151 if (SM.getFileID(Start) != SM.getFileID(End)) {
152 llvm::errs() << "start or end location were in different files\n";
153 return tooling::Replacement();
154 }
155 return tooling::Replacement(
156 SM, CharSourceRange::getTokenRange(SM.getSpellingLoc(Start),
157 SM.getSpellingLoc(End)),
158 ReplacementText);
159}
160
161tooling::Replacement createInsertion(SourceLocation Loc,
162 llvm::StringRef InsertText,
163 const SourceManager &SM) {
164 if (Loc.isInvalid()) {
165 llvm::errs() << "insert Location is invalid.\n";
166 return tooling::Replacement();
167 }
168 Loc = SM.getSpellingLoc(Loc);
169 return tooling::Replacement(SM, Loc, 0, InsertText);
170}
171
172// Returns the shortest qualified name for declaration `DeclName` in the
173// namespace `NsName`. For example, if `DeclName` is "a::b::X" and `NsName`
174// is "a::c::d", then "b::X" will be returned.
175std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
176 llvm::StringRef NsName) {
177 llvm::SmallVector<llvm::StringRef, 4> DeclNameSplitted;
178 DeclName.split(DeclNameSplitted, "::");
179 if (DeclNameSplitted.size() == 1)
180 return DeclName;
181 const auto UnqualifiedName = DeclNameSplitted.back();
182 while (true) {
183 const auto Pos = NsName.find_last_of(':');
184 if (Pos == llvm::StringRef::npos)
185 return DeclName;
186 const auto Prefix = NsName.substr(0, Pos - 1);
187 if (DeclName.startswith(Prefix))
188 return (Prefix + "::" + UnqualifiedName).str();
189 NsName = Prefix;
190 }
191 return DeclName;
192}
193
194std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) {
195 if (Code.back() != '\n')
196 Code += "\n";
197 llvm::SmallVector<StringRef, 4> NsSplitted;
198 NestedNs.split(NsSplitted, "::");
199 while (!NsSplitted.empty()) {
200 // FIXME: consider code style for comments.
201 Code = ("namespace " + NsSplitted.back() + " {\n" + Code +
202 "} // namespace " + NsSplitted.back() + "\n")
203 .str();
204 NsSplitted.pop_back();
205 }
206 return Code;
207}
208
209} // anonymous namespace
210
211ChangeNamespaceTool::ChangeNamespaceTool(
212 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
213 std::map<std::string, tooling::Replacements> *FileToReplacements,
214 llvm::StringRef FallbackStyle)
215 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
216 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
217 FilePattern(FilePattern) {
218 FileToReplacements->clear();
219 llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted;
220 llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted;
221 llvm::StringRef(OldNamespace).split(OldNsSplitted, "::");
222 llvm::StringRef(NewNamespace).split(NewNsSplitted, "::");
223 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
224 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
225 OldNsSplitted.front() == NewNsSplitted.front()) {
226 OldNsSplitted.erase(OldNsSplitted.begin());
227 NewNsSplitted.erase(NewNsSplitted.begin());
228 }
229 DiffOldNamespace = joinNamespaces(OldNsSplitted);
230 DiffNewNamespace = joinNamespaces(NewNsSplitted);
231}
232
Eric Liu495b2112016-09-19 17:40:32233void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
234 // Match old namespace blocks.
235 std::string FullOldNs = "::" + OldNamespace;
236 Finder->addMatcher(
237 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
238 .bind("old_ns"),
239 this);
240
241 auto IsInMovedNs =
242 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
243 isExpansionInFileMatching(FilePattern));
244
245 // Match forward-declarations in the old namespace.
246 Finder->addMatcher(
247 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), IsInMovedNs)
248 .bind("fwd_decl"),
249 this);
250
251 // Match references to types that are not defined in the old namespace.
252 // Forward-declarations in the old namespace are also matched since they will
253 // be moved back to the old namespace.
254 auto DeclMatcher = namedDecl(
255 hasAncestor(namespaceDecl()),
256 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48257 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32258 hasAncestor(cxxRecordDecl()),
259 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48260
Eric Liu495b2112016-09-19 17:40:32261 // Match TypeLocs on the declaration. Carefully match only the outermost
262 // TypeLoc that's directly linked to the old class and don't handle nested
263 // name specifier locs.
Eric Liu495b2112016-09-19 17:40:32264 Finder->addMatcher(
265 typeLoc(IsInMovedNs,
266 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
267 unless(anyOf(hasParent(typeLoc(
268 loc(qualType(hasDeclaration(DeclMatcher))))),
269 hasParent(nestedNameSpecifierLoc()))),
270 hasAncestor(decl().bind("dc")))
271 .bind("type"),
272 this);
Eric Liu912d0392016-09-27 12:54:48273
Eric Liu68765a82016-09-21 15:06:12274 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
275 // special case it.
276 Finder->addMatcher(
Eric Liu912d0392016-09-27 12:54:48277 usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl())).bind("using_decl"),
278 this);
279
Eric Liu68765a82016-09-21 15:06:12280 // Handle types in nested name specifier.
281 Finder->addMatcher(nestedNameSpecifierLoc(
282 hasAncestor(decl(IsInMovedNs).bind("dc")),
283 loc(nestedNameSpecifier(specifiesType(
284 hasDeclaration(DeclMatcher.bind("from_decl"))))))
285 .bind("nested_specifier_loc"),
286 this);
Eric Liu12068d82016-09-22 11:54:00287
288 // Handle function.
Eric Liu912d0392016-09-27 12:54:48289 // Only handle functions that are defined in a namespace excluding member
290 // function, static methods (qualified by nested specifier), and functions
291 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00292 // Note that the matcher does not exclude calls to out-of-line static method
293 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48294 auto FuncMatcher =
295 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
296 hasAncestor(namespaceDecl(isAnonymous())),
297 hasAncestor(cxxRecordDecl()))),
298 hasParent(namespaceDecl()));
Eric Liu12068d82016-09-22 11:54:00299 Finder->addMatcher(
300 decl(forEachDescendant(callExpr(callee(FuncMatcher)).bind("call")),
Eric Liu912d0392016-09-27 12:54:48301 IsInMovedNs, unless(isImplicit()))
Eric Liu12068d82016-09-22 11:54:00302 .bind("dc"),
303 this);
Eric Liu159f0132016-09-30 04:32:39304
305 auto GlobalVarMatcher = varDecl(
306 hasGlobalStorage(), hasParent(namespaceDecl()),
307 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
308 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
309 to(GlobalVarMatcher.bind("var_decl")))
310 .bind("var_ref"),
311 this);
Eric Liu495b2112016-09-19 17:40:32312}
313
314void ChangeNamespaceTool::run(
315 const ast_matchers::MatchFinder::MatchResult &Result) {
316 if (const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
317 moveOldNamespace(Result, NsDecl);
318 } else if (const auto *FwdDecl =
319 Result.Nodes.getNodeAs<CXXRecordDecl>("fwd_decl")) {
320 moveClassForwardDeclaration(Result, FwdDecl);
Eric Liu68765a82016-09-21 15:06:12321 } else if (const auto *UsingDeclaration =
322 Result.Nodes.getNodeAs<UsingDecl>("using_decl")) {
323 fixUsingShadowDecl(Result, UsingDeclaration);
324 } else if (const auto *Specifier =
325 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
326 "nested_specifier_loc")) {
327 SourceLocation Start = Specifier->getBeginLoc();
328 SourceLocation End = EndLocationForType(Specifier->getTypeLoc());
329 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00330 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu495b2112016-09-19 17:40:32331 fixTypeLoc(Result, startLocationForType(*TLoc), EndLocationForType(*TLoc),
332 *TLoc);
Eric Liu159f0132016-09-30 04:32:39333 } else if (const auto *VarRef = Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")){
334 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
335 assert(Var);
336 if (Var->getCanonicalDecl()->isStaticDataMember())
337 return;
338 std::string Name = Var->getQualifiedNameAsString();
339 const clang::Decl *Context = Result.Nodes.getNodeAs<clang::Decl>("dc");
340 assert(Context && "Empty decl context.");
341 clang::SourceRange VarRefRange = VarRef->getSourceRange();
342 replaceQualifiedSymbolInDeclContext(Result, Context, VarRefRange.getBegin(),
343 VarRefRange.getEnd(), Name);
Eric Liu12068d82016-09-22 11:54:00344 } else {
Eric Liu159f0132016-09-30 04:32:39345 const auto *Call = Result.Nodes.getNodeAs<clang::CallExpr>("call");
Eric Liu12068d82016-09-22 11:54:00346 assert(Call != nullptr &&"Expecting callback for CallExpr.");
347 const clang::FunctionDecl* Func = Call->getDirectCallee();
348 assert(Func != nullptr);
349 // Ignore out-of-line static methods since they will be handled by nested
350 // name specifiers.
351 if (Func->getCanonicalDecl()->getStorageClass() ==
352 clang::StorageClass::SC_Static &&
353 Func->isOutOfLine())
354 return;
355 std::string Name = Func->getQualifiedNameAsString();
356 const clang::Decl *Context = Result.Nodes.getNodeAs<clang::Decl>("dc");
357 assert(Context && "Empty decl context.");
358 clang::SourceRange CalleeRange = Call->getCallee()->getSourceRange();
359 replaceQualifiedSymbolInDeclContext(Result, Context, CalleeRange.getBegin(),
360 CalleeRange.getEnd(), Name);
Eric Liu495b2112016-09-19 17:40:32361 }
362}
363
364// Stores information about a moved namespace in `MoveNamespaces` and leaves
365// the actual movement to `onEndOfTranslationUnit()`.
366void ChangeNamespaceTool::moveOldNamespace(
367 const ast_matchers::MatchFinder::MatchResult &Result,
368 const NamespaceDecl *NsDecl) {
369 // If the namespace is empty, do nothing.
370 if (Decl::castToDeclContext(NsDecl)->decls_empty())
371 return;
372
373 // Get the range of the code in the old namespace.
374 SourceLocation Start = NsDecl->decls_begin()->getLocStart();
375 SourceLocation End = NsDecl->getRBraceLoc().getLocWithOffset(-1);
376 // Create a replacement that deletes the code in the old namespace merely for
377 // retrieving offset and length from it.
378 const auto R = createReplacement(Start, End, "", *Result.SourceManager);
379 MoveNamespace MoveNs;
380 MoveNs.Offset = R.getOffset();
381 MoveNs.Length = R.getLength();
382
383 // Insert the new namespace after `DiffOldNamespace`. For example, if
384 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
385 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
386 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
387 // in the above example.
388 // FIXME: consider the case where DiffOldNamespace is empty.
389 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
390 SourceLocation LocAfterNs =
391 getStartOfNextLine(OuterNs->getRBraceLoc(), *Result.SourceManager,
392 Result.Context->getLangOpts());
393 assert(LocAfterNs.isValid() &&
394 "Failed to get location after DiffOldNamespace");
395 MoveNs.InsertionOffset = Result.SourceManager->getFileOffset(
396 Result.SourceManager->getSpellingLoc(LocAfterNs));
397
Eric Liucc83c662016-09-19 17:58:59398 MoveNs.FID = Result.SourceManager->getFileID(Start);
399 MoveNs.SourceMgr = Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32400 MoveNamespaces[R.getFilePath()].push_back(MoveNs);
401}
402
403// Removes a class forward declaration from the code in the moved namespace and
404// creates an `InsertForwardDeclaration` to insert the forward declaration back
405// into the old namespace after moving code from the old namespace to the new
406// namespace.
407// For example, changing "a" to "x":
408// Old code:
409// namespace a {
410// class FWD;
411// class A { FWD *fwd; }
412// } // a
413// New code:
414// namespace a {
415// class FWD;
416// } // a
417// namespace x {
418// class A { a::FWD *fwd; }
419// } // x
420void ChangeNamespaceTool::moveClassForwardDeclaration(
421 const ast_matchers::MatchFinder::MatchResult &Result,
422 const CXXRecordDecl *FwdDecl) {
423 SourceLocation Start = FwdDecl->getLocStart();
424 SourceLocation End = FwdDecl->getLocEnd();
425 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
426 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
427 /*SkipTrailingWhitespaceAndNewLine=*/true);
428 if (AfterSemi.isValid())
429 End = AfterSemi.getLocWithOffset(-1);
430 // Delete the forward declaration from the code to be moved.
431 const auto Deletion =
432 createReplacement(Start, End, "", *Result.SourceManager);
433 addOrMergeReplacement(Deletion, &FileToReplacements[Deletion.getFilePath()]);
434 llvm::StringRef Code = Lexer::getSourceText(
435 CharSourceRange::getTokenRange(
436 Result.SourceManager->getSpellingLoc(Start),
437 Result.SourceManager->getSpellingLoc(End)),
438 *Result.SourceManager, Result.Context->getLangOpts());
439 // Insert the forward declaration back into the old namespace after moving the
440 // code from old namespace to new namespace.
441 // Insertion information is stored in `InsertFwdDecls` and actual
442 // insertion will be performed in `onEndOfTranslationUnit`.
443 // Get the (old) namespace that contains the forward declaration.
444 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
445 // The namespace contains the forward declaration, so it must not be empty.
446 assert(!NsDecl->decls_empty());
447 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
448 Code, *Result.SourceManager);
449 InsertForwardDeclaration InsertFwd;
450 InsertFwd.InsertionOffset = Insertion.getOffset();
451 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
452 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
453}
454
455// Replaces a qualified symbol that refers to a declaration `DeclName` with the
456// shortest qualified name possible when the reference is in `NewNamespace`.
Eric Liu912d0392016-09-27 12:54:48457// FIXME: don't need to add redundant namespace qualifier when there is
458// UsingShadowDecl or using namespace decl.
Eric Liu495b2112016-09-19 17:40:32459void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
460 const ast_matchers::MatchFinder::MatchResult &Result, const Decl *DeclCtx,
461 SourceLocation Start, SourceLocation End, llvm::StringRef DeclName) {
462 const auto *NsDeclContext =
463 DeclCtx->getDeclContext()->getEnclosingNamespaceContext();
464 const auto *NsDecl = llvm::dyn_cast<NamespaceDecl>(NsDeclContext);
465 // Calculate the name of the `NsDecl` after it is moved to new namespace.
466 std::string OldNs = NsDecl->getQualifiedNameAsString();
467 llvm::StringRef Postfix = OldNs;
468 bool Consumed = Postfix.consume_front(OldNamespace);
469 assert(Consumed && "Expect OldNS to start with OldNamespace.");
470 (void)Consumed;
471 const std::string NewNs = (NewNamespace + Postfix).str();
472
473 llvm::StringRef NestedName = Lexer::getSourceText(
474 CharSourceRange::getTokenRange(
475 Result.SourceManager->getSpellingLoc(Start),
476 Result.SourceManager->getSpellingLoc(End)),
477 *Result.SourceManager, Result.Context->getLangOpts());
478 // If the symbol is already fully qualified, no change needs to be make.
479 if (NestedName.startswith("::"))
480 return;
481 std::string ReplaceName =
482 getShortestQualifiedNameInNamespace(DeclName, NewNs);
483 // If the new nested name in the new namespace is the same as it was in the
484 // old namespace, we don't create replacement.
485 if (NestedName == ReplaceName)
486 return;
487 auto R = createReplacement(Start, End, ReplaceName, *Result.SourceManager);
488 addOrMergeReplacement(R, &FileToReplacements[R.getFilePath()]);
489}
490
491// Replace the [Start, End] of `Type` with the shortest qualified name when the
492// `Type` is in `NewNamespace`.
493void ChangeNamespaceTool::fixTypeLoc(
494 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
495 SourceLocation End, TypeLoc Type) {
496 // FIXME: do not rename template parameter.
497 if (Start.isInvalid() || End.isInvalid())
498 return;
499 // The declaration which this TypeLoc refers to.
500 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
501 // `hasDeclaration` gives underlying declaration, but if the type is
502 // a typedef type, we need to use the typedef type instead.
503 if (auto *Typedef = Type.getType()->getAs<TypedefType>())
504 FromDecl = Typedef->getDecl();
505
506 const Decl *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
507 assert(DeclCtx && "Empty decl context.");
508 replaceQualifiedSymbolInDeclContext(Result, DeclCtx, Start, End,
509 FromDecl->getQualifiedNameAsString());
510}
511
Eric Liu68765a82016-09-21 15:06:12512void ChangeNamespaceTool::fixUsingShadowDecl(
513 const ast_matchers::MatchFinder::MatchResult &Result,
514 const UsingDecl *UsingDeclaration) {
515 SourceLocation Start = UsingDeclaration->getLocStart();
516 SourceLocation End = UsingDeclaration->getLocEnd();
517 if (Start.isInvalid() || End.isInvalid()) return;
518
519 assert(UsingDeclaration->shadow_size() > 0);
520 // FIXME: it might not be always accurate to use the first using-decl.
521 const NamedDecl *TargetDecl =
522 UsingDeclaration->shadow_begin()->getTargetDecl();
523 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
524 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
525 // sense. If this happens, we need to use name with the new namespace.
526 // Use fully qualified name in UsingDecl for now.
527 auto R = createReplacement(Start, End, "using ::" + TargetDeclName,
528 *Result.SourceManager);
529 addOrMergeReplacement(R, &FileToReplacements[R.getFilePath()]);
530}
531
Eric Liu495b2112016-09-19 17:40:32532void ChangeNamespaceTool::onEndOfTranslationUnit() {
533 // Move namespace blocks and insert forward declaration to old namespace.
534 for (const auto &FileAndNsMoves : MoveNamespaces) {
535 auto &NsMoves = FileAndNsMoves.second;
536 if (NsMoves.empty())
537 continue;
538 const std::string &FilePath = FileAndNsMoves.first;
539 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59540 auto &SM = *NsMoves.begin()->SourceMgr;
541 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32542 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
543 if (!ChangedCode) {
544 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
545 continue;
546 }
547 // Replacements on the changed code for moving namespaces and inserting
548 // forward declarations to old namespaces.
549 tooling::Replacements NewReplacements;
550 // Cut the changed code from the old namespace and paste the code in the new
551 // namespace.
552 for (const auto &NsMove : NsMoves) {
553 // Calculate the range of the old namespace block in the changed
554 // code.
555 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
556 const unsigned NewLength =
557 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
558 NewOffset;
559 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
560 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
561 std::string MovedCodeWrappedInNewNs =
562 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
563 // Calculate the new offset at which the code will be inserted in the
564 // changed code.
565 unsigned NewInsertionOffset =
566 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
567 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
568 MovedCodeWrappedInNewNs);
569 addOrMergeReplacement(Deletion, &NewReplacements);
570 addOrMergeReplacement(Insertion, &NewReplacements);
571 }
572 // After moving namespaces, insert forward declarations back to old
573 // namespaces.
574 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
575 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
576 unsigned NewInsertionOffset =
577 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
578 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
579 FwdDeclInsertion.ForwardDeclText);
580 addOrMergeReplacement(Insertion, &NewReplacements);
581 }
582 // Add replacements referring to the changed code to existing replacements,
583 // which refers to the original code.
584 Replaces = Replaces.merge(NewReplacements);
585 format::FormatStyle Style =
586 format::getStyle("file", FilePath, FallbackStyle);
587 // Clean up old namespaces if there is nothing in it after moving.
588 auto CleanReplacements =
589 format::cleanupAroundReplacements(Code, Replaces, Style);
590 if (!CleanReplacements) {
591 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
592 continue;
593 }
594 FileToReplacements[FilePath] = *CleanReplacements;
595 }
596}
597
598} // namespace change_namespace
599} // namespace clang