blob: 728aa2b8bc229f7be36daefe6a848aa5a3b28eed [file] [log] [blame]
Eric Liu495b2112016-09-19 17:40:32 +00001//===-- ChangeNamespace.cpp - Change namespace implementation -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "ChangeNamespace.h"
10#include "clang/Format/Format.h"
11#include "clang/Lex/Lexer.h"
Eric Liuff51f012016-11-16 16:54:53 +000012#include "llvm/Support/ErrorHandling.h"
Eric Liu495b2112016-09-19 17:40:32 +000013
14using namespace clang::ast_matchers;
15
16namespace clang {
17namespace change_namespace {
18
19namespace {
20
21inline std::string
22joinNamespaces(const llvm::SmallVectorImpl<StringRef> &Namespaces) {
23 if (Namespaces.empty())
24 return "";
25 std::string Result = Namespaces.front();
26 for (auto I = Namespaces.begin() + 1, E = Namespaces.end(); I != E; ++I)
27 Result += ("::" + *I).str();
28 return Result;
29}
30
31SourceLocation startLocationForType(TypeLoc TLoc) {
32 // For elaborated types (e.g. `struct a::A`) we want the portion after the
33 // `struct` but including the namespace qualifier, `a::`.
34 if (TLoc.getTypeLocClass() == TypeLoc::Elaborated) {
35 NestedNameSpecifierLoc NestedNameSpecifier =
36 TLoc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
37 if (NestedNameSpecifier.getNestedNameSpecifier())
38 return NestedNameSpecifier.getBeginLoc();
39 TLoc = TLoc.getNextTypeLoc();
40 }
41 return TLoc.getLocStart();
42}
43
Eric Liuc265b022016-12-01 17:25:55 +000044SourceLocation endLocationForType(TypeLoc TLoc) {
Eric Liu495b2112016-09-19 17:40:32 +000045 // Dig past any namespace or keyword qualifications.
46 while (TLoc.getTypeLocClass() == TypeLoc::Elaborated ||
47 TLoc.getTypeLocClass() == TypeLoc::Qualified)
48 TLoc = TLoc.getNextTypeLoc();
49
50 // The location for template specializations (e.g. Foo<int>) includes the
51 // templated types in its location range. We want to restrict this to just
52 // before the `<` character.
53 if (TLoc.getTypeLocClass() == TypeLoc::TemplateSpecialization)
54 return TLoc.castAs<TemplateSpecializationTypeLoc>()
55 .getLAngleLoc()
56 .getLocWithOffset(-1);
57 return TLoc.getEndLoc();
58}
59
60// Returns the containing namespace of `InnerNs` by skipping `PartialNsName`.
Eric Liu6aa94162016-11-10 18:29:01 +000061// If the `InnerNs` does not have `PartialNsName` as suffix, or `PartialNsName`
62// is empty, nullptr is returned.
Eric Liu495b2112016-09-19 17:40:32 +000063// For example, if `InnerNs` is "a::b::c" and `PartialNsName` is "b::c", then
64// the NamespaceDecl of namespace "a" will be returned.
65const NamespaceDecl *getOuterNamespace(const NamespaceDecl *InnerNs,
66 llvm::StringRef PartialNsName) {
Eric Liu6aa94162016-11-10 18:29:01 +000067 if (!InnerNs || PartialNsName.empty())
68 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +000069 const auto *CurrentContext = llvm::cast<DeclContext>(InnerNs);
70 const auto *CurrentNs = InnerNs;
71 llvm::SmallVector<llvm::StringRef, 4> PartialNsNameSplitted;
Eric Liu6aa94162016-11-10 18:29:01 +000072 PartialNsName.split(PartialNsNameSplitted, "::", /*MaxSplit=*/-1,
73 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32 +000074 while (!PartialNsNameSplitted.empty()) {
75 // Get the inner-most namespace in CurrentContext.
76 while (CurrentContext && !llvm::isa<NamespaceDecl>(CurrentContext))
77 CurrentContext = CurrentContext->getParent();
78 if (!CurrentContext)
79 return nullptr;
80 CurrentNs = llvm::cast<NamespaceDecl>(CurrentContext);
81 if (PartialNsNameSplitted.back() != CurrentNs->getNameAsString())
82 return nullptr;
83 PartialNsNameSplitted.pop_back();
84 CurrentContext = CurrentContext->getParent();
85 }
86 return CurrentNs;
87}
88
Eric Liu73f49fd2016-10-12 12:34:18 +000089static std::unique_ptr<Lexer>
90getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM,
91 const LangOptions &LangOpts) {
Eric Liu495b2112016-09-19 17:40:32 +000092 if (Loc.isMacroID() &&
93 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eric Liu73f49fd2016-10-12 12:34:18 +000094 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +000095 // Break down the source location.
96 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
97 // Try to load the file buffer.
98 bool InvalidTemp = false;
99 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
100 if (InvalidTemp)
Eric Liu73f49fd2016-10-12 12:34:18 +0000101 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +0000102
103 const char *TokBegin = File.data() + LocInfo.second;
104 // Lex from the start of the given location.
Eric Liu73f49fd2016-10-12 12:34:18 +0000105 return llvm::make_unique<Lexer>(SM.getLocForStartOfFile(LocInfo.first),
106 LangOpts, File.begin(), TokBegin, File.end());
107}
Eric Liu495b2112016-09-19 17:40:32 +0000108
Eric Liu73f49fd2016-10-12 12:34:18 +0000109// FIXME: get rid of this helper function if this is supported in clang-refactor
110// library.
111static SourceLocation getStartOfNextLine(SourceLocation Loc,
112 const SourceManager &SM,
113 const LangOptions &LangOpts) {
114 std::unique_ptr<Lexer> Lex = getLexerStartingFromLoc(Loc, SM, LangOpts);
115 if (!Lex.get())
116 return SourceLocation();
Eric Liu495b2112016-09-19 17:40:32 +0000117 llvm::SmallVector<char, 16> Line;
118 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
Eric Liu73f49fd2016-10-12 12:34:18 +0000119 Lex->setParsingPreprocessorDirective(true);
120 Lex->ReadToEndOfLine(&Line);
Haojian Wuef8a6dc2016-10-04 10:35:53 +0000121 auto End = Loc.getLocWithOffset(Line.size());
Eric Liu73f49fd2016-10-12 12:34:18 +0000122 return SM.getLocForEndOfFile(SM.getDecomposedLoc(Loc).first) == End
123 ? End
124 : End.getLocWithOffset(1);
Eric Liu495b2112016-09-19 17:40:32 +0000125}
126
127// Returns `R` with new range that refers to code after `Replaces` being
128// applied.
129tooling::Replacement
130getReplacementInChangedCode(const tooling::Replacements &Replaces,
131 const tooling::Replacement &R) {
132 unsigned NewStart = Replaces.getShiftedCodePosition(R.getOffset());
133 unsigned NewEnd =
134 Replaces.getShiftedCodePosition(R.getOffset() + R.getLength());
135 return tooling::Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
136 R.getReplacementText());
137}
138
139// Adds a replacement `R` into `Replaces` or merges it into `Replaces` by
140// applying all existing Replaces first if there is conflict.
141void addOrMergeReplacement(const tooling::Replacement &R,
142 tooling::Replacements *Replaces) {
143 auto Err = Replaces->add(R);
144 if (Err) {
145 llvm::consumeError(std::move(Err));
146 auto Replace = getReplacementInChangedCode(*Replaces, R);
147 *Replaces = Replaces->merge(tooling::Replacements(Replace));
148 }
149}
150
151tooling::Replacement createReplacement(SourceLocation Start, SourceLocation End,
152 llvm::StringRef ReplacementText,
153 const SourceManager &SM) {
154 if (!Start.isValid() || !End.isValid()) {
155 llvm::errs() << "start or end location were invalid\n";
156 return tooling::Replacement();
157 }
158 if (SM.getDecomposedLoc(Start).first != SM.getDecomposedLoc(End).first) {
159 llvm::errs()
160 << "start or end location were in different macro expansions\n";
161 return tooling::Replacement();
162 }
163 Start = SM.getSpellingLoc(Start);
164 End = SM.getSpellingLoc(End);
165 if (SM.getFileID(Start) != SM.getFileID(End)) {
166 llvm::errs() << "start or end location were in different files\n";
167 return tooling::Replacement();
168 }
169 return tooling::Replacement(
170 SM, CharSourceRange::getTokenRange(SM.getSpellingLoc(Start),
171 SM.getSpellingLoc(End)),
172 ReplacementText);
173}
174
Eric Liu4fe99e12016-12-14 17:01:52 +0000175void addReplacementOrDie(
176 SourceLocation Start, SourceLocation End, llvm::StringRef ReplacementText,
177 const SourceManager &SM,
178 std::map<std::string, tooling::Replacements> *FileToReplacements) {
179 const auto R = createReplacement(Start, End, ReplacementText, SM);
180 auto Err = (*FileToReplacements)[R.getFilePath()].add(R);
181 if (Err)
182 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
183}
184
Eric Liu495b2112016-09-19 17:40:32 +0000185tooling::Replacement createInsertion(SourceLocation Loc,
186 llvm::StringRef InsertText,
187 const SourceManager &SM) {
188 if (Loc.isInvalid()) {
189 llvm::errs() << "insert Location is invalid.\n";
190 return tooling::Replacement();
191 }
192 Loc = SM.getSpellingLoc(Loc);
193 return tooling::Replacement(SM, Loc, 0, InsertText);
194}
195
196// Returns the shortest qualified name for declaration `DeclName` in the
197// namespace `NsName`. For example, if `DeclName` is "a::b::X" and `NsName`
198// is "a::c::d", then "b::X" will be returned.
Eric Liubc715502017-01-26 15:08:44 +0000199// 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:39 +0000201// \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:32 +0000204std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
205 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39 +0000206 DeclName = DeclName.ltrim(':');
207 NsName = NsName.ltrim(':');
Eric Liu447164d2016-10-05 15:52:39 +0000208 if (DeclName.find(':') == llvm::StringRef::npos)
Eric Liub9bf1b52016-11-08 22:44:17 +0000209 return DeclName;
Eric Liu447164d2016-10-05 15:52:39 +0000210
Eric Liubc715502017-01-26 15:08:44 +0000211 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:32 +0000234 }
Eric Liubc715502017-01-26 15:08:44 +0000235 // 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:32 +0000247}
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:04 +0000253 NestedNs.split(NsSplitted, "::", /*MaxSplit=*/-1,
254 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32 +0000255 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:17 +0000265// 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) {
278 SourceLocation DeclLoc = SM.getSpellingLoc(D->getLocation());
279 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 Liu495b2112016-09-19 17:40:32 +0000285} // anonymous namespace
286
287ChangeNamespaceTool::ChangeNamespaceTool(
288 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
289 std::map<std::string, tooling::Replacements> *FileToReplacements,
290 llvm::StringRef FallbackStyle)
291 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
292 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
Eric Liuc265b022016-12-01 17:25:55 +0000293 FilePattern(FilePattern), FilePatternRE(FilePattern) {
Eric Liu495b2112016-09-19 17:40:32 +0000294 FileToReplacements->clear();
295 llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted;
296 llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted;
297 llvm::StringRef(OldNamespace).split(OldNsSplitted, "::");
298 llvm::StringRef(NewNamespace).split(NewNsSplitted, "::");
299 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
300 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
301 OldNsSplitted.front() == NewNsSplitted.front()) {
302 OldNsSplitted.erase(OldNsSplitted.begin());
303 NewNsSplitted.erase(NewNsSplitted.begin());
304 }
305 DiffOldNamespace = joinNamespaces(OldNsSplitted);
306 DiffNewNamespace = joinNamespaces(NewNsSplitted);
307}
308
Eric Liu495b2112016-09-19 17:40:32 +0000309void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32 +0000310 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17 +0000311 // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the
312 // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will
313 // be "a::b". Declarations in this namespace will not be visible in the new
314 // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-".
315 llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04 +0000316 llvm::StringRef(DiffOldNamespace)
317 .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1,
318 /*KeepEmpty=*/false);
Eric Liub9bf1b52016-11-08 22:44:17 +0000319 std::string Prefix = "-";
320 if (!DiffOldNsSplitted.empty())
321 Prefix = (StringRef(FullOldNs).drop_back(DiffOldNamespace.size()) +
322 DiffOldNsSplitted.front())
323 .str();
324 auto IsInMovedNs =
325 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
326 isExpansionInFileMatching(FilePattern));
327 auto IsVisibleInNewNs = anyOf(
328 IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Prefix)))));
329 // Match using declarations.
330 Finder->addMatcher(
331 usingDecl(isExpansionInFileMatching(FilePattern), IsVisibleInNewNs)
332 .bind("using"),
333 this);
334 // Match using namespace declarations.
335 Finder->addMatcher(usingDirectiveDecl(isExpansionInFileMatching(FilePattern),
336 IsVisibleInNewNs)
337 .bind("using_namespace"),
338 this);
Eric Liu180dac62016-12-23 10:47:09 +0000339 // Match namespace alias declarations.
340 Finder->addMatcher(namespaceAliasDecl(isExpansionInFileMatching(FilePattern),
341 IsVisibleInNewNs)
342 .bind("namespace_alias"),
343 this);
Eric Liub9bf1b52016-11-08 22:44:17 +0000344
345 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32 +0000346 Finder->addMatcher(
347 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
348 .bind("old_ns"),
349 this);
350
Eric Liu41552d62016-12-07 14:20:52 +0000351 // Match class forward-declarations in the old namespace.
352 // Note that forward-declarations in classes are not matched.
353 Finder->addMatcher(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())),
354 IsInMovedNs, hasParent(namespaceDecl()))
355 .bind("class_fwd_decl"),
356 this);
357
358 // Match template class forward-declarations in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000359 Finder->addMatcher(
Eric Liu41552d62016-12-07 14:20:52 +0000360 classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))),
361 IsInMovedNs, hasParent(namespaceDecl()))
362 .bind("template_class_fwd_decl"),
Eric Liu495b2112016-09-19 17:40:32 +0000363 this);
364
365 // Match references to types that are not defined in the old namespace.
366 // Forward-declarations in the old namespace are also matched since they will
367 // be moved back to the old namespace.
368 auto DeclMatcher = namedDecl(
369 hasAncestor(namespaceDecl()),
370 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48 +0000371 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32 +0000372 hasAncestor(cxxRecordDecl()),
373 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48 +0000374
Eric Liu8685c762016-12-07 17:04:07 +0000375 // Using shadow declarations in classes always refers to base class, which
376 // does not need to be qualified since it can be inferred from inheritance.
377 // Note that this does not match using alias declarations.
378 auto UsingShadowDeclInClass =
379 usingDecl(hasAnyUsingShadowDecl(decl()), hasParent(cxxRecordDecl()));
380
Eric Liu495b2112016-09-19 17:40:32 +0000381 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29 +0000382 // TypeLoc and template specialization arguments (which are not outermost)
383 // that are directly linked to types matching `DeclMatcher`. Nested name
384 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32 +0000385 Finder->addMatcher(
386 typeLoc(IsInMovedNs,
387 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29 +0000388 unless(anyOf(hasParent(typeLoc(loc(qualType(
389 allOf(hasDeclaration(DeclMatcher),
390 unless(templateSpecializationType())))))),
Eric Liu8685c762016-12-07 17:04:07 +0000391 hasParent(nestedNameSpecifierLoc()),
392 hasAncestor(isImplicit()),
393 hasAncestor(UsingShadowDeclInClass))),
Eric Liu495b2112016-09-19 17:40:32 +0000394 hasAncestor(decl().bind("dc")))
395 .bind("type"),
396 this);
Eric Liu912d0392016-09-27 12:54:48 +0000397
Eric Liu68765a82016-09-21 15:06:12 +0000398 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
399 // special case it.
Eric Liu8685c762016-12-07 17:04:07 +0000400 // Since using declarations inside classes must have the base class in the
401 // nested name specifier, we leave it to the nested name specifier matcher.
402 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()),
403 unless(UsingShadowDeclInClass))
Eric Liub9bf1b52016-11-08 22:44:17 +0000404 .bind("using_with_shadow"),
405 this);
Eric Liu912d0392016-09-27 12:54:48 +0000406
Eric Liuff51f012016-11-16 16:54:53 +0000407 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
408 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
409 // "A::A" would have already been fixed.
Eric Liu8685c762016-12-07 17:04:07 +0000410 Finder->addMatcher(
411 nestedNameSpecifierLoc(
412 hasAncestor(decl(IsInMovedNs).bind("dc")),
413 loc(nestedNameSpecifier(
414 specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
415 unless(anyOf(hasAncestor(isImplicit()),
416 hasAncestor(UsingShadowDeclInClass),
417 hasAncestor(typeLoc(loc(qualType(hasDeclaration(
418 decl(equalsBoundNode("from_decl"))))))))))
419 .bind("nested_specifier_loc"),
420 this);
Eric Liu12068d82016-09-22 11:54:00 +0000421
Eric Liuff51f012016-11-16 16:54:53 +0000422 // Matches base class initializers in constructors. TypeLocs of base class
423 // initializers do not need to be fixed. For example,
424 // class X : public a::b::Y {
425 // public:
426 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
427 // };
428 Finder->addMatcher(
429 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
430
Eric Liu12068d82016-09-22 11:54:00 +0000431 // Handle function.
Eric Liu912d0392016-09-27 12:54:48 +0000432 // Only handle functions that are defined in a namespace excluding member
433 // function, static methods (qualified by nested specifier), and functions
434 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00 +0000435 // Note that the matcher does not exclude calls to out-of-line static method
436 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48 +0000437 auto FuncMatcher =
438 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
439 hasAncestor(namespaceDecl(isAnonymous())),
440 hasAncestor(cxxRecordDecl()))),
441 hasParent(namespaceDecl()));
Eric Liuda22b3c2016-11-29 14:15:14 +0000442 Finder->addMatcher(decl(forEachDescendant(expr(anyOf(
443 callExpr(callee(FuncMatcher)).bind("call"),
444 declRefExpr(to(FuncMatcher.bind("func_decl")))
445 .bind("func_ref")))),
446 IsInMovedNs, unless(isImplicit()))
447 .bind("dc"),
448 this);
Eric Liu159f0132016-09-30 04:32:39 +0000449
450 auto GlobalVarMatcher = varDecl(
451 hasGlobalStorage(), hasParent(namespaceDecl()),
452 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
453 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
454 to(GlobalVarMatcher.bind("var_decl")))
455 .bind("var_ref"),
456 this);
Eric Liu495b2112016-09-19 17:40:32 +0000457}
458
459void ChangeNamespaceTool::run(
460 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17 +0000461 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
462 UsingDecls.insert(Using);
463 } else if (const auto *UsingNamespace =
464 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
465 "using_namespace")) {
466 UsingNamespaceDecls.insert(UsingNamespace);
Eric Liu180dac62016-12-23 10:47:09 +0000467 } else if (const auto *NamespaceAlias =
468 Result.Nodes.getNodeAs<NamespaceAliasDecl>(
469 "namespace_alias")) {
470 NamespaceAliasDecls.insert(NamespaceAlias);
Eric Liub9bf1b52016-11-08 22:44:17 +0000471 } else if (const auto *NsDecl =
472 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32 +0000473 moveOldNamespace(Result, NsDecl);
474 } else if (const auto *FwdDecl =
Eric Liu41552d62016-12-07 14:20:52 +0000475 Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) {
476 moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl));
477 } else if (const auto *TemplateFwdDecl =
478 Result.Nodes.getNodeAs<ClassTemplateDecl>(
479 "template_class_fwd_decl")) {
480 moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl));
Eric Liub9bf1b52016-11-08 22:44:17 +0000481 } else if (const auto *UsingWithShadow =
482 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
483 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12 +0000484 } else if (const auto *Specifier =
485 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
486 "nested_specifier_loc")) {
487 SourceLocation Start = Specifier->getBeginLoc();
Eric Liuc265b022016-12-01 17:25:55 +0000488 SourceLocation End = endLocationForType(Specifier->getTypeLoc());
Eric Liu68765a82016-09-21 15:06:12 +0000489 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53 +0000490 } else if (const auto *BaseInitializer =
491 Result.Nodes.getNodeAs<CXXCtorInitializer>(
492 "base_initializer")) {
493 BaseCtorInitializerTypeLocs.push_back(
494 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00 +0000495 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu26cf68a2016-12-15 10:42:35 +0000496 // This avoids fixing types with record types as qualifier, which is not
497 // filtered by matchers in some cases, e.g. the type is templated. We should
498 // handle the record type qualifier instead.
Eric Liu0c0aea02016-12-15 13:02:41 +0000499 TypeLoc Loc = *TLoc;
500 while (Loc.getTypeLocClass() == TypeLoc::Qualified)
501 Loc = Loc.getNextTypeLoc();
502 if (Loc.getTypeLocClass() == TypeLoc::Elaborated) {
Eric Liu26cf68a2016-12-15 10:42:35 +0000503 NestedNameSpecifierLoc NestedNameSpecifier =
Eric Liu0c0aea02016-12-15 13:02:41 +0000504 Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
Eric Liu26cf68a2016-12-15 10:42:35 +0000505 const Type *SpecifierType =
506 NestedNameSpecifier.getNestedNameSpecifier()->getAsType();
507 if (SpecifierType && SpecifierType->isRecordType())
508 return;
509 }
Eric Liu0c0aea02016-12-15 13:02:41 +0000510 fixTypeLoc(Result, startLocationForType(Loc), endLocationForType(Loc), Loc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000511 } else if (const auto *VarRef =
512 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39 +0000513 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
514 assert(Var);
515 if (Var->getCanonicalDecl()->isStaticDataMember())
516 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000517 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu159f0132016-09-30 04:32:39 +0000518 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000519 fixDeclRefExpr(Result, Context->getDeclContext(),
520 llvm::cast<NamedDecl>(Var), VarRef);
521 } else if (const auto *FuncRef =
522 Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) {
Eric Liue3f35e42016-12-20 14:39:04 +0000523 // If this reference has been processed as a function call, we do not
524 // process it again.
525 if (ProcessedFuncRefs.count(FuncRef))
526 return;
527 ProcessedFuncRefs.insert(FuncRef);
Eric Liuda22b3c2016-11-29 14:15:14 +0000528 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
529 assert(Func);
530 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
531 assert(Context && "Empty decl context.");
532 fixDeclRefExpr(Result, Context->getDeclContext(),
533 llvm::cast<NamedDecl>(Func), FuncRef);
Eric Liu12068d82016-09-22 11:54:00 +0000534 } else {
Eric Liuda22b3c2016-11-29 14:15:14 +0000535 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000536 assert(Call != nullptr && "Expecting callback for CallExpr.");
Eric Liue3f35e42016-12-20 14:39:04 +0000537 const auto *CalleeFuncRef =
538 llvm::cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit());
539 ProcessedFuncRefs.insert(CalleeFuncRef);
Eric Liuda22b3c2016-11-29 14:15:14 +0000540 const FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00 +0000541 assert(Func != nullptr);
Eric Liue3f35e42016-12-20 14:39:04 +0000542 // FIXME: ignore overloaded operators. This would miss cases where operators
543 // are called by qualified names (i.e. "ns::operator <"). Ignore such
544 // cases for now.
545 if (Func->isOverloadedOperator())
546 return;
Eric Liu12068d82016-09-22 11:54:00 +0000547 // Ignore out-of-line static methods since they will be handled by nested
548 // name specifiers.
549 if (Func->getCanonicalDecl()->getStorageClass() ==
Eric Liuda22b3c2016-11-29 14:15:14 +0000550 StorageClass::SC_Static &&
Eric Liu12068d82016-09-22 11:54:00 +0000551 Func->isOutOfLine())
552 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000553 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu12068d82016-09-22 11:54:00 +0000554 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000555 SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17 +0000556 replaceQualifiedSymbolInDeclContext(
557 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34 +0000558 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32 +0000559 }
560}
561
Eric Liu73f49fd2016-10-12 12:34:18 +0000562static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
563 const SourceManager &SM,
564 const LangOptions &LangOpts) {
565 std::unique_ptr<Lexer> Lex =
566 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
567 assert(Lex.get() &&
568 "Failed to create lexer from the beginning of namespace.");
569 if (!Lex.get())
570 return SourceLocation();
571 Token Tok;
572 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
573 }
574 return Tok.isNot(tok::TokenKind::l_brace)
575 ? SourceLocation()
576 : Tok.getEndLoc().getLocWithOffset(1);
577}
578
Eric Liu495b2112016-09-19 17:40:32 +0000579// Stores information about a moved namespace in `MoveNamespaces` and leaves
580// the actual movement to `onEndOfTranslationUnit()`.
581void ChangeNamespaceTool::moveOldNamespace(
582 const ast_matchers::MatchFinder::MatchResult &Result,
583 const NamespaceDecl *NsDecl) {
584 // If the namespace is empty, do nothing.
585 if (Decl::castToDeclContext(NsDecl)->decls_empty())
586 return;
587
Eric Liuee5104b2017-01-04 14:49:08 +0000588 const SourceManager &SM = *Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32 +0000589 // Get the range of the code in the old namespace.
Eric Liuee5104b2017-01-04 14:49:08 +0000590 SourceLocation Start =
591 getLocAfterNamespaceLBrace(NsDecl, SM, Result.Context->getLangOpts());
Eric Liu73f49fd2016-10-12 12:34:18 +0000592 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32 +0000593 MoveNamespace MoveNs;
Eric Liuee5104b2017-01-04 14:49:08 +0000594 MoveNs.Offset = SM.getFileOffset(Start);
595 // The range of the moved namespace is from the location just past the left
596 // brace to the location right before the right brace.
597 MoveNs.Length = SM.getFileOffset(NsDecl->getRBraceLoc()) - MoveNs.Offset;
Eric Liu495b2112016-09-19 17:40:32 +0000598
599 // Insert the new namespace after `DiffOldNamespace`. For example, if
600 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
601 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
602 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
603 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01 +0000604 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
605 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000606 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01 +0000607 SourceLocation InsertionLoc = Start;
608 if (OuterNs) {
Eric Liuee5104b2017-01-04 14:49:08 +0000609 SourceLocation LocAfterNs = getStartOfNextLine(
610 OuterNs->getRBraceLoc(), SM, Result.Context->getLangOpts());
Eric Liu6aa94162016-11-10 18:29:01 +0000611 assert(LocAfterNs.isValid() &&
612 "Failed to get location after DiffOldNamespace");
613 InsertionLoc = LocAfterNs;
614 }
Eric Liuee5104b2017-01-04 14:49:08 +0000615 MoveNs.InsertionOffset = SM.getFileOffset(SM.getSpellingLoc(InsertionLoc));
616 MoveNs.FID = SM.getFileID(Start);
Eric Liucc83c662016-09-19 17:58:59 +0000617 MoveNs.SourceMgr = Result.SourceManager;
Eric Liuee5104b2017-01-04 14:49:08 +0000618 MoveNamespaces[SM.getFilename(Start)].push_back(MoveNs);
Eric Liu495b2112016-09-19 17:40:32 +0000619}
620
621// Removes a class forward declaration from the code in the moved namespace and
622// creates an `InsertForwardDeclaration` to insert the forward declaration back
623// into the old namespace after moving code from the old namespace to the new
624// namespace.
625// For example, changing "a" to "x":
626// Old code:
627// namespace a {
628// class FWD;
629// class A { FWD *fwd; }
630// } // a
631// New code:
632// namespace a {
633// class FWD;
634// } // a
635// namespace x {
636// class A { a::FWD *fwd; }
637// } // x
638void ChangeNamespaceTool::moveClassForwardDeclaration(
639 const ast_matchers::MatchFinder::MatchResult &Result,
Eric Liu41552d62016-12-07 14:20:52 +0000640 const NamedDecl *FwdDecl) {
Eric Liu495b2112016-09-19 17:40:32 +0000641 SourceLocation Start = FwdDecl->getLocStart();
642 SourceLocation End = FwdDecl->getLocEnd();
643 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
644 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
645 /*SkipTrailingWhitespaceAndNewLine=*/true);
646 if (AfterSemi.isValid())
647 End = AfterSemi.getLocWithOffset(-1);
648 // Delete the forward declaration from the code to be moved.
Eric Liu4fe99e12016-12-14 17:01:52 +0000649 addReplacementOrDie(Start, End, "", *Result.SourceManager,
650 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32 +0000651 llvm::StringRef Code = Lexer::getSourceText(
652 CharSourceRange::getTokenRange(
653 Result.SourceManager->getSpellingLoc(Start),
654 Result.SourceManager->getSpellingLoc(End)),
655 *Result.SourceManager, Result.Context->getLangOpts());
656 // Insert the forward declaration back into the old namespace after moving the
657 // code from old namespace to new namespace.
658 // Insertion information is stored in `InsertFwdDecls` and actual
659 // insertion will be performed in `onEndOfTranslationUnit`.
660 // Get the (old) namespace that contains the forward declaration.
661 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
662 // The namespace contains the forward declaration, so it must not be empty.
663 assert(!NsDecl->decls_empty());
664 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
665 Code, *Result.SourceManager);
666 InsertForwardDeclaration InsertFwd;
667 InsertFwd.InsertionOffset = Insertion.getOffset();
668 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
669 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
670}
671
Eric Liub9bf1b52016-11-08 22:44:17 +0000672// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
673// FromDecl with the shortest qualified name possible when the reference is in
674// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32 +0000675void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17 +0000676 const ast_matchers::MatchFinder::MatchResult &Result,
677 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
678 const NamedDecl *FromDecl) {
679 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu4fe99e12016-12-14 17:01:52 +0000680 if (llvm::isa<TranslationUnitDecl>(NsDeclContext)) {
681 // This should not happen in usual unless the TypeLoc is in function type
682 // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of
683 // `T` will be the translation unit. We simply use fully-qualified name
684 // here.
685 // Note that `FromDecl` must not be defined in the old namespace (according
686 // to `DeclMatcher`), so its fully-qualified name will not change after
687 // changing the namespace.
688 addReplacementOrDie(Start, End, FromDecl->getQualifiedNameAsString(),
689 *Result.SourceManager, &FileToReplacements);
690 return;
691 }
Eric Liu231c6552016-11-10 18:15:34 +0000692 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32 +0000693 // Calculate the name of the `NsDecl` after it is moved to new namespace.
694 std::string OldNs = NsDecl->getQualifiedNameAsString();
695 llvm::StringRef Postfix = OldNs;
696 bool Consumed = Postfix.consume_front(OldNamespace);
697 assert(Consumed && "Expect OldNS to start with OldNamespace.");
698 (void)Consumed;
699 const std::string NewNs = (NewNamespace + Postfix).str();
700
701 llvm::StringRef NestedName = Lexer::getSourceText(
702 CharSourceRange::getTokenRange(
703 Result.SourceManager->getSpellingLoc(Start),
704 Result.SourceManager->getSpellingLoc(End)),
705 *Result.SourceManager, Result.Context->getLangOpts());
Eric Liub9bf1b52016-11-08 22:44:17 +0000706 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu495b2112016-09-19 17:40:32 +0000707 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17 +0000708 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
709 // Checks if there is any using namespace declarations that can shorten the
710 // qualified name.
711 for (const auto *UsingNamespace : UsingNamespaceDecls) {
712 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
713 Start))
714 continue;
715 StringRef FromDeclNameRef = FromDeclName;
716 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
717 ->getQualifiedNameAsString())) {
718 FromDeclNameRef = FromDeclNameRef.drop_front(2);
719 if (FromDeclNameRef.size() < ReplaceName.size())
720 ReplaceName = FromDeclNameRef;
721 }
722 }
Eric Liu180dac62016-12-23 10:47:09 +0000723 // Checks if there is any namespace alias declarations that can shorten the
724 // qualified name.
725 for (const auto *NamespaceAlias : NamespaceAliasDecls) {
726 if (!isDeclVisibleAtLocation(*Result.SourceManager, NamespaceAlias, DeclCtx,
727 Start))
728 continue;
729 StringRef FromDeclNameRef = FromDeclName;
730 if (FromDeclNameRef.consume_front(
731 NamespaceAlias->getNamespace()->getQualifiedNameAsString() +
732 "::")) {
733 std::string AliasName = NamespaceAlias->getNameAsString();
734 std::string AliasQualifiedName =
735 NamespaceAlias->getQualifiedNameAsString();
736 // We only consider namespace aliases define in the global namepspace or
737 // in namespaces that are directly visible from the reference, i.e.
738 // ancestor of the `OldNs`. Note that declarations in ancestor namespaces
739 // but not visible in the new namespace is filtered out by
740 // "IsVisibleInNewNs" matcher.
741 if (AliasQualifiedName != AliasName) {
742 // The alias is defined in some namespace.
743 assert(StringRef(AliasQualifiedName).endswith("::" + AliasName));
744 llvm::StringRef AliasNs =
745 StringRef(AliasQualifiedName).drop_back(AliasName.size() + 2);
746 if (!llvm::StringRef(OldNs).startswith(AliasNs))
747 continue;
748 }
749 std::string NameWithAliasNamespace =
750 (AliasName + "::" + FromDeclNameRef).str();
751 if (NameWithAliasNamespace.size() < ReplaceName.size())
752 ReplaceName = NameWithAliasNamespace;
753 }
754 }
Eric Liub9bf1b52016-11-08 22:44:17 +0000755 // Checks if there is any using shadow declarations that can shorten the
756 // qualified name.
757 bool Matched = false;
758 for (const UsingDecl *Using : UsingDecls) {
759 if (Matched)
760 break;
761 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
762 for (const auto *UsingShadow : Using->shadows()) {
763 const auto *TargetDecl = UsingShadow->getTargetDecl();
Eric Liuae7de712017-02-02 15:29:54 +0000764 if (TargetDecl->getQualifiedNameAsString() ==
765 FromDecl->getQualifiedNameAsString()) {
Eric Liub9bf1b52016-11-08 22:44:17 +0000766 ReplaceName = FromDecl->getNameAsString();
767 Matched = true;
768 break;
769 }
770 }
771 }
772 }
Eric Liu495b2112016-09-19 17:40:32 +0000773 // If the new nested name in the new namespace is the same as it was in the
774 // old namespace, we don't create replacement.
Eric Liu91229162017-01-26 16:31:32 +0000775 if (NestedName == ReplaceName ||
776 (NestedName.startswith("::") && NestedName.drop_front(2) == ReplaceName))
Eric Liu495b2112016-09-19 17:40:32 +0000777 return;
Eric Liu97f87ad2016-12-07 20:08:02 +0000778 // If the reference need to be fully-qualified, add a leading "::" unless
779 // NewNamespace is the global namespace.
780 if (ReplaceName == FromDeclName && !NewNamespace.empty())
781 ReplaceName = "::" + ReplaceName;
Eric Liu4fe99e12016-12-14 17:01:52 +0000782 addReplacementOrDie(Start, End, ReplaceName, *Result.SourceManager,
783 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32 +0000784}
785
786// Replace the [Start, End] of `Type` with the shortest qualified name when the
787// `Type` is in `NewNamespace`.
788void ChangeNamespaceTool::fixTypeLoc(
789 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
790 SourceLocation End, TypeLoc Type) {
791 // FIXME: do not rename template parameter.
792 if (Start.isInvalid() || End.isInvalid())
793 return;
Eric Liuff51f012016-11-16 16:54:53 +0000794 // Types of CXXCtorInitializers do not need to be fixed.
795 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
796 return;
Eric Liu495b2112016-09-19 17:40:32 +0000797 // The declaration which this TypeLoc refers to.
798 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
799 // `hasDeclaration` gives underlying declaration, but if the type is
800 // a typedef type, we need to use the typedef type instead.
Eric Liu26cf68a2016-12-15 10:42:35 +0000801 auto IsInMovedNs = [&](const NamedDecl *D) {
802 if (!llvm::StringRef(D->getQualifiedNameAsString())
803 .startswith(OldNamespace + "::"))
804 return false;
805 auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getLocStart());
806 if (ExpansionLoc.isInvalid())
807 return false;
808 llvm::StringRef Filename = Result.SourceManager->getFilename(ExpansionLoc);
809 return FilePatternRE.match(Filename);
810 };
811 // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if
812 // `Type` is an alias type, we make `FromDecl` the type alias declaration.
813 // Also, don't fix the \p Type if it refers to a type alias decl in the moved
814 // namespace since the alias decl will be moved along with the type reference.
Eric Liu32158862016-11-14 19:37:55 +0000815 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32 +0000816 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55 +0000817 if (IsInMovedNs(FromDecl))
818 return;
Eric Liu26cf68a2016-12-15 10:42:35 +0000819 } else if (auto *TemplateType =
820 Type.getType()->getAs<TemplateSpecializationType>()) {
821 if (TemplateType->isTypeAlias()) {
822 FromDecl = TemplateType->getTemplateName().getAsTemplateDecl();
823 if (IsInMovedNs(FromDecl))
824 return;
825 }
Eric Liu32158862016-11-14 19:37:55 +0000826 }
Piotr Padlewski08124b12016-12-14 15:29:23 +0000827 const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu495b2112016-09-19 17:40:32 +0000828 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17 +0000829 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
830 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32 +0000831}
832
Eric Liu68765a82016-09-21 15:06:12 +0000833void ChangeNamespaceTool::fixUsingShadowDecl(
834 const ast_matchers::MatchFinder::MatchResult &Result,
835 const UsingDecl *UsingDeclaration) {
836 SourceLocation Start = UsingDeclaration->getLocStart();
837 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000838 if (Start.isInvalid() || End.isInvalid())
839 return;
Eric Liu68765a82016-09-21 15:06:12 +0000840
841 assert(UsingDeclaration->shadow_size() > 0);
842 // FIXME: it might not be always accurate to use the first using-decl.
843 const NamedDecl *TargetDecl =
844 UsingDeclaration->shadow_begin()->getTargetDecl();
845 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
846 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
847 // sense. If this happens, we need to use name with the new namespace.
848 // Use fully qualified name in UsingDecl for now.
Eric Liu4fe99e12016-12-14 17:01:52 +0000849 addReplacementOrDie(Start, End, "using ::" + TargetDeclName,
850 *Result.SourceManager, &FileToReplacements);
Eric Liu68765a82016-09-21 15:06:12 +0000851}
852
Eric Liuda22b3c2016-11-29 14:15:14 +0000853void ChangeNamespaceTool::fixDeclRefExpr(
854 const ast_matchers::MatchFinder::MatchResult &Result,
855 const DeclContext *UseContext, const NamedDecl *From,
856 const DeclRefExpr *Ref) {
857 SourceRange RefRange = Ref->getSourceRange();
858 replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(),
859 RefRange.getEnd(), From);
860}
861
Eric Liu495b2112016-09-19 17:40:32 +0000862void ChangeNamespaceTool::onEndOfTranslationUnit() {
863 // Move namespace blocks and insert forward declaration to old namespace.
864 for (const auto &FileAndNsMoves : MoveNamespaces) {
865 auto &NsMoves = FileAndNsMoves.second;
866 if (NsMoves.empty())
867 continue;
868 const std::string &FilePath = FileAndNsMoves.first;
869 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59 +0000870 auto &SM = *NsMoves.begin()->SourceMgr;
871 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32 +0000872 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
873 if (!ChangedCode) {
874 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
875 continue;
876 }
877 // Replacements on the changed code for moving namespaces and inserting
878 // forward declarations to old namespaces.
879 tooling::Replacements NewReplacements;
880 // Cut the changed code from the old namespace and paste the code in the new
881 // namespace.
882 for (const auto &NsMove : NsMoves) {
883 // Calculate the range of the old namespace block in the changed
884 // code.
885 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
886 const unsigned NewLength =
887 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
888 NewOffset;
889 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
890 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
891 std::string MovedCodeWrappedInNewNs =
892 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
893 // Calculate the new offset at which the code will be inserted in the
894 // changed code.
895 unsigned NewInsertionOffset =
896 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
897 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
898 MovedCodeWrappedInNewNs);
899 addOrMergeReplacement(Deletion, &NewReplacements);
900 addOrMergeReplacement(Insertion, &NewReplacements);
901 }
902 // After moving namespaces, insert forward declarations back to old
903 // namespaces.
904 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
905 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
906 unsigned NewInsertionOffset =
907 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
908 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
909 FwdDeclInsertion.ForwardDeclText);
910 addOrMergeReplacement(Insertion, &NewReplacements);
911 }
912 // Add replacements referring to the changed code to existing replacements,
913 // which refers to the original code.
914 Replaces = Replaces.merge(NewReplacements);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000915 auto Style = format::getStyle("file", FilePath, FallbackStyle);
916 if (!Style) {
917 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
918 continue;
919 }
Eric Liu495b2112016-09-19 17:40:32 +0000920 // Clean up old namespaces if there is nothing in it after moving.
921 auto CleanReplacements =
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000922 format::cleanupAroundReplacements(Code, Replaces, *Style);
Eric Liu495b2112016-09-19 17:40:32 +0000923 if (!CleanReplacements) {
924 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
925 continue;
926 }
927 FileToReplacements[FilePath] = *CleanReplacements;
928 }
Eric Liuc265b022016-12-01 17:25:55 +0000929
930 // Make sure we don't generate replacements for files that do not match
931 // FilePattern.
932 for (auto &Entry : FileToReplacements)
933 if (!FilePatternRE.match(Entry.first))
934 Entry.second.clear();
Eric Liu495b2112016-09-19 17:40:32 +0000935}
936
937} // namespace change_namespace
938} // namespace clang