blob: 40eb36ba4efa09cf7f30177f6ab37f77bc31c489 [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"
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
Eric Liu73f49fd2016-10-12 12:34:18 +000085static std::unique_ptr<Lexer>
86getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM,
87 const LangOptions &LangOpts) {
Eric Liu495b2112016-09-19 17:40:32 +000088 if (Loc.isMacroID() &&
89 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eric Liu73f49fd2016-10-12 12:34:18 +000090 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +000091 // Break down the source location.
92 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
93 // Try to load the file buffer.
94 bool InvalidTemp = false;
95 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
96 if (InvalidTemp)
Eric Liu73f49fd2016-10-12 12:34:18 +000097 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +000098
99 const char *TokBegin = File.data() + LocInfo.second;
100 // Lex from the start of the given location.
Eric Liu73f49fd2016-10-12 12:34:18 +0000101 return llvm::make_unique<Lexer>(SM.getLocForStartOfFile(LocInfo.first),
102 LangOpts, File.begin(), TokBegin, File.end());
103}
Eric Liu495b2112016-09-19 17:40:32 +0000104
Eric Liu73f49fd2016-10-12 12:34:18 +0000105// FIXME: get rid of this helper function if this is supported in clang-refactor
106// library.
107static SourceLocation getStartOfNextLine(SourceLocation Loc,
108 const SourceManager &SM,
109 const LangOptions &LangOpts) {
110 std::unique_ptr<Lexer> Lex = getLexerStartingFromLoc(Loc, SM, LangOpts);
111 if (!Lex.get())
112 return SourceLocation();
Eric Liu495b2112016-09-19 17:40:32 +0000113 llvm::SmallVector<char, 16> Line;
114 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
Eric Liu73f49fd2016-10-12 12:34:18 +0000115 Lex->setParsingPreprocessorDirective(true);
116 Lex->ReadToEndOfLine(&Line);
Haojian Wuef8a6dc2016-10-04 10:35:53 +0000117 auto End = Loc.getLocWithOffset(Line.size());
Eric Liu73f49fd2016-10-12 12:34:18 +0000118 return SM.getLocForEndOfFile(SM.getDecomposedLoc(Loc).first) == End
119 ? End
120 : End.getLocWithOffset(1);
Eric Liu495b2112016-09-19 17:40:32 +0000121}
122
123// Returns `R` with new range that refers to code after `Replaces` being
124// applied.
125tooling::Replacement
126getReplacementInChangedCode(const tooling::Replacements &Replaces,
127 const tooling::Replacement &R) {
128 unsigned NewStart = Replaces.getShiftedCodePosition(R.getOffset());
129 unsigned NewEnd =
130 Replaces.getShiftedCodePosition(R.getOffset() + R.getLength());
131 return tooling::Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
132 R.getReplacementText());
133}
134
135// Adds a replacement `R` into `Replaces` or merges it into `Replaces` by
136// applying all existing Replaces first if there is conflict.
137void addOrMergeReplacement(const tooling::Replacement &R,
138 tooling::Replacements *Replaces) {
139 auto Err = Replaces->add(R);
140 if (Err) {
141 llvm::consumeError(std::move(Err));
142 auto Replace = getReplacementInChangedCode(*Replaces, R);
143 *Replaces = Replaces->merge(tooling::Replacements(Replace));
144 }
145}
146
147tooling::Replacement createReplacement(SourceLocation Start, SourceLocation End,
148 llvm::StringRef ReplacementText,
149 const SourceManager &SM) {
150 if (!Start.isValid() || !End.isValid()) {
151 llvm::errs() << "start or end location were invalid\n";
152 return tooling::Replacement();
153 }
154 if (SM.getDecomposedLoc(Start).first != SM.getDecomposedLoc(End).first) {
155 llvm::errs()
156 << "start or end location were in different macro expansions\n";
157 return tooling::Replacement();
158 }
159 Start = SM.getSpellingLoc(Start);
160 End = SM.getSpellingLoc(End);
161 if (SM.getFileID(Start) != SM.getFileID(End)) {
162 llvm::errs() << "start or end location were in different files\n";
163 return tooling::Replacement();
164 }
165 return tooling::Replacement(
166 SM, CharSourceRange::getTokenRange(SM.getSpellingLoc(Start),
167 SM.getSpellingLoc(End)),
168 ReplacementText);
169}
170
171tooling::Replacement createInsertion(SourceLocation Loc,
172 llvm::StringRef InsertText,
173 const SourceManager &SM) {
174 if (Loc.isInvalid()) {
175 llvm::errs() << "insert Location is invalid.\n";
176 return tooling::Replacement();
177 }
178 Loc = SM.getSpellingLoc(Loc);
179 return tooling::Replacement(SM, Loc, 0, InsertText);
180}
181
182// Returns the shortest qualified name for declaration `DeclName` in the
183// namespace `NsName`. For example, if `DeclName` is "a::b::X" and `NsName`
184// is "a::c::d", then "b::X" will be returned.
Eric Liu447164d2016-10-05 15:52:39 +0000185// \param DeclName A fully qualified name, "::a::b::X" or "a::b::X".
186// \param NsName A fully qualified name, "::a::b" or "a::b". Global namespace
187// will have empty name.
Eric Liu495b2112016-09-19 17:40:32 +0000188std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
189 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39 +0000190 DeclName = DeclName.ltrim(':');
191 NsName = NsName.ltrim(':');
192 // If `DeclName` is a global variable, we prepend "::" to it if it is not in
193 // the global namespace.
194 if (DeclName.find(':') == llvm::StringRef::npos)
195 return NsName.empty() ? DeclName.str() : ("::" + DeclName).str();
196
197 while (!DeclName.consume_front((NsName + "::").str())) {
Eric Liu495b2112016-09-19 17:40:32 +0000198 const auto Pos = NsName.find_last_of(':');
199 if (Pos == llvm::StringRef::npos)
200 return DeclName;
Eric Liu447164d2016-10-05 15:52:39 +0000201 assert(Pos > 0);
202 NsName = NsName.substr(0, Pos - 1);
Eric Liu495b2112016-09-19 17:40:32 +0000203 }
204 return DeclName;
205}
206
207std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) {
208 if (Code.back() != '\n')
209 Code += "\n";
210 llvm::SmallVector<StringRef, 4> NsSplitted;
211 NestedNs.split(NsSplitted, "::");
212 while (!NsSplitted.empty()) {
213 // FIXME: consider code style for comments.
214 Code = ("namespace " + NsSplitted.back() + " {\n" + Code +
215 "} // namespace " + NsSplitted.back() + "\n")
216 .str();
217 NsSplitted.pop_back();
218 }
219 return Code;
220}
221
222} // anonymous namespace
223
224ChangeNamespaceTool::ChangeNamespaceTool(
225 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
226 std::map<std::string, tooling::Replacements> *FileToReplacements,
227 llvm::StringRef FallbackStyle)
228 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
229 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
230 FilePattern(FilePattern) {
231 FileToReplacements->clear();
232 llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted;
233 llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted;
234 llvm::StringRef(OldNamespace).split(OldNsSplitted, "::");
235 llvm::StringRef(NewNamespace).split(NewNsSplitted, "::");
236 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
237 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
238 OldNsSplitted.front() == NewNsSplitted.front()) {
239 OldNsSplitted.erase(OldNsSplitted.begin());
240 NewNsSplitted.erase(NewNsSplitted.begin());
241 }
242 DiffOldNamespace = joinNamespaces(OldNsSplitted);
243 DiffNewNamespace = joinNamespaces(NewNsSplitted);
244}
245
Eric Liu495b2112016-09-19 17:40:32 +0000246void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
247 // Match old namespace blocks.
248 std::string FullOldNs = "::" + OldNamespace;
249 Finder->addMatcher(
250 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
251 .bind("old_ns"),
252 this);
253
254 auto IsInMovedNs =
255 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
256 isExpansionInFileMatching(FilePattern));
257
258 // Match forward-declarations in the old namespace.
259 Finder->addMatcher(
260 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), IsInMovedNs)
261 .bind("fwd_decl"),
262 this);
263
264 // Match references to types that are not defined in the old namespace.
265 // Forward-declarations in the old namespace are also matched since they will
266 // be moved back to the old namespace.
267 auto DeclMatcher = namedDecl(
268 hasAncestor(namespaceDecl()),
269 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48 +0000270 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32 +0000271 hasAncestor(cxxRecordDecl()),
272 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48 +0000273
Eric Liu495b2112016-09-19 17:40:32 +0000274 // Match TypeLocs on the declaration. Carefully match only the outermost
275 // TypeLoc that's directly linked to the old class and don't handle nested
276 // name specifier locs.
Eric Liu495b2112016-09-19 17:40:32 +0000277 Finder->addMatcher(
278 typeLoc(IsInMovedNs,
279 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
280 unless(anyOf(hasParent(typeLoc(
281 loc(qualType(hasDeclaration(DeclMatcher))))),
282 hasParent(nestedNameSpecifierLoc()))),
283 hasAncestor(decl().bind("dc")))
284 .bind("type"),
285 this);
Eric Liu912d0392016-09-27 12:54:48 +0000286
Eric Liu68765a82016-09-21 15:06:12 +0000287 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
288 // special case it.
289 Finder->addMatcher(
Eric Liu912d0392016-09-27 12:54:48 +0000290 usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl())).bind("using_decl"),
291 this);
292
Eric Liu68765a82016-09-21 15:06:12 +0000293 // Handle types in nested name specifier.
294 Finder->addMatcher(nestedNameSpecifierLoc(
295 hasAncestor(decl(IsInMovedNs).bind("dc")),
296 loc(nestedNameSpecifier(specifiesType(
297 hasDeclaration(DeclMatcher.bind("from_decl"))))))
298 .bind("nested_specifier_loc"),
299 this);
Eric Liu12068d82016-09-22 11:54:00 +0000300
301 // Handle function.
Eric Liu912d0392016-09-27 12:54:48 +0000302 // Only handle functions that are defined in a namespace excluding member
303 // function, static methods (qualified by nested specifier), and functions
304 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00 +0000305 // Note that the matcher does not exclude calls to out-of-line static method
306 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48 +0000307 auto FuncMatcher =
308 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
309 hasAncestor(namespaceDecl(isAnonymous())),
310 hasAncestor(cxxRecordDecl()))),
311 hasParent(namespaceDecl()));
Eric Liu12068d82016-09-22 11:54:00 +0000312 Finder->addMatcher(
313 decl(forEachDescendant(callExpr(callee(FuncMatcher)).bind("call")),
Eric Liu912d0392016-09-27 12:54:48 +0000314 IsInMovedNs, unless(isImplicit()))
Eric Liu12068d82016-09-22 11:54:00 +0000315 .bind("dc"),
316 this);
Eric Liu159f0132016-09-30 04:32:39 +0000317
318 auto GlobalVarMatcher = varDecl(
319 hasGlobalStorage(), hasParent(namespaceDecl()),
320 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
321 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
322 to(GlobalVarMatcher.bind("var_decl")))
323 .bind("var_ref"),
324 this);
Eric Liu495b2112016-09-19 17:40:32 +0000325}
326
327void ChangeNamespaceTool::run(
328 const ast_matchers::MatchFinder::MatchResult &Result) {
329 if (const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
330 moveOldNamespace(Result, NsDecl);
331 } else if (const auto *FwdDecl =
332 Result.Nodes.getNodeAs<CXXRecordDecl>("fwd_decl")) {
333 moveClassForwardDeclaration(Result, FwdDecl);
Eric Liu68765a82016-09-21 15:06:12 +0000334 } else if (const auto *UsingDeclaration =
335 Result.Nodes.getNodeAs<UsingDecl>("using_decl")) {
336 fixUsingShadowDecl(Result, UsingDeclaration);
337 } else if (const auto *Specifier =
338 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
339 "nested_specifier_loc")) {
340 SourceLocation Start = Specifier->getBeginLoc();
341 SourceLocation End = EndLocationForType(Specifier->getTypeLoc());
342 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00 +0000343 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu495b2112016-09-19 17:40:32 +0000344 fixTypeLoc(Result, startLocationForType(*TLoc), EndLocationForType(*TLoc),
345 *TLoc);
Eric Liu159f0132016-09-30 04:32:39 +0000346 } else if (const auto *VarRef = Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")){
347 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
348 assert(Var);
349 if (Var->getCanonicalDecl()->isStaticDataMember())
350 return;
351 std::string Name = Var->getQualifiedNameAsString();
352 const clang::Decl *Context = Result.Nodes.getNodeAs<clang::Decl>("dc");
353 assert(Context && "Empty decl context.");
354 clang::SourceRange VarRefRange = VarRef->getSourceRange();
355 replaceQualifiedSymbolInDeclContext(Result, Context, VarRefRange.getBegin(),
356 VarRefRange.getEnd(), Name);
Eric Liu12068d82016-09-22 11:54:00 +0000357 } else {
Eric Liu159f0132016-09-30 04:32:39 +0000358 const auto *Call = Result.Nodes.getNodeAs<clang::CallExpr>("call");
Eric Liu12068d82016-09-22 11:54:00 +0000359 assert(Call != nullptr &&"Expecting callback for CallExpr.");
360 const clang::FunctionDecl* Func = Call->getDirectCallee();
361 assert(Func != nullptr);
362 // Ignore out-of-line static methods since they will be handled by nested
363 // name specifiers.
364 if (Func->getCanonicalDecl()->getStorageClass() ==
365 clang::StorageClass::SC_Static &&
366 Func->isOutOfLine())
367 return;
368 std::string Name = Func->getQualifiedNameAsString();
369 const clang::Decl *Context = Result.Nodes.getNodeAs<clang::Decl>("dc");
370 assert(Context && "Empty decl context.");
371 clang::SourceRange CalleeRange = Call->getCallee()->getSourceRange();
372 replaceQualifiedSymbolInDeclContext(Result, Context, CalleeRange.getBegin(),
373 CalleeRange.getEnd(), Name);
Eric Liu495b2112016-09-19 17:40:32 +0000374 }
375}
376
Eric Liu73f49fd2016-10-12 12:34:18 +0000377static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
378 const SourceManager &SM,
379 const LangOptions &LangOpts) {
380 std::unique_ptr<Lexer> Lex =
381 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
382 assert(Lex.get() &&
383 "Failed to create lexer from the beginning of namespace.");
384 if (!Lex.get())
385 return SourceLocation();
386 Token Tok;
387 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
388 }
389 return Tok.isNot(tok::TokenKind::l_brace)
390 ? SourceLocation()
391 : Tok.getEndLoc().getLocWithOffset(1);
392}
393
Eric Liu495b2112016-09-19 17:40:32 +0000394// Stores information about a moved namespace in `MoveNamespaces` and leaves
395// the actual movement to `onEndOfTranslationUnit()`.
396void ChangeNamespaceTool::moveOldNamespace(
397 const ast_matchers::MatchFinder::MatchResult &Result,
398 const NamespaceDecl *NsDecl) {
399 // If the namespace is empty, do nothing.
400 if (Decl::castToDeclContext(NsDecl)->decls_empty())
401 return;
402
403 // Get the range of the code in the old namespace.
Eric Liu73f49fd2016-10-12 12:34:18 +0000404 SourceLocation Start = getLocAfterNamespaceLBrace(
405 NsDecl, *Result.SourceManager, Result.Context->getLangOpts());
406 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32 +0000407 SourceLocation End = NsDecl->getRBraceLoc().getLocWithOffset(-1);
408 // Create a replacement that deletes the code in the old namespace merely for
409 // retrieving offset and length from it.
410 const auto R = createReplacement(Start, End, "", *Result.SourceManager);
411 MoveNamespace MoveNs;
412 MoveNs.Offset = R.getOffset();
413 MoveNs.Length = R.getLength();
414
415 // Insert the new namespace after `DiffOldNamespace`. For example, if
416 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
417 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
418 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
419 // in the above example.
420 // FIXME: consider the case where DiffOldNamespace is empty.
421 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
422 SourceLocation LocAfterNs =
423 getStartOfNextLine(OuterNs->getRBraceLoc(), *Result.SourceManager,
424 Result.Context->getLangOpts());
425 assert(LocAfterNs.isValid() &&
426 "Failed to get location after DiffOldNamespace");
427 MoveNs.InsertionOffset = Result.SourceManager->getFileOffset(
428 Result.SourceManager->getSpellingLoc(LocAfterNs));
429
Eric Liucc83c662016-09-19 17:58:59 +0000430 MoveNs.FID = Result.SourceManager->getFileID(Start);
431 MoveNs.SourceMgr = Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32 +0000432 MoveNamespaces[R.getFilePath()].push_back(MoveNs);
433}
434
435// Removes a class forward declaration from the code in the moved namespace and
436// creates an `InsertForwardDeclaration` to insert the forward declaration back
437// into the old namespace after moving code from the old namespace to the new
438// namespace.
439// For example, changing "a" to "x":
440// Old code:
441// namespace a {
442// class FWD;
443// class A { FWD *fwd; }
444// } // a
445// New code:
446// namespace a {
447// class FWD;
448// } // a
449// namespace x {
450// class A { a::FWD *fwd; }
451// } // x
452void ChangeNamespaceTool::moveClassForwardDeclaration(
453 const ast_matchers::MatchFinder::MatchResult &Result,
454 const CXXRecordDecl *FwdDecl) {
455 SourceLocation Start = FwdDecl->getLocStart();
456 SourceLocation End = FwdDecl->getLocEnd();
457 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
458 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
459 /*SkipTrailingWhitespaceAndNewLine=*/true);
460 if (AfterSemi.isValid())
461 End = AfterSemi.getLocWithOffset(-1);
462 // Delete the forward declaration from the code to be moved.
463 const auto Deletion =
464 createReplacement(Start, End, "", *Result.SourceManager);
465 addOrMergeReplacement(Deletion, &FileToReplacements[Deletion.getFilePath()]);
466 llvm::StringRef Code = Lexer::getSourceText(
467 CharSourceRange::getTokenRange(
468 Result.SourceManager->getSpellingLoc(Start),
469 Result.SourceManager->getSpellingLoc(End)),
470 *Result.SourceManager, Result.Context->getLangOpts());
471 // Insert the forward declaration back into the old namespace after moving the
472 // code from old namespace to new namespace.
473 // Insertion information is stored in `InsertFwdDecls` and actual
474 // insertion will be performed in `onEndOfTranslationUnit`.
475 // Get the (old) namespace that contains the forward declaration.
476 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
477 // The namespace contains the forward declaration, so it must not be empty.
478 assert(!NsDecl->decls_empty());
479 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
480 Code, *Result.SourceManager);
481 InsertForwardDeclaration InsertFwd;
482 InsertFwd.InsertionOffset = Insertion.getOffset();
483 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
484 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
485}
486
487// Replaces a qualified symbol that refers to a declaration `DeclName` with the
488// shortest qualified name possible when the reference is in `NewNamespace`.
Eric Liu912d0392016-09-27 12:54:48 +0000489// FIXME: don't need to add redundant namespace qualifier when there is
490// UsingShadowDecl or using namespace decl.
Eric Liu495b2112016-09-19 17:40:32 +0000491void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
492 const ast_matchers::MatchFinder::MatchResult &Result, const Decl *DeclCtx,
493 SourceLocation Start, SourceLocation End, llvm::StringRef DeclName) {
494 const auto *NsDeclContext =
495 DeclCtx->getDeclContext()->getEnclosingNamespaceContext();
496 const auto *NsDecl = llvm::dyn_cast<NamespaceDecl>(NsDeclContext);
497 // Calculate the name of the `NsDecl` after it is moved to new namespace.
498 std::string OldNs = NsDecl->getQualifiedNameAsString();
499 llvm::StringRef Postfix = OldNs;
500 bool Consumed = Postfix.consume_front(OldNamespace);
501 assert(Consumed && "Expect OldNS to start with OldNamespace.");
502 (void)Consumed;
503 const std::string NewNs = (NewNamespace + Postfix).str();
504
505 llvm::StringRef NestedName = Lexer::getSourceText(
506 CharSourceRange::getTokenRange(
507 Result.SourceManager->getSpellingLoc(Start),
508 Result.SourceManager->getSpellingLoc(End)),
509 *Result.SourceManager, Result.Context->getLangOpts());
510 // If the symbol is already fully qualified, no change needs to be make.
511 if (NestedName.startswith("::"))
512 return;
513 std::string ReplaceName =
514 getShortestQualifiedNameInNamespace(DeclName, NewNs);
515 // If the new nested name in the new namespace is the same as it was in the
516 // old namespace, we don't create replacement.
517 if (NestedName == ReplaceName)
518 return;
519 auto R = createReplacement(Start, End, ReplaceName, *Result.SourceManager);
520 addOrMergeReplacement(R, &FileToReplacements[R.getFilePath()]);
521}
522
523// Replace the [Start, End] of `Type` with the shortest qualified name when the
524// `Type` is in `NewNamespace`.
525void ChangeNamespaceTool::fixTypeLoc(
526 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
527 SourceLocation End, TypeLoc Type) {
528 // FIXME: do not rename template parameter.
529 if (Start.isInvalid() || End.isInvalid())
530 return;
531 // The declaration which this TypeLoc refers to.
532 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
533 // `hasDeclaration` gives underlying declaration, but if the type is
534 // a typedef type, we need to use the typedef type instead.
535 if (auto *Typedef = Type.getType()->getAs<TypedefType>())
536 FromDecl = Typedef->getDecl();
537
538 const Decl *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
539 assert(DeclCtx && "Empty decl context.");
540 replaceQualifiedSymbolInDeclContext(Result, DeclCtx, Start, End,
541 FromDecl->getQualifiedNameAsString());
542}
543
Eric Liu68765a82016-09-21 15:06:12 +0000544void ChangeNamespaceTool::fixUsingShadowDecl(
545 const ast_matchers::MatchFinder::MatchResult &Result,
546 const UsingDecl *UsingDeclaration) {
547 SourceLocation Start = UsingDeclaration->getLocStart();
548 SourceLocation End = UsingDeclaration->getLocEnd();
549 if (Start.isInvalid() || End.isInvalid()) return;
550
551 assert(UsingDeclaration->shadow_size() > 0);
552 // FIXME: it might not be always accurate to use the first using-decl.
553 const NamedDecl *TargetDecl =
554 UsingDeclaration->shadow_begin()->getTargetDecl();
555 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
556 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
557 // sense. If this happens, we need to use name with the new namespace.
558 // Use fully qualified name in UsingDecl for now.
559 auto R = createReplacement(Start, End, "using ::" + TargetDeclName,
560 *Result.SourceManager);
561 addOrMergeReplacement(R, &FileToReplacements[R.getFilePath()]);
562}
563
Eric Liu495b2112016-09-19 17:40:32 +0000564void ChangeNamespaceTool::onEndOfTranslationUnit() {
565 // Move namespace blocks and insert forward declaration to old namespace.
566 for (const auto &FileAndNsMoves : MoveNamespaces) {
567 auto &NsMoves = FileAndNsMoves.second;
568 if (NsMoves.empty())
569 continue;
570 const std::string &FilePath = FileAndNsMoves.first;
571 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59 +0000572 auto &SM = *NsMoves.begin()->SourceMgr;
573 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32 +0000574 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
575 if (!ChangedCode) {
576 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
577 continue;
578 }
579 // Replacements on the changed code for moving namespaces and inserting
580 // forward declarations to old namespaces.
581 tooling::Replacements NewReplacements;
582 // Cut the changed code from the old namespace and paste the code in the new
583 // namespace.
584 for (const auto &NsMove : NsMoves) {
585 // Calculate the range of the old namespace block in the changed
586 // code.
587 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
588 const unsigned NewLength =
589 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
590 NewOffset;
591 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
592 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
593 std::string MovedCodeWrappedInNewNs =
594 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
595 // Calculate the new offset at which the code will be inserted in the
596 // changed code.
597 unsigned NewInsertionOffset =
598 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
599 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
600 MovedCodeWrappedInNewNs);
601 addOrMergeReplacement(Deletion, &NewReplacements);
602 addOrMergeReplacement(Insertion, &NewReplacements);
603 }
604 // After moving namespaces, insert forward declarations back to old
605 // namespaces.
606 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
607 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
608 unsigned NewInsertionOffset =
609 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
610 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
611 FwdDeclInsertion.ForwardDeclText);
612 addOrMergeReplacement(Insertion, &NewReplacements);
613 }
614 // Add replacements referring to the changed code to existing replacements,
615 // which refers to the original code.
616 Replaces = Replaces.merge(NewReplacements);
617 format::FormatStyle Style =
618 format::getStyle("file", FilePath, FallbackStyle);
619 // Clean up old namespaces if there is nothing in it after moving.
620 auto CleanReplacements =
621 format::cleanupAroundReplacements(Code, Replaces, Style);
622 if (!CleanReplacements) {
623 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
624 continue;
625 }
626 FileToReplacements[FilePath] = *CleanReplacements;
627 }
628}
629
630} // namespace change_namespace
631} // namespace clang