blob: ad1c22afcdb831967e4821532e75d2145be1761c [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"
Eric Liuff51f012016-11-16 16:54:5312#include "llvm/Support/ErrorHandling.h"
Eric Liu495b2112016-09-19 17:40:3213
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:5544SourceLocation endLocationForType(TypeLoc TLoc) {
Eric Liu495b2112016-09-19 17:40:3245 // 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:0161// If the `InnerNs` does not have `PartialNsName` as suffix, or `PartialNsName`
62// is empty, nullptr is returned.
Eric Liu495b2112016-09-19 17:40:3263// 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:0167 if (!InnerNs || PartialNsName.empty())
68 return nullptr;
Eric Liu495b2112016-09-19 17:40:3269 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:0172 PartialNsName.split(PartialNsNameSplitted, "::", /*MaxSplit=*/-1,
73 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:3274 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:1889static std::unique_ptr<Lexer>
90getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM,
91 const LangOptions &LangOpts) {
Eric Liu495b2112016-09-19 17:40:3292 if (Loc.isMacroID() &&
93 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eric Liu73f49fd2016-10-12 12:34:1894 return nullptr;
Eric Liu495b2112016-09-19 17:40:3295 // 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:18101 return nullptr;
Eric Liu495b2112016-09-19 17:40:32102
103 const char *TokBegin = File.data() + LocInfo.second;
104 // Lex from the start of the given location.
Eric Liu73f49fd2016-10-12 12:34:18105 return llvm::make_unique<Lexer>(SM.getLocForStartOfFile(LocInfo.first),
106 LangOpts, File.begin(), TokBegin, File.end());
107}
Eric Liu495b2112016-09-19 17:40:32108
Eric Liu73f49fd2016-10-12 12:34:18109// 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:32117 llvm::SmallVector<char, 16> Line;
118 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
Eric Liu73f49fd2016-10-12 12:34:18119 Lex->setParsingPreprocessorDirective(true);
120 Lex->ReadToEndOfLine(&Line);
Haojian Wuef8a6dc2016-10-04 10:35:53121 auto End = Loc.getLocWithOffset(Line.size());
Eric Liu73f49fd2016-10-12 12:34:18122 return SM.getLocForEndOfFile(SM.getDecomposedLoc(Loc).first) == End
123 ? End
124 : End.getLocWithOffset(1);
Eric Liu495b2112016-09-19 17:40:32125}
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:52175void 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:32185tooling::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 Liubc715502017-01-26 15:08:44199// Note that if `DeclName` is `::b::X` and `NsName` is `::a::b`, this returns
200// "::b::X" instead of "b::X" since there will be a name conflict otherwise.
Eric Liu447164d2016-10-05 15:52:39201// \param DeclName A fully qualified name, "::a::b::X" or "a::b::X".
202// \param NsName A fully qualified name, "::a::b" or "a::b". Global namespace
203// will have empty name.
Eric Liu495b2112016-09-19 17:40:32204std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
205 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39206 DeclName = DeclName.ltrim(':');
207 NsName = NsName.ltrim(':');
Eric Liu447164d2016-10-05 15:52:39208 if (DeclName.find(':') == llvm::StringRef::npos)
Eric Liub9bf1b52016-11-08 22:44:17209 return DeclName;
Eric Liu447164d2016-10-05 15:52:39210
Eric Liubc715502017-01-26 15:08:44211 llvm::SmallVector<llvm::StringRef, 4> NsNameSplitted;
212 NsName.split(NsNameSplitted, "::", /*MaxSplit=*/-1,
213 /*KeepEmpty=*/false);
214 llvm::SmallVector<llvm::StringRef, 4> DeclNsSplitted;
215 DeclName.split(DeclNsSplitted, "::", /*MaxSplit=*/-1,
216 /*KeepEmpty=*/false);
217 llvm::StringRef UnqualifiedDeclName = DeclNsSplitted.pop_back_val();
218 // If the Decl is in global namespace, there is no need to shorten it.
219 if (DeclNsSplitted.empty())
220 return UnqualifiedDeclName;
221 // If NsName is the global namespace, we can simply use the DeclName sans
222 // leading "::".
223 if (NsNameSplitted.empty())
224 return DeclName;
225
226 if (NsNameSplitted.front() != DeclNsSplitted.front()) {
227 // The DeclName must be fully-qualified, but we still need to decide if a
228 // leading "::" is necessary. For example, if `NsName` is "a::b::c" and the
229 // `DeclName` is "b::X", then the reference must be qualified as "::b::X"
230 // to avoid conflict.
231 if (llvm::is_contained(NsNameSplitted, DeclNsSplitted.front()))
232 return ("::" + DeclName).str();
233 return DeclName;
Eric Liu495b2112016-09-19 17:40:32234 }
Eric Liubc715502017-01-26 15:08:44235 // Since there is already an overlap namespace, we know that `DeclName` can be
236 // shortened, so we reduce the longest common prefix.
237 auto DeclI = DeclNsSplitted.begin();
238 auto DeclE = DeclNsSplitted.end();
239 auto NsI = NsNameSplitted.begin();
240 auto NsE = NsNameSplitted.end();
241 for (; DeclI != DeclE && NsI != NsE && *DeclI == *NsI; ++DeclI, ++NsI) {
242 }
243 return (DeclI == DeclE)
244 ? UnqualifiedDeclName.str()
245 : (llvm::join(DeclI, DeclE, "::") + "::" + UnqualifiedDeclName)
246 .str();
Eric Liu495b2112016-09-19 17:40:32247}
248
249std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) {
250 if (Code.back() != '\n')
251 Code += "\n";
252 llvm::SmallVector<StringRef, 4> NsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04253 NestedNs.split(NsSplitted, "::", /*MaxSplit=*/-1,
254 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32255 while (!NsSplitted.empty()) {
256 // FIXME: consider code style for comments.
257 Code = ("namespace " + NsSplitted.back() + " {\n" + Code +
258 "} // namespace " + NsSplitted.back() + "\n")
259 .str();
260 NsSplitted.pop_back();
261 }
262 return Code;
263}
264
Eric Liub9bf1b52016-11-08 22:44:17265// Returns true if \p D is a nested DeclContext in \p Context
266bool isNestedDeclContext(const DeclContext *D, const DeclContext *Context) {
267 while (D) {
268 if (D == Context)
269 return true;
270 D = D->getParent();
271 }
272 return false;
273}
274
275// Returns true if \p D is visible at \p Loc with DeclContext \p DeclCtx.
276bool isDeclVisibleAtLocation(const SourceManager &SM, const Decl *D,
277 const DeclContext *DeclCtx, SourceLocation Loc) {
Eric Liua13c4192017-02-13 17:24:14278 SourceLocation DeclLoc = SM.getSpellingLoc(D->getLocStart());
Eric Liub9bf1b52016-11-08 22:44:17279 Loc = SM.getSpellingLoc(Loc);
280 return SM.isBeforeInTranslationUnit(DeclLoc, Loc) &&
281 (SM.getFileID(DeclLoc) == SM.getFileID(Loc) &&
282 isNestedDeclContext(DeclCtx, D->getDeclContext()));
283}
284
Eric Liu0325a772017-02-02 17:40:38285AST_MATCHER(EnumDecl, isScoped) {
286 return Node.isScoped();
287}
288
Eric Liu495b2112016-09-19 17:40:32289} // anonymous namespace
290
291ChangeNamespaceTool::ChangeNamespaceTool(
292 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
Eric Liu7fccc992017-02-24 11:54:45293 llvm::ArrayRef<std::string> WhiteListedSymbolPatterns,
Eric Liu495b2112016-09-19 17:40:32294 std::map<std::string, tooling::Replacements> *FileToReplacements,
295 llvm::StringRef FallbackStyle)
296 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
297 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
Eric Liuc265b022016-12-01 17:25:55298 FilePattern(FilePattern), FilePatternRE(FilePattern) {
Eric Liu495b2112016-09-19 17:40:32299 FileToReplacements->clear();
300 llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted;
301 llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted;
302 llvm::StringRef(OldNamespace).split(OldNsSplitted, "::");
303 llvm::StringRef(NewNamespace).split(NewNsSplitted, "::");
304 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
305 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
306 OldNsSplitted.front() == NewNsSplitted.front()) {
307 OldNsSplitted.erase(OldNsSplitted.begin());
308 NewNsSplitted.erase(NewNsSplitted.begin());
309 }
310 DiffOldNamespace = joinNamespaces(OldNsSplitted);
311 DiffNewNamespace = joinNamespaces(NewNsSplitted);
Eric Liu7fccc992017-02-24 11:54:45312
313 for (const auto &Pattern : WhiteListedSymbolPatterns)
314 WhiteListedSymbolRegexes.emplace_back(Pattern);
Eric Liu495b2112016-09-19 17:40:32315}
316
Eric Liu495b2112016-09-19 17:40:32317void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32318 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17319 // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the
320 // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will
321 // be "a::b". Declarations in this namespace will not be visible in the new
322 // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-".
323 llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04324 llvm::StringRef(DiffOldNamespace)
325 .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1,
326 /*KeepEmpty=*/false);
Eric Liub9bf1b52016-11-08 22:44:17327 std::string Prefix = "-";
328 if (!DiffOldNsSplitted.empty())
329 Prefix = (StringRef(FullOldNs).drop_back(DiffOldNamespace.size()) +
330 DiffOldNsSplitted.front())
331 .str();
332 auto IsInMovedNs =
333 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
334 isExpansionInFileMatching(FilePattern));
335 auto IsVisibleInNewNs = anyOf(
336 IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Prefix)))));
337 // Match using declarations.
338 Finder->addMatcher(
339 usingDecl(isExpansionInFileMatching(FilePattern), IsVisibleInNewNs)
340 .bind("using"),
341 this);
342 // Match using namespace declarations.
343 Finder->addMatcher(usingDirectiveDecl(isExpansionInFileMatching(FilePattern),
344 IsVisibleInNewNs)
345 .bind("using_namespace"),
346 this);
Eric Liu180dac62016-12-23 10:47:09347 // Match namespace alias declarations.
348 Finder->addMatcher(namespaceAliasDecl(isExpansionInFileMatching(FilePattern),
349 IsVisibleInNewNs)
350 .bind("namespace_alias"),
351 this);
Eric Liub9bf1b52016-11-08 22:44:17352
353 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32354 Finder->addMatcher(
355 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
356 .bind("old_ns"),
357 this);
358
Eric Liu41552d62016-12-07 14:20:52359 // Match class forward-declarations in the old namespace.
360 // Note that forward-declarations in classes are not matched.
361 Finder->addMatcher(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())),
362 IsInMovedNs, hasParent(namespaceDecl()))
363 .bind("class_fwd_decl"),
364 this);
365
366 // Match template class forward-declarations in the old namespace.
Eric Liu495b2112016-09-19 17:40:32367 Finder->addMatcher(
Eric Liu41552d62016-12-07 14:20:52368 classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))),
369 IsInMovedNs, hasParent(namespaceDecl()))
370 .bind("template_class_fwd_decl"),
Eric Liu495b2112016-09-19 17:40:32371 this);
372
373 // Match references to types that are not defined in the old namespace.
374 // Forward-declarations in the old namespace are also matched since they will
375 // be moved back to the old namespace.
376 auto DeclMatcher = namedDecl(
377 hasAncestor(namespaceDecl()),
378 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48379 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32380 hasAncestor(cxxRecordDecl()),
381 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48382
Eric Liu8685c762016-12-07 17:04:07383 // Using shadow declarations in classes always refers to base class, which
384 // does not need to be qualified since it can be inferred from inheritance.
385 // Note that this does not match using alias declarations.
386 auto UsingShadowDeclInClass =
387 usingDecl(hasAnyUsingShadowDecl(decl()), hasParent(cxxRecordDecl()));
388
Eric Liu495b2112016-09-19 17:40:32389 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29390 // TypeLoc and template specialization arguments (which are not outermost)
391 // that are directly linked to types matching `DeclMatcher`. Nested name
392 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32393 Finder->addMatcher(
394 typeLoc(IsInMovedNs,
395 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29396 unless(anyOf(hasParent(typeLoc(loc(qualType(
397 allOf(hasDeclaration(DeclMatcher),
398 unless(templateSpecializationType())))))),
Eric Liu8685c762016-12-07 17:04:07399 hasParent(nestedNameSpecifierLoc()),
400 hasAncestor(isImplicit()),
401 hasAncestor(UsingShadowDeclInClass))),
Eric Liu495b2112016-09-19 17:40:32402 hasAncestor(decl().bind("dc")))
403 .bind("type"),
404 this);
Eric Liu912d0392016-09-27 12:54:48405
Eric Liu68765a82016-09-21 15:06:12406 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
407 // special case it.
Eric Liu8685c762016-12-07 17:04:07408 // Since using declarations inside classes must have the base class in the
409 // nested name specifier, we leave it to the nested name specifier matcher.
410 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()),
411 unless(UsingShadowDeclInClass))
Eric Liub9bf1b52016-11-08 22:44:17412 .bind("using_with_shadow"),
413 this);
Eric Liu912d0392016-09-27 12:54:48414
Eric Liuff51f012016-11-16 16:54:53415 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
416 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
417 // "A::A" would have already been fixed.
Eric Liu8685c762016-12-07 17:04:07418 Finder->addMatcher(
419 nestedNameSpecifierLoc(
420 hasAncestor(decl(IsInMovedNs).bind("dc")),
421 loc(nestedNameSpecifier(
422 specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
423 unless(anyOf(hasAncestor(isImplicit()),
424 hasAncestor(UsingShadowDeclInClass),
425 hasAncestor(typeLoc(loc(qualType(hasDeclaration(
426 decl(equalsBoundNode("from_decl"))))))))))
427 .bind("nested_specifier_loc"),
428 this);
Eric Liu12068d82016-09-22 11:54:00429
Eric Liuff51f012016-11-16 16:54:53430 // Matches base class initializers in constructors. TypeLocs of base class
431 // initializers do not need to be fixed. For example,
432 // class X : public a::b::Y {
433 // public:
434 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
435 // };
436 Finder->addMatcher(
437 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
438
Eric Liu12068d82016-09-22 11:54:00439 // Handle function.
Eric Liu912d0392016-09-27 12:54:48440 // Only handle functions that are defined in a namespace excluding member
441 // function, static methods (qualified by nested specifier), and functions
442 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00443 // Note that the matcher does not exclude calls to out-of-line static method
444 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48445 auto FuncMatcher =
446 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
447 hasAncestor(namespaceDecl(isAnonymous())),
448 hasAncestor(cxxRecordDecl()))),
449 hasParent(namespaceDecl()));
Eric Liuda22b3c2016-11-29 14:15:14450 Finder->addMatcher(decl(forEachDescendant(expr(anyOf(
451 callExpr(callee(FuncMatcher)).bind("call"),
452 declRefExpr(to(FuncMatcher.bind("func_decl")))
453 .bind("func_ref")))),
454 IsInMovedNs, unless(isImplicit()))
455 .bind("dc"),
456 this);
Eric Liu159f0132016-09-30 04:32:39457
458 auto GlobalVarMatcher = varDecl(
459 hasGlobalStorage(), hasParent(namespaceDecl()),
460 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
461 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
462 to(GlobalVarMatcher.bind("var_decl")))
463 .bind("var_ref"),
464 this);
Eric Liu0325a772017-02-02 17:40:38465
466 // Handle unscoped enum constant.
467 auto UnscopedEnumMatcher = enumConstantDecl(hasParent(enumDecl(
468 hasParent(namespaceDecl()),
469 unless(anyOf(isScoped(), IsInMovedNs, hasAncestor(cxxRecordDecl()),
470 hasAncestor(namespaceDecl(isAnonymous())))))));
471 Finder->addMatcher(
472 declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
473 to(UnscopedEnumMatcher.bind("enum_const_decl")))
474 .bind("enum_const_ref"),
475 this);
Eric Liu495b2112016-09-19 17:40:32476}
477
478void ChangeNamespaceTool::run(
479 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17480 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
481 UsingDecls.insert(Using);
482 } else if (const auto *UsingNamespace =
483 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
484 "using_namespace")) {
485 UsingNamespaceDecls.insert(UsingNamespace);
Eric Liu180dac62016-12-23 10:47:09486 } else if (const auto *NamespaceAlias =
487 Result.Nodes.getNodeAs<NamespaceAliasDecl>(
488 "namespace_alias")) {
489 NamespaceAliasDecls.insert(NamespaceAlias);
Eric Liub9bf1b52016-11-08 22:44:17490 } else if (const auto *NsDecl =
491 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32492 moveOldNamespace(Result, NsDecl);
493 } else if (const auto *FwdDecl =
Eric Liu41552d62016-12-07 14:20:52494 Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) {
495 moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl));
496 } else if (const auto *TemplateFwdDecl =
497 Result.Nodes.getNodeAs<ClassTemplateDecl>(
498 "template_class_fwd_decl")) {
499 moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl));
Eric Liub9bf1b52016-11-08 22:44:17500 } else if (const auto *UsingWithShadow =
501 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
502 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12503 } else if (const auto *Specifier =
504 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
505 "nested_specifier_loc")) {
506 SourceLocation Start = Specifier->getBeginLoc();
Eric Liuc265b022016-12-01 17:25:55507 SourceLocation End = endLocationForType(Specifier->getTypeLoc());
Eric Liu68765a82016-09-21 15:06:12508 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53509 } else if (const auto *BaseInitializer =
510 Result.Nodes.getNodeAs<CXXCtorInitializer>(
511 "base_initializer")) {
512 BaseCtorInitializerTypeLocs.push_back(
513 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00514 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu26cf68a2016-12-15 10:42:35515 // This avoids fixing types with record types as qualifier, which is not
516 // filtered by matchers in some cases, e.g. the type is templated. We should
517 // handle the record type qualifier instead.
Eric Liu0c0aea02016-12-15 13:02:41518 TypeLoc Loc = *TLoc;
519 while (Loc.getTypeLocClass() == TypeLoc::Qualified)
520 Loc = Loc.getNextTypeLoc();
521 if (Loc.getTypeLocClass() == TypeLoc::Elaborated) {
Eric Liu26cf68a2016-12-15 10:42:35522 NestedNameSpecifierLoc NestedNameSpecifier =
Eric Liu0c0aea02016-12-15 13:02:41523 Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
Eric Liu26cf68a2016-12-15 10:42:35524 const Type *SpecifierType =
525 NestedNameSpecifier.getNestedNameSpecifier()->getAsType();
526 if (SpecifierType && SpecifierType->isRecordType())
527 return;
528 }
Eric Liu0c0aea02016-12-15 13:02:41529 fixTypeLoc(Result, startLocationForType(Loc), endLocationForType(Loc), Loc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19530 } else if (const auto *VarRef =
531 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39532 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
533 assert(Var);
534 if (Var->getCanonicalDecl()->isStaticDataMember())
535 return;
Eric Liuda22b3c2016-11-29 14:15:14536 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu159f0132016-09-30 04:32:39537 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14538 fixDeclRefExpr(Result, Context->getDeclContext(),
539 llvm::cast<NamedDecl>(Var), VarRef);
Eric Liu0325a772017-02-02 17:40:38540 } else if (const auto *EnumConstRef =
541 Result.Nodes.getNodeAs<DeclRefExpr>("enum_const_ref")) {
542 // Do not rename the reference if it is already scoped by the EnumDecl name.
543 if (EnumConstRef->hasQualifier() &&
Eric Liu28c30ce2017-02-02 19:46:12544 EnumConstRef->getQualifier()->getKind() ==
545 NestedNameSpecifier::SpecifierKind::TypeSpec &&
Eric Liu0325a772017-02-02 17:40:38546 EnumConstRef->getQualifier()->getAsType()->isEnumeralType())
547 return;
548 const auto *EnumConstDecl =
549 Result.Nodes.getNodeAs<EnumConstantDecl>("enum_const_decl");
550 assert(EnumConstDecl);
551 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
552 assert(Context && "Empty decl context.");
553 // FIXME: this would qualify "ns::VALUE" as "ns::EnumValue::VALUE". Fix it
554 // if it turns out to be an issue.
555 fixDeclRefExpr(Result, Context->getDeclContext(),
556 llvm::cast<NamedDecl>(EnumConstDecl), EnumConstRef);
Eric Liuda22b3c2016-11-29 14:15:14557 } else if (const auto *FuncRef =
558 Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) {
Eric Liue3f35e42016-12-20 14:39:04559 // If this reference has been processed as a function call, we do not
560 // process it again.
561 if (ProcessedFuncRefs.count(FuncRef))
562 return;
563 ProcessedFuncRefs.insert(FuncRef);
Eric Liuda22b3c2016-11-29 14:15:14564 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
565 assert(Func);
566 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
567 assert(Context && "Empty decl context.");
568 fixDeclRefExpr(Result, Context->getDeclContext(),
569 llvm::cast<NamedDecl>(Func), FuncRef);
Eric Liu12068d82016-09-22 11:54:00570 } else {
Eric Liuda22b3c2016-11-29 14:15:14571 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19572 assert(Call != nullptr && "Expecting callback for CallExpr.");
Eric Liue3f35e42016-12-20 14:39:04573 const auto *CalleeFuncRef =
574 llvm::cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit());
575 ProcessedFuncRefs.insert(CalleeFuncRef);
Eric Liuda22b3c2016-11-29 14:15:14576 const FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00577 assert(Func != nullptr);
Eric Liue3f35e42016-12-20 14:39:04578 // FIXME: ignore overloaded operators. This would miss cases where operators
579 // are called by qualified names (i.e. "ns::operator <"). Ignore such
580 // cases for now.
581 if (Func->isOverloadedOperator())
582 return;
Eric Liu12068d82016-09-22 11:54:00583 // Ignore out-of-line static methods since they will be handled by nested
584 // name specifiers.
585 if (Func->getCanonicalDecl()->getStorageClass() ==
Eric Liuda22b3c2016-11-29 14:15:14586 StorageClass::SC_Static &&
Eric Liu12068d82016-09-22 11:54:00587 Func->isOutOfLine())
588 return;
Eric Liuda22b3c2016-11-29 14:15:14589 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu12068d82016-09-22 11:54:00590 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14591 SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17592 replaceQualifiedSymbolInDeclContext(
593 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34594 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32595 }
596}
597
Eric Liu73f49fd2016-10-12 12:34:18598static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
599 const SourceManager &SM,
600 const LangOptions &LangOpts) {
601 std::unique_ptr<Lexer> Lex =
602 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
603 assert(Lex.get() &&
604 "Failed to create lexer from the beginning of namespace.");
605 if (!Lex.get())
606 return SourceLocation();
607 Token Tok;
608 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
609 }
610 return Tok.isNot(tok::TokenKind::l_brace)
611 ? SourceLocation()
612 : Tok.getEndLoc().getLocWithOffset(1);
613}
614
Eric Liu495b2112016-09-19 17:40:32615// Stores information about a moved namespace in `MoveNamespaces` and leaves
616// the actual movement to `onEndOfTranslationUnit()`.
617void ChangeNamespaceTool::moveOldNamespace(
618 const ast_matchers::MatchFinder::MatchResult &Result,
619 const NamespaceDecl *NsDecl) {
620 // If the namespace is empty, do nothing.
621 if (Decl::castToDeclContext(NsDecl)->decls_empty())
622 return;
623
Eric Liuee5104b2017-01-04 14:49:08624 const SourceManager &SM = *Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32625 // Get the range of the code in the old namespace.
Eric Liuee5104b2017-01-04 14:49:08626 SourceLocation Start =
627 getLocAfterNamespaceLBrace(NsDecl, SM, Result.Context->getLangOpts());
Eric Liu73f49fd2016-10-12 12:34:18628 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32629 MoveNamespace MoveNs;
Eric Liuee5104b2017-01-04 14:49:08630 MoveNs.Offset = SM.getFileOffset(Start);
631 // The range of the moved namespace is from the location just past the left
632 // brace to the location right before the right brace.
633 MoveNs.Length = SM.getFileOffset(NsDecl->getRBraceLoc()) - MoveNs.Offset;
Eric Liu495b2112016-09-19 17:40:32634
635 // Insert the new namespace after `DiffOldNamespace`. For example, if
636 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
637 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
638 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
639 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01640 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
641 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32642 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01643 SourceLocation InsertionLoc = Start;
644 if (OuterNs) {
Eric Liuee5104b2017-01-04 14:49:08645 SourceLocation LocAfterNs = getStartOfNextLine(
646 OuterNs->getRBraceLoc(), SM, Result.Context->getLangOpts());
Eric Liu6aa94162016-11-10 18:29:01647 assert(LocAfterNs.isValid() &&
648 "Failed to get location after DiffOldNamespace");
649 InsertionLoc = LocAfterNs;
650 }
Eric Liuee5104b2017-01-04 14:49:08651 MoveNs.InsertionOffset = SM.getFileOffset(SM.getSpellingLoc(InsertionLoc));
652 MoveNs.FID = SM.getFileID(Start);
Eric Liucc83c662016-09-19 17:58:59653 MoveNs.SourceMgr = Result.SourceManager;
Eric Liuee5104b2017-01-04 14:49:08654 MoveNamespaces[SM.getFilename(Start)].push_back(MoveNs);
Eric Liu495b2112016-09-19 17:40:32655}
656
657// Removes a class forward declaration from the code in the moved namespace and
658// creates an `InsertForwardDeclaration` to insert the forward declaration back
659// into the old namespace after moving code from the old namespace to the new
660// namespace.
661// For example, changing "a" to "x":
662// Old code:
663// namespace a {
664// class FWD;
665// class A { FWD *fwd; }
666// } // a
667// New code:
668// namespace a {
669// class FWD;
670// } // a
671// namespace x {
672// class A { a::FWD *fwd; }
673// } // x
674void ChangeNamespaceTool::moveClassForwardDeclaration(
675 const ast_matchers::MatchFinder::MatchResult &Result,
Eric Liu41552d62016-12-07 14:20:52676 const NamedDecl *FwdDecl) {
Eric Liu495b2112016-09-19 17:40:32677 SourceLocation Start = FwdDecl->getLocStart();
678 SourceLocation End = FwdDecl->getLocEnd();
679 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
680 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
681 /*SkipTrailingWhitespaceAndNewLine=*/true);
682 if (AfterSemi.isValid())
683 End = AfterSemi.getLocWithOffset(-1);
684 // Delete the forward declaration from the code to be moved.
Eric Liu4fe99e12016-12-14 17:01:52685 addReplacementOrDie(Start, End, "", *Result.SourceManager,
686 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32687 llvm::StringRef Code = Lexer::getSourceText(
688 CharSourceRange::getTokenRange(
689 Result.SourceManager->getSpellingLoc(Start),
690 Result.SourceManager->getSpellingLoc(End)),
691 *Result.SourceManager, Result.Context->getLangOpts());
692 // Insert the forward declaration back into the old namespace after moving the
693 // code from old namespace to new namespace.
694 // Insertion information is stored in `InsertFwdDecls` and actual
695 // insertion will be performed in `onEndOfTranslationUnit`.
696 // Get the (old) namespace that contains the forward declaration.
697 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
698 // The namespace contains the forward declaration, so it must not be empty.
699 assert(!NsDecl->decls_empty());
700 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
701 Code, *Result.SourceManager);
702 InsertForwardDeclaration InsertFwd;
703 InsertFwd.InsertionOffset = Insertion.getOffset();
704 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
705 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
706}
707
Eric Liub9bf1b52016-11-08 22:44:17708// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
709// FromDecl with the shortest qualified name possible when the reference is in
710// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32711void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17712 const ast_matchers::MatchFinder::MatchResult &Result,
713 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
714 const NamedDecl *FromDecl) {
715 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu4fe99e12016-12-14 17:01:52716 if (llvm::isa<TranslationUnitDecl>(NsDeclContext)) {
717 // This should not happen in usual unless the TypeLoc is in function type
718 // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of
719 // `T` will be the translation unit. We simply use fully-qualified name
720 // here.
721 // Note that `FromDecl` must not be defined in the old namespace (according
722 // to `DeclMatcher`), so its fully-qualified name will not change after
723 // changing the namespace.
724 addReplacementOrDie(Start, End, FromDecl->getQualifiedNameAsString(),
725 *Result.SourceManager, &FileToReplacements);
726 return;
727 }
Eric Liu231c6552016-11-10 18:15:34728 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32729 // Calculate the name of the `NsDecl` after it is moved to new namespace.
730 std::string OldNs = NsDecl->getQualifiedNameAsString();
731 llvm::StringRef Postfix = OldNs;
732 bool Consumed = Postfix.consume_front(OldNamespace);
733 assert(Consumed && "Expect OldNS to start with OldNamespace.");
734 (void)Consumed;
735 const std::string NewNs = (NewNamespace + Postfix).str();
736
737 llvm::StringRef NestedName = Lexer::getSourceText(
738 CharSourceRange::getTokenRange(
739 Result.SourceManager->getSpellingLoc(Start),
740 Result.SourceManager->getSpellingLoc(End)),
741 *Result.SourceManager, Result.Context->getLangOpts());
Eric Liub9bf1b52016-11-08 22:44:17742 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu7fccc992017-02-24 11:54:45743 for (llvm::Regex &RE : WhiteListedSymbolRegexes)
744 if (RE.match(FromDeclName))
745 return;
Eric Liu495b2112016-09-19 17:40:32746 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17747 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
748 // Checks if there is any using namespace declarations that can shorten the
749 // qualified name.
750 for (const auto *UsingNamespace : UsingNamespaceDecls) {
751 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
752 Start))
753 continue;
754 StringRef FromDeclNameRef = FromDeclName;
755 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
756 ->getQualifiedNameAsString())) {
757 FromDeclNameRef = FromDeclNameRef.drop_front(2);
758 if (FromDeclNameRef.size() < ReplaceName.size())
759 ReplaceName = FromDeclNameRef;
760 }
761 }
Eric Liu180dac62016-12-23 10:47:09762 // Checks if there is any namespace alias declarations that can shorten the
763 // qualified name.
764 for (const auto *NamespaceAlias : NamespaceAliasDecls) {
765 if (!isDeclVisibleAtLocation(*Result.SourceManager, NamespaceAlias, DeclCtx,
766 Start))
767 continue;
768 StringRef FromDeclNameRef = FromDeclName;
769 if (FromDeclNameRef.consume_front(
770 NamespaceAlias->getNamespace()->getQualifiedNameAsString() +
771 "::")) {
772 std::string AliasName = NamespaceAlias->getNameAsString();
773 std::string AliasQualifiedName =
774 NamespaceAlias->getQualifiedNameAsString();
775 // We only consider namespace aliases define in the global namepspace or
776 // in namespaces that are directly visible from the reference, i.e.
777 // ancestor of the `OldNs`. Note that declarations in ancestor namespaces
778 // but not visible in the new namespace is filtered out by
779 // "IsVisibleInNewNs" matcher.
780 if (AliasQualifiedName != AliasName) {
781 // The alias is defined in some namespace.
782 assert(StringRef(AliasQualifiedName).endswith("::" + AliasName));
783 llvm::StringRef AliasNs =
784 StringRef(AliasQualifiedName).drop_back(AliasName.size() + 2);
785 if (!llvm::StringRef(OldNs).startswith(AliasNs))
786 continue;
787 }
788 std::string NameWithAliasNamespace =
789 (AliasName + "::" + FromDeclNameRef).str();
790 if (NameWithAliasNamespace.size() < ReplaceName.size())
791 ReplaceName = NameWithAliasNamespace;
792 }
793 }
Eric Liub9bf1b52016-11-08 22:44:17794 // Checks if there is any using shadow declarations that can shorten the
795 // qualified name.
796 bool Matched = false;
797 for (const UsingDecl *Using : UsingDecls) {
798 if (Matched)
799 break;
800 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
801 for (const auto *UsingShadow : Using->shadows()) {
802 const auto *TargetDecl = UsingShadow->getTargetDecl();
Eric Liuae7de712017-02-02 15:29:54803 if (TargetDecl->getQualifiedNameAsString() ==
804 FromDecl->getQualifiedNameAsString()) {
Eric Liub9bf1b52016-11-08 22:44:17805 ReplaceName = FromDecl->getNameAsString();
806 Matched = true;
807 break;
808 }
809 }
810 }
811 }
Eric Liu495b2112016-09-19 17:40:32812 // If the new nested name in the new namespace is the same as it was in the
813 // old namespace, we don't create replacement.
Eric Liu91229162017-01-26 16:31:32814 if (NestedName == ReplaceName ||
815 (NestedName.startswith("::") && NestedName.drop_front(2) == ReplaceName))
Eric Liu495b2112016-09-19 17:40:32816 return;
Eric Liu97f87ad2016-12-07 20:08:02817 // If the reference need to be fully-qualified, add a leading "::" unless
818 // NewNamespace is the global namespace.
819 if (ReplaceName == FromDeclName && !NewNamespace.empty())
820 ReplaceName = "::" + ReplaceName;
Eric Liu4fe99e12016-12-14 17:01:52821 addReplacementOrDie(Start, End, ReplaceName, *Result.SourceManager,
822 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32823}
824
825// Replace the [Start, End] of `Type` with the shortest qualified name when the
826// `Type` is in `NewNamespace`.
827void ChangeNamespaceTool::fixTypeLoc(
828 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
829 SourceLocation End, TypeLoc Type) {
830 // FIXME: do not rename template parameter.
831 if (Start.isInvalid() || End.isInvalid())
832 return;
Eric Liuff51f012016-11-16 16:54:53833 // Types of CXXCtorInitializers do not need to be fixed.
834 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
835 return;
Eric Liu495b2112016-09-19 17:40:32836 // The declaration which this TypeLoc refers to.
837 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
838 // `hasDeclaration` gives underlying declaration, but if the type is
839 // a typedef type, we need to use the typedef type instead.
Eric Liu26cf68a2016-12-15 10:42:35840 auto IsInMovedNs = [&](const NamedDecl *D) {
841 if (!llvm::StringRef(D->getQualifiedNameAsString())
842 .startswith(OldNamespace + "::"))
843 return false;
844 auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getLocStart());
845 if (ExpansionLoc.isInvalid())
846 return false;
847 llvm::StringRef Filename = Result.SourceManager->getFilename(ExpansionLoc);
848 return FilePatternRE.match(Filename);
849 };
850 // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if
851 // `Type` is an alias type, we make `FromDecl` the type alias declaration.
852 // Also, don't fix the \p Type if it refers to a type alias decl in the moved
853 // namespace since the alias decl will be moved along with the type reference.
Eric Liu32158862016-11-14 19:37:55854 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32855 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55856 if (IsInMovedNs(FromDecl))
857 return;
Eric Liu26cf68a2016-12-15 10:42:35858 } else if (auto *TemplateType =
859 Type.getType()->getAs<TemplateSpecializationType>()) {
860 if (TemplateType->isTypeAlias()) {
861 FromDecl = TemplateType->getTemplateName().getAsTemplateDecl();
862 if (IsInMovedNs(FromDecl))
863 return;
864 }
Eric Liu32158862016-11-14 19:37:55865 }
Piotr Padlewski08124b12016-12-14 15:29:23866 const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu495b2112016-09-19 17:40:32867 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17868 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
869 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32870}
871
Eric Liu68765a82016-09-21 15:06:12872void ChangeNamespaceTool::fixUsingShadowDecl(
873 const ast_matchers::MatchFinder::MatchResult &Result,
874 const UsingDecl *UsingDeclaration) {
875 SourceLocation Start = UsingDeclaration->getLocStart();
876 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19877 if (Start.isInvalid() || End.isInvalid())
878 return;
Eric Liu68765a82016-09-21 15:06:12879
880 assert(UsingDeclaration->shadow_size() > 0);
881 // FIXME: it might not be always accurate to use the first using-decl.
882 const NamedDecl *TargetDecl =
883 UsingDeclaration->shadow_begin()->getTargetDecl();
884 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
885 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
886 // sense. If this happens, we need to use name with the new namespace.
887 // Use fully qualified name in UsingDecl for now.
Eric Liu4fe99e12016-12-14 17:01:52888 addReplacementOrDie(Start, End, "using ::" + TargetDeclName,
889 *Result.SourceManager, &FileToReplacements);
Eric Liu68765a82016-09-21 15:06:12890}
891
Eric Liuda22b3c2016-11-29 14:15:14892void ChangeNamespaceTool::fixDeclRefExpr(
893 const ast_matchers::MatchFinder::MatchResult &Result,
894 const DeclContext *UseContext, const NamedDecl *From,
895 const DeclRefExpr *Ref) {
896 SourceRange RefRange = Ref->getSourceRange();
897 replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(),
898 RefRange.getEnd(), From);
899}
900
Eric Liu495b2112016-09-19 17:40:32901void ChangeNamespaceTool::onEndOfTranslationUnit() {
902 // Move namespace blocks and insert forward declaration to old namespace.
903 for (const auto &FileAndNsMoves : MoveNamespaces) {
904 auto &NsMoves = FileAndNsMoves.second;
905 if (NsMoves.empty())
906 continue;
907 const std::string &FilePath = FileAndNsMoves.first;
908 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59909 auto &SM = *NsMoves.begin()->SourceMgr;
910 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32911 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
912 if (!ChangedCode) {
913 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
914 continue;
915 }
916 // Replacements on the changed code for moving namespaces and inserting
917 // forward declarations to old namespaces.
918 tooling::Replacements NewReplacements;
919 // Cut the changed code from the old namespace and paste the code in the new
920 // namespace.
921 for (const auto &NsMove : NsMoves) {
922 // Calculate the range of the old namespace block in the changed
923 // code.
924 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
925 const unsigned NewLength =
926 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
927 NewOffset;
928 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
929 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
930 std::string MovedCodeWrappedInNewNs =
931 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
932 // Calculate the new offset at which the code will be inserted in the
933 // changed code.
934 unsigned NewInsertionOffset =
935 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
936 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
937 MovedCodeWrappedInNewNs);
938 addOrMergeReplacement(Deletion, &NewReplacements);
939 addOrMergeReplacement(Insertion, &NewReplacements);
940 }
941 // After moving namespaces, insert forward declarations back to old
942 // namespaces.
943 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
944 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
945 unsigned NewInsertionOffset =
946 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
947 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
948 FwdDeclInsertion.ForwardDeclText);
949 addOrMergeReplacement(Insertion, &NewReplacements);
950 }
951 // Add replacements referring to the changed code to existing replacements,
952 // which refers to the original code.
953 Replaces = Replaces.merge(NewReplacements);
Antonio Maiorano0d7d9c22017-01-17 00:13:32954 auto Style = format::getStyle("file", FilePath, FallbackStyle);
955 if (!Style) {
956 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
957 continue;
958 }
Eric Liu495b2112016-09-19 17:40:32959 // Clean up old namespaces if there is nothing in it after moving.
960 auto CleanReplacements =
Antonio Maiorano0d7d9c22017-01-17 00:13:32961 format::cleanupAroundReplacements(Code, Replaces, *Style);
Eric Liu495b2112016-09-19 17:40:32962 if (!CleanReplacements) {
963 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
964 continue;
965 }
966 FileToReplacements[FilePath] = *CleanReplacements;
967 }
Eric Liuc265b022016-12-01 17:25:55968
969 // Make sure we don't generate replacements for files that do not match
970 // FilePattern.
971 for (auto &Entry : FileToReplacements)
972 if (!FilePatternRE.match(Entry.first))
973 Entry.second.clear();
Eric Liu495b2112016-09-19 17:40:32974}
975
976} // namespace change_namespace
977} // namespace clang