blob: 4157e4df4ca9e4bb7e0e47f585492019300a84aa [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
Eric Liu73f49fd2016-10-12 12:34:1885static std::unique_ptr<Lexer>
86getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM,
87 const LangOptions &LangOpts) {
Eric Liu495b2112016-09-19 17:40:3288 if (Loc.isMacroID() &&
89 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eric Liu73f49fd2016-10-12 12:34:1890 return nullptr;
Eric Liu495b2112016-09-19 17:40:3291 // 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:1897 return nullptr;
Eric Liu495b2112016-09-19 17:40:3298
99 const char *TokBegin = File.data() + LocInfo.second;
100 // Lex from the start of the given location.
Eric Liu73f49fd2016-10-12 12:34:18101 return llvm::make_unique<Lexer>(SM.getLocForStartOfFile(LocInfo.first),
102 LangOpts, File.begin(), TokBegin, File.end());
103}
Eric Liu495b2112016-09-19 17:40:32104
Eric Liu73f49fd2016-10-12 12:34:18105// 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:32113 llvm::SmallVector<char, 16> Line;
114 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
Eric Liu73f49fd2016-10-12 12:34:18115 Lex->setParsingPreprocessorDirective(true);
116 Lex->ReadToEndOfLine(&Line);
Haojian Wuef8a6dc2016-10-04 10:35:53117 auto End = Loc.getLocWithOffset(Line.size());
Eric Liu73f49fd2016-10-12 12:34:18118 return SM.getLocForEndOfFile(SM.getDecomposedLoc(Loc).first) == End
119 ? End
120 : End.getLocWithOffset(1);
Eric Liu495b2112016-09-19 17:40:32121}
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:39185// \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:32188std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
189 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39190 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:32198 const auto Pos = NsName.find_last_of(':');
199 if (Pos == llvm::StringRef::npos)
200 return DeclName;
Eric Liu447164d2016-10-05 15:52:39201 assert(Pos > 0);
202 NsName = NsName.substr(0, Pos - 1);
Eric Liu495b2112016-09-19 17:40:32203 }
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:32246void 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:48270 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32271 hasAncestor(cxxRecordDecl()),
272 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48273
Eric Liu495b2112016-09-19 17:40:32274 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29275 // TypeLoc and template specialization arguments (which are not outermost)
276 // that are directly linked to types matching `DeclMatcher`. Nested name
277 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32278 Finder->addMatcher(
279 typeLoc(IsInMovedNs,
280 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29281 unless(anyOf(hasParent(typeLoc(loc(qualType(
282 allOf(hasDeclaration(DeclMatcher),
283 unless(templateSpecializationType())))))),
Eric Liu495b2112016-09-19 17:40:32284 hasParent(nestedNameSpecifierLoc()))),
285 hasAncestor(decl().bind("dc")))
286 .bind("type"),
287 this);
Eric Liu912d0392016-09-27 12:54:48288
Eric Liu68765a82016-09-21 15:06:12289 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
290 // special case it.
291 Finder->addMatcher(
Eric Liu912d0392016-09-27 12:54:48292 usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl())).bind("using_decl"),
293 this);
294
Eric Liu68765a82016-09-21 15:06:12295 // Handle types in nested name specifier.
296 Finder->addMatcher(nestedNameSpecifierLoc(
297 hasAncestor(decl(IsInMovedNs).bind("dc")),
298 loc(nestedNameSpecifier(specifiesType(
299 hasDeclaration(DeclMatcher.bind("from_decl"))))))
300 .bind("nested_specifier_loc"),
301 this);
Eric Liu12068d82016-09-22 11:54:00302
303 // Handle function.
Eric Liu912d0392016-09-27 12:54:48304 // Only handle functions that are defined in a namespace excluding member
305 // function, static methods (qualified by nested specifier), and functions
306 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00307 // Note that the matcher does not exclude calls to out-of-line static method
308 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48309 auto FuncMatcher =
310 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
311 hasAncestor(namespaceDecl(isAnonymous())),
312 hasAncestor(cxxRecordDecl()))),
313 hasParent(namespaceDecl()));
Eric Liu12068d82016-09-22 11:54:00314 Finder->addMatcher(
315 decl(forEachDescendant(callExpr(callee(FuncMatcher)).bind("call")),
Eric Liu912d0392016-09-27 12:54:48316 IsInMovedNs, unless(isImplicit()))
Eric Liu12068d82016-09-22 11:54:00317 .bind("dc"),
318 this);
Eric Liu159f0132016-09-30 04:32:39319
320 auto GlobalVarMatcher = varDecl(
321 hasGlobalStorage(), hasParent(namespaceDecl()),
322 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
323 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
324 to(GlobalVarMatcher.bind("var_decl")))
325 .bind("var_ref"),
326 this);
Eric Liu495b2112016-09-19 17:40:32327}
328
329void ChangeNamespaceTool::run(
330 const ast_matchers::MatchFinder::MatchResult &Result) {
331 if (const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
332 moveOldNamespace(Result, NsDecl);
333 } else if (const auto *FwdDecl =
334 Result.Nodes.getNodeAs<CXXRecordDecl>("fwd_decl")) {
335 moveClassForwardDeclaration(Result, FwdDecl);
Eric Liu68765a82016-09-21 15:06:12336 } else if (const auto *UsingDeclaration =
337 Result.Nodes.getNodeAs<UsingDecl>("using_decl")) {
338 fixUsingShadowDecl(Result, UsingDeclaration);
339 } else if (const auto *Specifier =
340 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
341 "nested_specifier_loc")) {
342 SourceLocation Start = Specifier->getBeginLoc();
343 SourceLocation End = EndLocationForType(Specifier->getTypeLoc());
344 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00345 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu495b2112016-09-19 17:40:32346 fixTypeLoc(Result, startLocationForType(*TLoc), EndLocationForType(*TLoc),
347 *TLoc);
Eric Liu159f0132016-09-30 04:32:39348 } else if (const auto *VarRef = Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")){
349 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
350 assert(Var);
351 if (Var->getCanonicalDecl()->isStaticDataMember())
352 return;
353 std::string Name = Var->getQualifiedNameAsString();
354 const clang::Decl *Context = Result.Nodes.getNodeAs<clang::Decl>("dc");
355 assert(Context && "Empty decl context.");
356 clang::SourceRange VarRefRange = VarRef->getSourceRange();
357 replaceQualifiedSymbolInDeclContext(Result, Context, VarRefRange.getBegin(),
358 VarRefRange.getEnd(), Name);
Eric Liu12068d82016-09-22 11:54:00359 } else {
Eric Liu159f0132016-09-30 04:32:39360 const auto *Call = Result.Nodes.getNodeAs<clang::CallExpr>("call");
Eric Liu12068d82016-09-22 11:54:00361 assert(Call != nullptr &&"Expecting callback for CallExpr.");
362 const clang::FunctionDecl* Func = Call->getDirectCallee();
363 assert(Func != nullptr);
364 // Ignore out-of-line static methods since they will be handled by nested
365 // name specifiers.
366 if (Func->getCanonicalDecl()->getStorageClass() ==
367 clang::StorageClass::SC_Static &&
368 Func->isOutOfLine())
369 return;
370 std::string Name = Func->getQualifiedNameAsString();
371 const clang::Decl *Context = Result.Nodes.getNodeAs<clang::Decl>("dc");
372 assert(Context && "Empty decl context.");
373 clang::SourceRange CalleeRange = Call->getCallee()->getSourceRange();
374 replaceQualifiedSymbolInDeclContext(Result, Context, CalleeRange.getBegin(),
375 CalleeRange.getEnd(), Name);
Eric Liu495b2112016-09-19 17:40:32376 }
377}
378
Eric Liu73f49fd2016-10-12 12:34:18379static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
380 const SourceManager &SM,
381 const LangOptions &LangOpts) {
382 std::unique_ptr<Lexer> Lex =
383 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
384 assert(Lex.get() &&
385 "Failed to create lexer from the beginning of namespace.");
386 if (!Lex.get())
387 return SourceLocation();
388 Token Tok;
389 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
390 }
391 return Tok.isNot(tok::TokenKind::l_brace)
392 ? SourceLocation()
393 : Tok.getEndLoc().getLocWithOffset(1);
394}
395
Eric Liu495b2112016-09-19 17:40:32396// Stores information about a moved namespace in `MoveNamespaces` and leaves
397// the actual movement to `onEndOfTranslationUnit()`.
398void ChangeNamespaceTool::moveOldNamespace(
399 const ast_matchers::MatchFinder::MatchResult &Result,
400 const NamespaceDecl *NsDecl) {
401 // If the namespace is empty, do nothing.
402 if (Decl::castToDeclContext(NsDecl)->decls_empty())
403 return;
404
405 // Get the range of the code in the old namespace.
Eric Liu73f49fd2016-10-12 12:34:18406 SourceLocation Start = getLocAfterNamespaceLBrace(
407 NsDecl, *Result.SourceManager, Result.Context->getLangOpts());
408 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32409 SourceLocation End = NsDecl->getRBraceLoc().getLocWithOffset(-1);
410 // Create a replacement that deletes the code in the old namespace merely for
411 // retrieving offset and length from it.
412 const auto R = createReplacement(Start, End, "", *Result.SourceManager);
413 MoveNamespace MoveNs;
414 MoveNs.Offset = R.getOffset();
415 MoveNs.Length = R.getLength();
416
417 // Insert the new namespace after `DiffOldNamespace`. For example, if
418 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
419 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
420 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
421 // in the above example.
422 // FIXME: consider the case where DiffOldNamespace is empty.
423 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
424 SourceLocation LocAfterNs =
425 getStartOfNextLine(OuterNs->getRBraceLoc(), *Result.SourceManager,
426 Result.Context->getLangOpts());
427 assert(LocAfterNs.isValid() &&
428 "Failed to get location after DiffOldNamespace");
429 MoveNs.InsertionOffset = Result.SourceManager->getFileOffset(
430 Result.SourceManager->getSpellingLoc(LocAfterNs));
431
Eric Liucc83c662016-09-19 17:58:59432 MoveNs.FID = Result.SourceManager->getFileID(Start);
433 MoveNs.SourceMgr = Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32434 MoveNamespaces[R.getFilePath()].push_back(MoveNs);
435}
436
437// Removes a class forward declaration from the code in the moved namespace and
438// creates an `InsertForwardDeclaration` to insert the forward declaration back
439// into the old namespace after moving code from the old namespace to the new
440// namespace.
441// For example, changing "a" to "x":
442// Old code:
443// namespace a {
444// class FWD;
445// class A { FWD *fwd; }
446// } // a
447// New code:
448// namespace a {
449// class FWD;
450// } // a
451// namespace x {
452// class A { a::FWD *fwd; }
453// } // x
454void ChangeNamespaceTool::moveClassForwardDeclaration(
455 const ast_matchers::MatchFinder::MatchResult &Result,
456 const CXXRecordDecl *FwdDecl) {
457 SourceLocation Start = FwdDecl->getLocStart();
458 SourceLocation End = FwdDecl->getLocEnd();
459 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
460 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
461 /*SkipTrailingWhitespaceAndNewLine=*/true);
462 if (AfterSemi.isValid())
463 End = AfterSemi.getLocWithOffset(-1);
464 // Delete the forward declaration from the code to be moved.
465 const auto Deletion =
466 createReplacement(Start, End, "", *Result.SourceManager);
467 addOrMergeReplacement(Deletion, &FileToReplacements[Deletion.getFilePath()]);
468 llvm::StringRef Code = Lexer::getSourceText(
469 CharSourceRange::getTokenRange(
470 Result.SourceManager->getSpellingLoc(Start),
471 Result.SourceManager->getSpellingLoc(End)),
472 *Result.SourceManager, Result.Context->getLangOpts());
473 // Insert the forward declaration back into the old namespace after moving the
474 // code from old namespace to new namespace.
475 // Insertion information is stored in `InsertFwdDecls` and actual
476 // insertion will be performed in `onEndOfTranslationUnit`.
477 // Get the (old) namespace that contains the forward declaration.
478 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
479 // The namespace contains the forward declaration, so it must not be empty.
480 assert(!NsDecl->decls_empty());
481 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
482 Code, *Result.SourceManager);
483 InsertForwardDeclaration InsertFwd;
484 InsertFwd.InsertionOffset = Insertion.getOffset();
485 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
486 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
487}
488
489// Replaces a qualified symbol that refers to a declaration `DeclName` with the
490// shortest qualified name possible when the reference is in `NewNamespace`.
Eric Liu912d0392016-09-27 12:54:48491// FIXME: don't need to add redundant namespace qualifier when there is
492// UsingShadowDecl or using namespace decl.
Eric Liu495b2112016-09-19 17:40:32493void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
494 const ast_matchers::MatchFinder::MatchResult &Result, const Decl *DeclCtx,
495 SourceLocation Start, SourceLocation End, llvm::StringRef DeclName) {
496 const auto *NsDeclContext =
497 DeclCtx->getDeclContext()->getEnclosingNamespaceContext();
498 const auto *NsDecl = llvm::dyn_cast<NamespaceDecl>(NsDeclContext);
499 // Calculate the name of the `NsDecl` after it is moved to new namespace.
500 std::string OldNs = NsDecl->getQualifiedNameAsString();
501 llvm::StringRef Postfix = OldNs;
502 bool Consumed = Postfix.consume_front(OldNamespace);
503 assert(Consumed && "Expect OldNS to start with OldNamespace.");
504 (void)Consumed;
505 const std::string NewNs = (NewNamespace + Postfix).str();
506
507 llvm::StringRef NestedName = Lexer::getSourceText(
508 CharSourceRange::getTokenRange(
509 Result.SourceManager->getSpellingLoc(Start),
510 Result.SourceManager->getSpellingLoc(End)),
511 *Result.SourceManager, Result.Context->getLangOpts());
512 // If the symbol is already fully qualified, no change needs to be make.
513 if (NestedName.startswith("::"))
514 return;
515 std::string ReplaceName =
516 getShortestQualifiedNameInNamespace(DeclName, NewNs);
517 // If the new nested name in the new namespace is the same as it was in the
518 // old namespace, we don't create replacement.
519 if (NestedName == ReplaceName)
520 return;
521 auto R = createReplacement(Start, End, ReplaceName, *Result.SourceManager);
522 addOrMergeReplacement(R, &FileToReplacements[R.getFilePath()]);
523}
524
525// Replace the [Start, End] of `Type` with the shortest qualified name when the
526// `Type` is in `NewNamespace`.
527void ChangeNamespaceTool::fixTypeLoc(
528 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
529 SourceLocation End, TypeLoc Type) {
530 // FIXME: do not rename template parameter.
531 if (Start.isInvalid() || End.isInvalid())
532 return;
533 // The declaration which this TypeLoc refers to.
534 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
535 // `hasDeclaration` gives underlying declaration, but if the type is
536 // a typedef type, we need to use the typedef type instead.
537 if (auto *Typedef = Type.getType()->getAs<TypedefType>())
538 FromDecl = Typedef->getDecl();
539
540 const Decl *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
541 assert(DeclCtx && "Empty decl context.");
542 replaceQualifiedSymbolInDeclContext(Result, DeclCtx, Start, End,
543 FromDecl->getQualifiedNameAsString());
544}
545
Eric Liu68765a82016-09-21 15:06:12546void ChangeNamespaceTool::fixUsingShadowDecl(
547 const ast_matchers::MatchFinder::MatchResult &Result,
548 const UsingDecl *UsingDeclaration) {
549 SourceLocation Start = UsingDeclaration->getLocStart();
550 SourceLocation End = UsingDeclaration->getLocEnd();
551 if (Start.isInvalid() || End.isInvalid()) return;
552
553 assert(UsingDeclaration->shadow_size() > 0);
554 // FIXME: it might not be always accurate to use the first using-decl.
555 const NamedDecl *TargetDecl =
556 UsingDeclaration->shadow_begin()->getTargetDecl();
557 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
558 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
559 // sense. If this happens, we need to use name with the new namespace.
560 // Use fully qualified name in UsingDecl for now.
561 auto R = createReplacement(Start, End, "using ::" + TargetDeclName,
562 *Result.SourceManager);
563 addOrMergeReplacement(R, &FileToReplacements[R.getFilePath()]);
564}
565
Eric Liu495b2112016-09-19 17:40:32566void ChangeNamespaceTool::onEndOfTranslationUnit() {
567 // Move namespace blocks and insert forward declaration to old namespace.
568 for (const auto &FileAndNsMoves : MoveNamespaces) {
569 auto &NsMoves = FileAndNsMoves.second;
570 if (NsMoves.empty())
571 continue;
572 const std::string &FilePath = FileAndNsMoves.first;
573 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59574 auto &SM = *NsMoves.begin()->SourceMgr;
575 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32576 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
577 if (!ChangedCode) {
578 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
579 continue;
580 }
581 // Replacements on the changed code for moving namespaces and inserting
582 // forward declarations to old namespaces.
583 tooling::Replacements NewReplacements;
584 // Cut the changed code from the old namespace and paste the code in the new
585 // namespace.
586 for (const auto &NsMove : NsMoves) {
587 // Calculate the range of the old namespace block in the changed
588 // code.
589 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
590 const unsigned NewLength =
591 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
592 NewOffset;
593 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
594 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
595 std::string MovedCodeWrappedInNewNs =
596 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
597 // Calculate the new offset at which the code will be inserted in the
598 // changed code.
599 unsigned NewInsertionOffset =
600 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
601 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
602 MovedCodeWrappedInNewNs);
603 addOrMergeReplacement(Deletion, &NewReplacements);
604 addOrMergeReplacement(Insertion, &NewReplacements);
605 }
606 // After moving namespaces, insert forward declarations back to old
607 // namespaces.
608 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
609 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
610 unsigned NewInsertionOffset =
611 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
612 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
613 FwdDeclInsertion.ForwardDeclText);
614 addOrMergeReplacement(Insertion, &NewReplacements);
615 }
616 // Add replacements referring to the changed code to existing replacements,
617 // which refers to the original code.
618 Replaces = Replaces.merge(NewReplacements);
619 format::FormatStyle Style =
620 format::getStyle("file", FilePath, FallbackStyle);
621 // Clean up old namespaces if there is nothing in it after moving.
622 auto CleanReplacements =
623 format::cleanupAroundReplacements(Code, Replaces, Style);
624 if (!CleanReplacements) {
625 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
626 continue;
627 }
628 FileToReplacements[FilePath] = *CleanReplacements;
629 }
630}
631
632} // namespace change_namespace
633} // namespace clang