blob: bb3867c8ed7992b597a7eebbcfad2ffedcc5bffd [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
Eric Liu8bc24162017-03-21 12:41:5931// Given "a::b::c", returns {"a", "b", "c"}.
32llvm::SmallVector<llvm::StringRef, 4> splitSymbolName(llvm::StringRef Name) {
33 llvm::SmallVector<llvm::StringRef, 4> Splitted;
34 Name.split(Splitted, "::", /*MaxSplit=*/-1,
35 /*KeepEmpty=*/false);
36 return Splitted;
37}
38
Eric Liu495b2112016-09-19 17:40:3239SourceLocation startLocationForType(TypeLoc TLoc) {
40 // For elaborated types (e.g. `struct a::A`) we want the portion after the
41 // `struct` but including the namespace qualifier, `a::`.
42 if (TLoc.getTypeLocClass() == TypeLoc::Elaborated) {
43 NestedNameSpecifierLoc NestedNameSpecifier =
44 TLoc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
45 if (NestedNameSpecifier.getNestedNameSpecifier())
46 return NestedNameSpecifier.getBeginLoc();
47 TLoc = TLoc.getNextTypeLoc();
48 }
49 return TLoc.getLocStart();
50}
51
Eric Liuc265b022016-12-01 17:25:5552SourceLocation endLocationForType(TypeLoc TLoc) {
Eric Liu495b2112016-09-19 17:40:3253 // Dig past any namespace or keyword qualifications.
54 while (TLoc.getTypeLocClass() == TypeLoc::Elaborated ||
55 TLoc.getTypeLocClass() == TypeLoc::Qualified)
56 TLoc = TLoc.getNextTypeLoc();
57
58 // The location for template specializations (e.g. Foo<int>) includes the
59 // templated types in its location range. We want to restrict this to just
60 // before the `<` character.
61 if (TLoc.getTypeLocClass() == TypeLoc::TemplateSpecialization)
62 return TLoc.castAs<TemplateSpecializationTypeLoc>()
63 .getLAngleLoc()
64 .getLocWithOffset(-1);
65 return TLoc.getEndLoc();
66}
67
68// Returns the containing namespace of `InnerNs` by skipping `PartialNsName`.
Eric Liu6aa94162016-11-10 18:29:0169// If the `InnerNs` does not have `PartialNsName` as suffix, or `PartialNsName`
70// is empty, nullptr is returned.
Eric Liu495b2112016-09-19 17:40:3271// For example, if `InnerNs` is "a::b::c" and `PartialNsName` is "b::c", then
72// the NamespaceDecl of namespace "a" will be returned.
73const NamespaceDecl *getOuterNamespace(const NamespaceDecl *InnerNs,
74 llvm::StringRef PartialNsName) {
Eric Liu6aa94162016-11-10 18:29:0175 if (!InnerNs || PartialNsName.empty())
76 return nullptr;
Eric Liu495b2112016-09-19 17:40:3277 const auto *CurrentContext = llvm::cast<DeclContext>(InnerNs);
78 const auto *CurrentNs = InnerNs;
Eric Liu8bc24162017-03-21 12:41:5979 auto PartialNsNameSplitted = splitSymbolName(PartialNsName);
Eric Liu495b2112016-09-19 17:40:3280 while (!PartialNsNameSplitted.empty()) {
81 // Get the inner-most namespace in CurrentContext.
82 while (CurrentContext && !llvm::isa<NamespaceDecl>(CurrentContext))
83 CurrentContext = CurrentContext->getParent();
84 if (!CurrentContext)
85 return nullptr;
86 CurrentNs = llvm::cast<NamespaceDecl>(CurrentContext);
87 if (PartialNsNameSplitted.back() != CurrentNs->getNameAsString())
88 return nullptr;
89 PartialNsNameSplitted.pop_back();
90 CurrentContext = CurrentContext->getParent();
91 }
92 return CurrentNs;
93}
94
Eric Liu73f49fd2016-10-12 12:34:1895static std::unique_ptr<Lexer>
96getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM,
97 const LangOptions &LangOpts) {
Eric Liu495b2112016-09-19 17:40:3298 if (Loc.isMacroID() &&
99 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eric Liu73f49fd2016-10-12 12:34:18100 return nullptr;
Eric Liu495b2112016-09-19 17:40:32101 // Break down the source location.
102 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
103 // Try to load the file buffer.
104 bool InvalidTemp = false;
105 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
106 if (InvalidTemp)
Eric Liu73f49fd2016-10-12 12:34:18107 return nullptr;
Eric Liu495b2112016-09-19 17:40:32108
109 const char *TokBegin = File.data() + LocInfo.second;
110 // Lex from the start of the given location.
Eric Liu73f49fd2016-10-12 12:34:18111 return llvm::make_unique<Lexer>(SM.getLocForStartOfFile(LocInfo.first),
112 LangOpts, File.begin(), TokBegin, File.end());
113}
Eric Liu495b2112016-09-19 17:40:32114
Eric Liu73f49fd2016-10-12 12:34:18115// FIXME: get rid of this helper function if this is supported in clang-refactor
116// library.
117static SourceLocation getStartOfNextLine(SourceLocation Loc,
118 const SourceManager &SM,
119 const LangOptions &LangOpts) {
120 std::unique_ptr<Lexer> Lex = getLexerStartingFromLoc(Loc, SM, LangOpts);
121 if (!Lex.get())
122 return SourceLocation();
Eric Liu495b2112016-09-19 17:40:32123 llvm::SmallVector<char, 16> Line;
124 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
Eric Liu73f49fd2016-10-12 12:34:18125 Lex->setParsingPreprocessorDirective(true);
126 Lex->ReadToEndOfLine(&Line);
Haojian Wuef8a6dc2016-10-04 10:35:53127 auto End = Loc.getLocWithOffset(Line.size());
Eric Liu73f49fd2016-10-12 12:34:18128 return SM.getLocForEndOfFile(SM.getDecomposedLoc(Loc).first) == End
129 ? End
130 : End.getLocWithOffset(1);
Eric Liu495b2112016-09-19 17:40:32131}
132
133// Returns `R` with new range that refers to code after `Replaces` being
134// applied.
135tooling::Replacement
136getReplacementInChangedCode(const tooling::Replacements &Replaces,
137 const tooling::Replacement &R) {
138 unsigned NewStart = Replaces.getShiftedCodePosition(R.getOffset());
139 unsigned NewEnd =
140 Replaces.getShiftedCodePosition(R.getOffset() + R.getLength());
141 return tooling::Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
142 R.getReplacementText());
143}
144
145// Adds a replacement `R` into `Replaces` or merges it into `Replaces` by
146// applying all existing Replaces first if there is conflict.
147void addOrMergeReplacement(const tooling::Replacement &R,
148 tooling::Replacements *Replaces) {
149 auto Err = Replaces->add(R);
150 if (Err) {
151 llvm::consumeError(std::move(Err));
152 auto Replace = getReplacementInChangedCode(*Replaces, R);
153 *Replaces = Replaces->merge(tooling::Replacements(Replace));
154 }
155}
156
157tooling::Replacement createReplacement(SourceLocation Start, SourceLocation End,
158 llvm::StringRef ReplacementText,
159 const SourceManager &SM) {
160 if (!Start.isValid() || !End.isValid()) {
161 llvm::errs() << "start or end location were invalid\n";
162 return tooling::Replacement();
163 }
164 if (SM.getDecomposedLoc(Start).first != SM.getDecomposedLoc(End).first) {
165 llvm::errs()
166 << "start or end location were in different macro expansions\n";
167 return tooling::Replacement();
168 }
169 Start = SM.getSpellingLoc(Start);
170 End = SM.getSpellingLoc(End);
171 if (SM.getFileID(Start) != SM.getFileID(End)) {
172 llvm::errs() << "start or end location were in different files\n";
173 return tooling::Replacement();
174 }
175 return tooling::Replacement(
176 SM, CharSourceRange::getTokenRange(SM.getSpellingLoc(Start),
177 SM.getSpellingLoc(End)),
178 ReplacementText);
179}
180
Eric Liu4fe99e12016-12-14 17:01:52181void addReplacementOrDie(
182 SourceLocation Start, SourceLocation End, llvm::StringRef ReplacementText,
183 const SourceManager &SM,
184 std::map<std::string, tooling::Replacements> *FileToReplacements) {
185 const auto R = createReplacement(Start, End, ReplacementText, SM);
186 auto Err = (*FileToReplacements)[R.getFilePath()].add(R);
187 if (Err)
188 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
189}
190
Eric Liu495b2112016-09-19 17:40:32191tooling::Replacement createInsertion(SourceLocation Loc,
192 llvm::StringRef InsertText,
193 const SourceManager &SM) {
194 if (Loc.isInvalid()) {
195 llvm::errs() << "insert Location is invalid.\n";
196 return tooling::Replacement();
197 }
198 Loc = SM.getSpellingLoc(Loc);
199 return tooling::Replacement(SM, Loc, 0, InsertText);
200}
201
202// Returns the shortest qualified name for declaration `DeclName` in the
203// namespace `NsName`. For example, if `DeclName` is "a::b::X" and `NsName`
204// is "a::c::d", then "b::X" will be returned.
Eric Liubc715502017-01-26 15:08:44205// Note that if `DeclName` is `::b::X` and `NsName` is `::a::b`, this returns
206// "::b::X" instead of "b::X" since there will be a name conflict otherwise.
Eric Liu447164d2016-10-05 15:52:39207// \param DeclName A fully qualified name, "::a::b::X" or "a::b::X".
208// \param NsName A fully qualified name, "::a::b" or "a::b". Global namespace
209// will have empty name.
Eric Liu495b2112016-09-19 17:40:32210std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
211 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39212 DeclName = DeclName.ltrim(':');
213 NsName = NsName.ltrim(':');
Eric Liu447164d2016-10-05 15:52:39214 if (DeclName.find(':') == llvm::StringRef::npos)
Eric Liub9bf1b52016-11-08 22:44:17215 return DeclName;
Eric Liu447164d2016-10-05 15:52:39216
Eric Liu8bc24162017-03-21 12:41:59217 auto NsNameSplitted = splitSymbolName(NsName);
218 auto DeclNsSplitted = splitSymbolName(DeclName);
Eric Liubc715502017-01-26 15:08:44219 llvm::StringRef UnqualifiedDeclName = DeclNsSplitted.pop_back_val();
220 // If the Decl is in global namespace, there is no need to shorten it.
221 if (DeclNsSplitted.empty())
222 return UnqualifiedDeclName;
223 // If NsName is the global namespace, we can simply use the DeclName sans
224 // leading "::".
225 if (NsNameSplitted.empty())
226 return DeclName;
227
228 if (NsNameSplitted.front() != DeclNsSplitted.front()) {
229 // The DeclName must be fully-qualified, but we still need to decide if a
230 // leading "::" is necessary. For example, if `NsName` is "a::b::c" and the
231 // `DeclName` is "b::X", then the reference must be qualified as "::b::X"
232 // to avoid conflict.
233 if (llvm::is_contained(NsNameSplitted, DeclNsSplitted.front()))
234 return ("::" + DeclName).str();
235 return DeclName;
Eric Liu495b2112016-09-19 17:40:32236 }
Eric Liubc715502017-01-26 15:08:44237 // Since there is already an overlap namespace, we know that `DeclName` can be
238 // shortened, so we reduce the longest common prefix.
239 auto DeclI = DeclNsSplitted.begin();
240 auto DeclE = DeclNsSplitted.end();
241 auto NsI = NsNameSplitted.begin();
242 auto NsE = NsNameSplitted.end();
243 for (; DeclI != DeclE && NsI != NsE && *DeclI == *NsI; ++DeclI, ++NsI) {
244 }
245 return (DeclI == DeclE)
246 ? UnqualifiedDeclName.str()
247 : (llvm::join(DeclI, DeclE, "::") + "::" + UnqualifiedDeclName)
248 .str();
Eric Liu495b2112016-09-19 17:40:32249}
250
251std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) {
252 if (Code.back() != '\n')
253 Code += "\n";
Eric Liu8bc24162017-03-21 12:41:59254 auto NsSplitted = splitSymbolName(NestedNs);
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 Liu8bc24162017-03-21 12:41:59285// Given a qualified symbol name, returns true if the symbol will be
286// incorrectly qualified without leading "::".
287bool conflictInNamespace(llvm::StringRef QualifiedSymbol,
288 llvm::StringRef Namespace) {
289 auto SymbolSplitted = splitSymbolName(QualifiedSymbol.trim(":"));
290 assert(!SymbolSplitted.empty());
291 SymbolSplitted.pop_back(); // We are only interested in namespaces.
292
293 if (SymbolSplitted.size() > 1 && !Namespace.empty()) {
294 auto NsSplitted = splitSymbolName(Namespace.trim(":"));
295 assert(!NsSplitted.empty());
296 // We do not check the outermost namespace since it would not be a conflict
297 // if it equals to the symbol's outermost namespace and the symbol name
298 // would have been shortened.
299 for (auto I = NsSplitted.begin() + 1, E = NsSplitted.end(); I != E; ++I) {
300 if (*I == SymbolSplitted.front())
301 return true;
302 }
303 }
304 return false;
305}
306
Eric Liu0325a772017-02-02 17:40:38307AST_MATCHER(EnumDecl, isScoped) {
308 return Node.isScoped();
309}
310
Eric Liu284b97c2017-03-17 14:05:39311bool isTemplateParameter(TypeLoc Type) {
312 while (!Type.isNull()) {
313 if (Type.getTypeLocClass() == TypeLoc::SubstTemplateTypeParm)
314 return true;
315 Type = Type.getNextTypeLoc();
316 }
317 return false;
318}
319
Eric Liu495b2112016-09-19 17:40:32320} // anonymous namespace
321
322ChangeNamespaceTool::ChangeNamespaceTool(
323 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
Eric Liu7fccc992017-02-24 11:54:45324 llvm::ArrayRef<std::string> WhiteListedSymbolPatterns,
Eric Liu495b2112016-09-19 17:40:32325 std::map<std::string, tooling::Replacements> *FileToReplacements,
326 llvm::StringRef FallbackStyle)
327 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
328 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
Eric Liuc265b022016-12-01 17:25:55329 FilePattern(FilePattern), FilePatternRE(FilePattern) {
Eric Liu495b2112016-09-19 17:40:32330 FileToReplacements->clear();
Eric Liu8bc24162017-03-21 12:41:59331 auto OldNsSplitted = splitSymbolName(OldNamespace);
332 auto NewNsSplitted = splitSymbolName(NewNamespace);
Eric Liu495b2112016-09-19 17:40:32333 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
334 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
335 OldNsSplitted.front() == NewNsSplitted.front()) {
336 OldNsSplitted.erase(OldNsSplitted.begin());
337 NewNsSplitted.erase(NewNsSplitted.begin());
338 }
339 DiffOldNamespace = joinNamespaces(OldNsSplitted);
340 DiffNewNamespace = joinNamespaces(NewNsSplitted);
Eric Liu7fccc992017-02-24 11:54:45341
342 for (const auto &Pattern : WhiteListedSymbolPatterns)
343 WhiteListedSymbolRegexes.emplace_back(Pattern);
Eric Liu495b2112016-09-19 17:40:32344}
345
Eric Liu495b2112016-09-19 17:40:32346void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32347 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17348 // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the
349 // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will
350 // be "a::b". Declarations in this namespace will not be visible in the new
351 // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-".
352 llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04353 llvm::StringRef(DiffOldNamespace)
354 .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1,
355 /*KeepEmpty=*/false);
Eric Liub9bf1b52016-11-08 22:44:17356 std::string Prefix = "-";
357 if (!DiffOldNsSplitted.empty())
358 Prefix = (StringRef(FullOldNs).drop_back(DiffOldNamespace.size()) +
359 DiffOldNsSplitted.front())
360 .str();
361 auto IsInMovedNs =
362 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
363 isExpansionInFileMatching(FilePattern));
364 auto IsVisibleInNewNs = anyOf(
365 IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Prefix)))));
366 // Match using declarations.
367 Finder->addMatcher(
368 usingDecl(isExpansionInFileMatching(FilePattern), IsVisibleInNewNs)
369 .bind("using"),
370 this);
371 // Match using namespace declarations.
372 Finder->addMatcher(usingDirectiveDecl(isExpansionInFileMatching(FilePattern),
373 IsVisibleInNewNs)
374 .bind("using_namespace"),
375 this);
Eric Liu180dac62016-12-23 10:47:09376 // Match namespace alias declarations.
377 Finder->addMatcher(namespaceAliasDecl(isExpansionInFileMatching(FilePattern),
378 IsVisibleInNewNs)
379 .bind("namespace_alias"),
380 this);
Eric Liub9bf1b52016-11-08 22:44:17381
382 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32383 Finder->addMatcher(
384 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
385 .bind("old_ns"),
386 this);
387
Eric Liu41552d62016-12-07 14:20:52388 // Match class forward-declarations in the old namespace.
389 // Note that forward-declarations in classes are not matched.
390 Finder->addMatcher(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())),
391 IsInMovedNs, hasParent(namespaceDecl()))
392 .bind("class_fwd_decl"),
393 this);
394
395 // Match template class forward-declarations in the old namespace.
Eric Liu495b2112016-09-19 17:40:32396 Finder->addMatcher(
Eric Liu41552d62016-12-07 14:20:52397 classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))),
398 IsInMovedNs, hasParent(namespaceDecl()))
399 .bind("template_class_fwd_decl"),
Eric Liu495b2112016-09-19 17:40:32400 this);
401
402 // Match references to types that are not defined in the old namespace.
403 // Forward-declarations in the old namespace are also matched since they will
404 // be moved back to the old namespace.
405 auto DeclMatcher = namedDecl(
406 hasAncestor(namespaceDecl()),
407 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48408 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32409 hasAncestor(cxxRecordDecl()),
410 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48411
Eric Liu8685c762016-12-07 17:04:07412 // Using shadow declarations in classes always refers to base class, which
413 // does not need to be qualified since it can be inferred from inheritance.
414 // Note that this does not match using alias declarations.
415 auto UsingShadowDeclInClass =
416 usingDecl(hasAnyUsingShadowDecl(decl()), hasParent(cxxRecordDecl()));
417
Eric Liu495b2112016-09-19 17:40:32418 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29419 // TypeLoc and template specialization arguments (which are not outermost)
420 // that are directly linked to types matching `DeclMatcher`. Nested name
421 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32422 Finder->addMatcher(
423 typeLoc(IsInMovedNs,
424 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29425 unless(anyOf(hasParent(typeLoc(loc(qualType(
426 allOf(hasDeclaration(DeclMatcher),
427 unless(templateSpecializationType())))))),
Eric Liu8685c762016-12-07 17:04:07428 hasParent(nestedNameSpecifierLoc()),
429 hasAncestor(isImplicit()),
Eric Liub583a7e2017-10-16 08:20:10430 hasAncestor(UsingShadowDeclInClass),
431 hasAncestor(functionDecl(isDefaulted())))),
Eric Liu495b2112016-09-19 17:40:32432 hasAncestor(decl().bind("dc")))
433 .bind("type"),
434 this);
Eric Liu912d0392016-09-27 12:54:48435
Eric Liu68765a82016-09-21 15:06:12436 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
437 // special case it.
Eric Liu8685c762016-12-07 17:04:07438 // Since using declarations inside classes must have the base class in the
439 // nested name specifier, we leave it to the nested name specifier matcher.
440 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()),
441 unless(UsingShadowDeclInClass))
Eric Liub9bf1b52016-11-08 22:44:17442 .bind("using_with_shadow"),
443 this);
Eric Liu912d0392016-09-27 12:54:48444
Eric Liuff51f012016-11-16 16:54:53445 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
446 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
447 // "A::A" would have already been fixed.
Eric Liu8685c762016-12-07 17:04:07448 Finder->addMatcher(
449 nestedNameSpecifierLoc(
450 hasAncestor(decl(IsInMovedNs).bind("dc")),
451 loc(nestedNameSpecifier(
452 specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
453 unless(anyOf(hasAncestor(isImplicit()),
454 hasAncestor(UsingShadowDeclInClass),
Eric Liub583a7e2017-10-16 08:20:10455 hasAncestor(functionDecl(isDefaulted())),
Eric Liu8685c762016-12-07 17:04:07456 hasAncestor(typeLoc(loc(qualType(hasDeclaration(
457 decl(equalsBoundNode("from_decl"))))))))))
458 .bind("nested_specifier_loc"),
459 this);
Eric Liu12068d82016-09-22 11:54:00460
Eric Liuff51f012016-11-16 16:54:53461 // Matches base class initializers in constructors. TypeLocs of base class
462 // initializers do not need to be fixed. For example,
463 // class X : public a::b::Y {
464 // public:
465 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
466 // };
467 Finder->addMatcher(
468 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
469
Eric Liu12068d82016-09-22 11:54:00470 // Handle function.
Eric Liu912d0392016-09-27 12:54:48471 // Only handle functions that are defined in a namespace excluding member
472 // function, static methods (qualified by nested specifier), and functions
473 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00474 // Note that the matcher does not exclude calls to out-of-line static method
475 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48476 auto FuncMatcher =
477 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
478 hasAncestor(namespaceDecl(isAnonymous())),
479 hasAncestor(cxxRecordDecl()))),
480 hasParent(namespaceDecl()));
Eric Liuda22b3c2016-11-29 14:15:14481 Finder->addMatcher(decl(forEachDescendant(expr(anyOf(
482 callExpr(callee(FuncMatcher)).bind("call"),
483 declRefExpr(to(FuncMatcher.bind("func_decl")))
484 .bind("func_ref")))),
485 IsInMovedNs, unless(isImplicit()))
486 .bind("dc"),
487 this);
Eric Liu159f0132016-09-30 04:32:39488
489 auto GlobalVarMatcher = varDecl(
490 hasGlobalStorage(), hasParent(namespaceDecl()),
491 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
492 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
493 to(GlobalVarMatcher.bind("var_decl")))
494 .bind("var_ref"),
495 this);
Eric Liu0325a772017-02-02 17:40:38496
497 // Handle unscoped enum constant.
498 auto UnscopedEnumMatcher = enumConstantDecl(hasParent(enumDecl(
499 hasParent(namespaceDecl()),
500 unless(anyOf(isScoped(), IsInMovedNs, hasAncestor(cxxRecordDecl()),
501 hasAncestor(namespaceDecl(isAnonymous())))))));
502 Finder->addMatcher(
503 declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
504 to(UnscopedEnumMatcher.bind("enum_const_decl")))
505 .bind("enum_const_ref"),
506 this);
Eric Liu495b2112016-09-19 17:40:32507}
508
509void ChangeNamespaceTool::run(
510 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17511 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
512 UsingDecls.insert(Using);
513 } else if (const auto *UsingNamespace =
514 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
515 "using_namespace")) {
516 UsingNamespaceDecls.insert(UsingNamespace);
Eric Liu180dac62016-12-23 10:47:09517 } else if (const auto *NamespaceAlias =
518 Result.Nodes.getNodeAs<NamespaceAliasDecl>(
519 "namespace_alias")) {
520 NamespaceAliasDecls.insert(NamespaceAlias);
Eric Liub9bf1b52016-11-08 22:44:17521 } else if (const auto *NsDecl =
522 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32523 moveOldNamespace(Result, NsDecl);
524 } else if (const auto *FwdDecl =
Eric Liu41552d62016-12-07 14:20:52525 Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) {
526 moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl));
527 } else if (const auto *TemplateFwdDecl =
528 Result.Nodes.getNodeAs<ClassTemplateDecl>(
529 "template_class_fwd_decl")) {
530 moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl));
Eric Liub9bf1b52016-11-08 22:44:17531 } else if (const auto *UsingWithShadow =
532 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
533 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12534 } else if (const auto *Specifier =
535 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
536 "nested_specifier_loc")) {
537 SourceLocation Start = Specifier->getBeginLoc();
Eric Liuc265b022016-12-01 17:25:55538 SourceLocation End = endLocationForType(Specifier->getTypeLoc());
Eric Liu68765a82016-09-21 15:06:12539 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53540 } else if (const auto *BaseInitializer =
541 Result.Nodes.getNodeAs<CXXCtorInitializer>(
542 "base_initializer")) {
543 BaseCtorInitializerTypeLocs.push_back(
544 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00545 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu26cf68a2016-12-15 10:42:35546 // This avoids fixing types with record types as qualifier, which is not
547 // filtered by matchers in some cases, e.g. the type is templated. We should
548 // handle the record type qualifier instead.
Eric Liu0c0aea02016-12-15 13:02:41549 TypeLoc Loc = *TLoc;
550 while (Loc.getTypeLocClass() == TypeLoc::Qualified)
551 Loc = Loc.getNextTypeLoc();
552 if (Loc.getTypeLocClass() == TypeLoc::Elaborated) {
Eric Liu26cf68a2016-12-15 10:42:35553 NestedNameSpecifierLoc NestedNameSpecifier =
Eric Liu0c0aea02016-12-15 13:02:41554 Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
Eric Liu26cf68a2016-12-15 10:42:35555 const Type *SpecifierType =
556 NestedNameSpecifier.getNestedNameSpecifier()->getAsType();
557 if (SpecifierType && SpecifierType->isRecordType())
558 return;
559 }
Eric Liu0c0aea02016-12-15 13:02:41560 fixTypeLoc(Result, startLocationForType(Loc), endLocationForType(Loc), Loc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19561 } else if (const auto *VarRef =
562 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39563 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
564 assert(Var);
565 if (Var->getCanonicalDecl()->isStaticDataMember())
566 return;
Eric Liuda22b3c2016-11-29 14:15:14567 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu159f0132016-09-30 04:32:39568 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14569 fixDeclRefExpr(Result, Context->getDeclContext(),
570 llvm::cast<NamedDecl>(Var), VarRef);
Eric Liu0325a772017-02-02 17:40:38571 } else if (const auto *EnumConstRef =
572 Result.Nodes.getNodeAs<DeclRefExpr>("enum_const_ref")) {
573 // Do not rename the reference if it is already scoped by the EnumDecl name.
574 if (EnumConstRef->hasQualifier() &&
Eric Liu28c30ce2017-02-02 19:46:12575 EnumConstRef->getQualifier()->getKind() ==
576 NestedNameSpecifier::SpecifierKind::TypeSpec &&
Eric Liu0325a772017-02-02 17:40:38577 EnumConstRef->getQualifier()->getAsType()->isEnumeralType())
578 return;
579 const auto *EnumConstDecl =
580 Result.Nodes.getNodeAs<EnumConstantDecl>("enum_const_decl");
581 assert(EnumConstDecl);
582 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
583 assert(Context && "Empty decl context.");
584 // FIXME: this would qualify "ns::VALUE" as "ns::EnumValue::VALUE". Fix it
585 // if it turns out to be an issue.
586 fixDeclRefExpr(Result, Context->getDeclContext(),
587 llvm::cast<NamedDecl>(EnumConstDecl), EnumConstRef);
Eric Liuda22b3c2016-11-29 14:15:14588 } else if (const auto *FuncRef =
589 Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) {
Eric Liue3f35e42016-12-20 14:39:04590 // If this reference has been processed as a function call, we do not
591 // process it again.
592 if (ProcessedFuncRefs.count(FuncRef))
593 return;
594 ProcessedFuncRefs.insert(FuncRef);
Eric Liuda22b3c2016-11-29 14:15:14595 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
596 assert(Func);
597 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
598 assert(Context && "Empty decl context.");
599 fixDeclRefExpr(Result, Context->getDeclContext(),
600 llvm::cast<NamedDecl>(Func), FuncRef);
Eric Liu12068d82016-09-22 11:54:00601 } else {
Eric Liuda22b3c2016-11-29 14:15:14602 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19603 assert(Call != nullptr && "Expecting callback for CallExpr.");
Eric Liue3f35e42016-12-20 14:39:04604 const auto *CalleeFuncRef =
605 llvm::cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit());
606 ProcessedFuncRefs.insert(CalleeFuncRef);
Eric Liuda22b3c2016-11-29 14:15:14607 const FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00608 assert(Func != nullptr);
Eric Liue3f35e42016-12-20 14:39:04609 // FIXME: ignore overloaded operators. This would miss cases where operators
610 // are called by qualified names (i.e. "ns::operator <"). Ignore such
611 // cases for now.
612 if (Func->isOverloadedOperator())
613 return;
Eric Liu12068d82016-09-22 11:54:00614 // Ignore out-of-line static methods since they will be handled by nested
615 // name specifiers.
616 if (Func->getCanonicalDecl()->getStorageClass() ==
Eric Liuda22b3c2016-11-29 14:15:14617 StorageClass::SC_Static &&
Eric Liu12068d82016-09-22 11:54:00618 Func->isOutOfLine())
619 return;
Eric Liuda22b3c2016-11-29 14:15:14620 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu12068d82016-09-22 11:54:00621 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14622 SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17623 replaceQualifiedSymbolInDeclContext(
624 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34625 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32626 }
627}
628
Eric Liu73f49fd2016-10-12 12:34:18629static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
630 const SourceManager &SM,
631 const LangOptions &LangOpts) {
632 std::unique_ptr<Lexer> Lex =
633 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
634 assert(Lex.get() &&
635 "Failed to create lexer from the beginning of namespace.");
636 if (!Lex.get())
637 return SourceLocation();
638 Token Tok;
639 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
640 }
641 return Tok.isNot(tok::TokenKind::l_brace)
642 ? SourceLocation()
643 : Tok.getEndLoc().getLocWithOffset(1);
644}
645
Eric Liu495b2112016-09-19 17:40:32646// Stores information about a moved namespace in `MoveNamespaces` and leaves
647// the actual movement to `onEndOfTranslationUnit()`.
648void ChangeNamespaceTool::moveOldNamespace(
649 const ast_matchers::MatchFinder::MatchResult &Result,
650 const NamespaceDecl *NsDecl) {
651 // If the namespace is empty, do nothing.
652 if (Decl::castToDeclContext(NsDecl)->decls_empty())
653 return;
654
Eric Liuee5104b2017-01-04 14:49:08655 const SourceManager &SM = *Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32656 // Get the range of the code in the old namespace.
Eric Liuee5104b2017-01-04 14:49:08657 SourceLocation Start =
658 getLocAfterNamespaceLBrace(NsDecl, SM, Result.Context->getLangOpts());
Eric Liu73f49fd2016-10-12 12:34:18659 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32660 MoveNamespace MoveNs;
Eric Liuee5104b2017-01-04 14:49:08661 MoveNs.Offset = SM.getFileOffset(Start);
662 // The range of the moved namespace is from the location just past the left
663 // brace to the location right before the right brace.
664 MoveNs.Length = SM.getFileOffset(NsDecl->getRBraceLoc()) - MoveNs.Offset;
Eric Liu495b2112016-09-19 17:40:32665
666 // Insert the new namespace after `DiffOldNamespace`. For example, if
667 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
668 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
669 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
670 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01671 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
672 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32673 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01674 SourceLocation InsertionLoc = Start;
675 if (OuterNs) {
Eric Liuee5104b2017-01-04 14:49:08676 SourceLocation LocAfterNs = getStartOfNextLine(
677 OuterNs->getRBraceLoc(), SM, Result.Context->getLangOpts());
Eric Liu6aa94162016-11-10 18:29:01678 assert(LocAfterNs.isValid() &&
679 "Failed to get location after DiffOldNamespace");
680 InsertionLoc = LocAfterNs;
681 }
Eric Liuee5104b2017-01-04 14:49:08682 MoveNs.InsertionOffset = SM.getFileOffset(SM.getSpellingLoc(InsertionLoc));
683 MoveNs.FID = SM.getFileID(Start);
Eric Liucc83c662016-09-19 17:58:59684 MoveNs.SourceMgr = Result.SourceManager;
Eric Liuee5104b2017-01-04 14:49:08685 MoveNamespaces[SM.getFilename(Start)].push_back(MoveNs);
Eric Liu495b2112016-09-19 17:40:32686}
687
688// Removes a class forward declaration from the code in the moved namespace and
689// creates an `InsertForwardDeclaration` to insert the forward declaration back
690// into the old namespace after moving code from the old namespace to the new
691// namespace.
692// For example, changing "a" to "x":
693// Old code:
694// namespace a {
695// class FWD;
696// class A { FWD *fwd; }
697// } // a
698// New code:
699// namespace a {
700// class FWD;
701// } // a
702// namespace x {
703// class A { a::FWD *fwd; }
704// } // x
705void ChangeNamespaceTool::moveClassForwardDeclaration(
706 const ast_matchers::MatchFinder::MatchResult &Result,
Eric Liu41552d62016-12-07 14:20:52707 const NamedDecl *FwdDecl) {
Eric Liu495b2112016-09-19 17:40:32708 SourceLocation Start = FwdDecl->getLocStart();
709 SourceLocation End = FwdDecl->getLocEnd();
Eric Liu41367152017-03-01 10:29:39710 const SourceManager &SM = *Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32711 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
Eric Liu41367152017-03-01 10:29:39712 End, tok::semi, SM, Result.Context->getLangOpts(),
Eric Liu495b2112016-09-19 17:40:32713 /*SkipTrailingWhitespaceAndNewLine=*/true);
714 if (AfterSemi.isValid())
715 End = AfterSemi.getLocWithOffset(-1);
716 // Delete the forward declaration from the code to be moved.
Eric Liu41367152017-03-01 10:29:39717 addReplacementOrDie(Start, End, "", SM, &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32718 llvm::StringRef Code = Lexer::getSourceText(
Eric Liu41367152017-03-01 10:29:39719 CharSourceRange::getTokenRange(SM.getSpellingLoc(Start),
720 SM.getSpellingLoc(End)),
721 SM, Result.Context->getLangOpts());
Eric Liu495b2112016-09-19 17:40:32722 // Insert the forward declaration back into the old namespace after moving the
723 // code from old namespace to new namespace.
724 // Insertion information is stored in `InsertFwdDecls` and actual
725 // insertion will be performed in `onEndOfTranslationUnit`.
726 // Get the (old) namespace that contains the forward declaration.
727 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
728 // The namespace contains the forward declaration, so it must not be empty.
729 assert(!NsDecl->decls_empty());
Eric Liu41367152017-03-01 10:29:39730 const auto Insertion = createInsertion(
731 getLocAfterNamespaceLBrace(NsDecl, SM, Result.Context->getLangOpts()),
732 Code, SM);
Eric Liu495b2112016-09-19 17:40:32733 InsertForwardDeclaration InsertFwd;
734 InsertFwd.InsertionOffset = Insertion.getOffset();
735 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
736 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
737}
738
Eric Liub9bf1b52016-11-08 22:44:17739// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
740// FromDecl with the shortest qualified name possible when the reference is in
741// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32742void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17743 const ast_matchers::MatchFinder::MatchResult &Result,
744 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
745 const NamedDecl *FromDecl) {
746 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu4fe99e12016-12-14 17:01:52747 if (llvm::isa<TranslationUnitDecl>(NsDeclContext)) {
748 // This should not happen in usual unless the TypeLoc is in function type
749 // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of
750 // `T` will be the translation unit. We simply use fully-qualified name
751 // here.
752 // Note that `FromDecl` must not be defined in the old namespace (according
753 // to `DeclMatcher`), so its fully-qualified name will not change after
754 // changing the namespace.
755 addReplacementOrDie(Start, End, FromDecl->getQualifiedNameAsString(),
756 *Result.SourceManager, &FileToReplacements);
757 return;
758 }
Eric Liu231c6552016-11-10 18:15:34759 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32760 // Calculate the name of the `NsDecl` after it is moved to new namespace.
761 std::string OldNs = NsDecl->getQualifiedNameAsString();
762 llvm::StringRef Postfix = OldNs;
763 bool Consumed = Postfix.consume_front(OldNamespace);
764 assert(Consumed && "Expect OldNS to start with OldNamespace.");
765 (void)Consumed;
766 const std::string NewNs = (NewNamespace + Postfix).str();
767
768 llvm::StringRef NestedName = Lexer::getSourceText(
769 CharSourceRange::getTokenRange(
770 Result.SourceManager->getSpellingLoc(Start),
771 Result.SourceManager->getSpellingLoc(End)),
772 *Result.SourceManager, Result.Context->getLangOpts());
Eric Liub9bf1b52016-11-08 22:44:17773 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu7fccc992017-02-24 11:54:45774 for (llvm::Regex &RE : WhiteListedSymbolRegexes)
775 if (RE.match(FromDeclName))
776 return;
Eric Liu495b2112016-09-19 17:40:32777 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17778 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
779 // Checks if there is any using namespace declarations that can shorten the
780 // qualified name.
781 for (const auto *UsingNamespace : UsingNamespaceDecls) {
782 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
783 Start))
784 continue;
785 StringRef FromDeclNameRef = FromDeclName;
786 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
787 ->getQualifiedNameAsString())) {
788 FromDeclNameRef = FromDeclNameRef.drop_front(2);
789 if (FromDeclNameRef.size() < ReplaceName.size())
790 ReplaceName = FromDeclNameRef;
791 }
792 }
Eric Liu180dac62016-12-23 10:47:09793 // Checks if there is any namespace alias declarations that can shorten the
794 // qualified name.
795 for (const auto *NamespaceAlias : NamespaceAliasDecls) {
796 if (!isDeclVisibleAtLocation(*Result.SourceManager, NamespaceAlias, DeclCtx,
797 Start))
798 continue;
799 StringRef FromDeclNameRef = FromDeclName;
800 if (FromDeclNameRef.consume_front(
801 NamespaceAlias->getNamespace()->getQualifiedNameAsString() +
802 "::")) {
803 std::string AliasName = NamespaceAlias->getNameAsString();
804 std::string AliasQualifiedName =
805 NamespaceAlias->getQualifiedNameAsString();
806 // We only consider namespace aliases define in the global namepspace or
807 // in namespaces that are directly visible from the reference, i.e.
808 // ancestor of the `OldNs`. Note that declarations in ancestor namespaces
809 // but not visible in the new namespace is filtered out by
810 // "IsVisibleInNewNs" matcher.
811 if (AliasQualifiedName != AliasName) {
812 // The alias is defined in some namespace.
813 assert(StringRef(AliasQualifiedName).endswith("::" + AliasName));
814 llvm::StringRef AliasNs =
815 StringRef(AliasQualifiedName).drop_back(AliasName.size() + 2);
816 if (!llvm::StringRef(OldNs).startswith(AliasNs))
817 continue;
818 }
819 std::string NameWithAliasNamespace =
820 (AliasName + "::" + FromDeclNameRef).str();
821 if (NameWithAliasNamespace.size() < ReplaceName.size())
822 ReplaceName = NameWithAliasNamespace;
823 }
824 }
Eric Liub9bf1b52016-11-08 22:44:17825 // Checks if there is any using shadow declarations that can shorten the
826 // qualified name.
827 bool Matched = false;
828 for (const UsingDecl *Using : UsingDecls) {
829 if (Matched)
830 break;
831 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
832 for (const auto *UsingShadow : Using->shadows()) {
833 const auto *TargetDecl = UsingShadow->getTargetDecl();
Eric Liuae7de712017-02-02 15:29:54834 if (TargetDecl->getQualifiedNameAsString() ==
835 FromDecl->getQualifiedNameAsString()) {
Eric Liub9bf1b52016-11-08 22:44:17836 ReplaceName = FromDecl->getNameAsString();
837 Matched = true;
838 break;
839 }
840 }
841 }
842 }
Eric Liu495b2112016-09-19 17:40:32843 // If the new nested name in the new namespace is the same as it was in the
844 // old namespace, we don't create replacement.
Eric Liu91229162017-01-26 16:31:32845 if (NestedName == ReplaceName ||
846 (NestedName.startswith("::") && NestedName.drop_front(2) == ReplaceName))
Eric Liu495b2112016-09-19 17:40:32847 return;
Eric Liu97f87ad2016-12-07 20:08:02848 // If the reference need to be fully-qualified, add a leading "::" unless
849 // NewNamespace is the global namespace.
Eric Liu8bc24162017-03-21 12:41:59850 if (ReplaceName == FromDeclName && !NewNamespace.empty() &&
851 conflictInNamespace(ReplaceName, NewNamespace))
Eric Liu97f87ad2016-12-07 20:08:02852 ReplaceName = "::" + ReplaceName;
Eric Liu4fe99e12016-12-14 17:01:52853 addReplacementOrDie(Start, End, ReplaceName, *Result.SourceManager,
854 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32855}
856
857// Replace the [Start, End] of `Type` with the shortest qualified name when the
858// `Type` is in `NewNamespace`.
859void ChangeNamespaceTool::fixTypeLoc(
860 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
861 SourceLocation End, TypeLoc Type) {
862 // FIXME: do not rename template parameter.
863 if (Start.isInvalid() || End.isInvalid())
864 return;
Eric Liuff51f012016-11-16 16:54:53865 // Types of CXXCtorInitializers do not need to be fixed.
866 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
867 return;
Eric Liu284b97c2017-03-17 14:05:39868 if (isTemplateParameter(Type))
869 return;
Eric Liu495b2112016-09-19 17:40:32870 // The declaration which this TypeLoc refers to.
871 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
872 // `hasDeclaration` gives underlying declaration, but if the type is
873 // a typedef type, we need to use the typedef type instead.
Eric Liu26cf68a2016-12-15 10:42:35874 auto IsInMovedNs = [&](const NamedDecl *D) {
875 if (!llvm::StringRef(D->getQualifiedNameAsString())
876 .startswith(OldNamespace + "::"))
877 return false;
878 auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getLocStart());
879 if (ExpansionLoc.isInvalid())
880 return false;
881 llvm::StringRef Filename = Result.SourceManager->getFilename(ExpansionLoc);
882 return FilePatternRE.match(Filename);
883 };
884 // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if
885 // `Type` is an alias type, we make `FromDecl` the type alias declaration.
886 // Also, don't fix the \p Type if it refers to a type alias decl in the moved
887 // namespace since the alias decl will be moved along with the type reference.
Eric Liu32158862016-11-14 19:37:55888 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32889 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55890 if (IsInMovedNs(FromDecl))
891 return;
Eric Liu26cf68a2016-12-15 10:42:35892 } else if (auto *TemplateType =
893 Type.getType()->getAs<TemplateSpecializationType>()) {
894 if (TemplateType->isTypeAlias()) {
895 FromDecl = TemplateType->getTemplateName().getAsTemplateDecl();
896 if (IsInMovedNs(FromDecl))
897 return;
898 }
Eric Liu32158862016-11-14 19:37:55899 }
Piotr Padlewski08124b12016-12-14 15:29:23900 const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu495b2112016-09-19 17:40:32901 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17902 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
903 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32904}
905
Eric Liu68765a82016-09-21 15:06:12906void ChangeNamespaceTool::fixUsingShadowDecl(
907 const ast_matchers::MatchFinder::MatchResult &Result,
908 const UsingDecl *UsingDeclaration) {
909 SourceLocation Start = UsingDeclaration->getLocStart();
910 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19911 if (Start.isInvalid() || End.isInvalid())
912 return;
Eric Liu68765a82016-09-21 15:06:12913
914 assert(UsingDeclaration->shadow_size() > 0);
915 // FIXME: it might not be always accurate to use the first using-decl.
916 const NamedDecl *TargetDecl =
917 UsingDeclaration->shadow_begin()->getTargetDecl();
918 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
919 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
920 // sense. If this happens, we need to use name with the new namespace.
921 // Use fully qualified name in UsingDecl for now.
Eric Liu4fe99e12016-12-14 17:01:52922 addReplacementOrDie(Start, End, "using ::" + TargetDeclName,
923 *Result.SourceManager, &FileToReplacements);
Eric Liu68765a82016-09-21 15:06:12924}
925
Eric Liuda22b3c2016-11-29 14:15:14926void ChangeNamespaceTool::fixDeclRefExpr(
927 const ast_matchers::MatchFinder::MatchResult &Result,
928 const DeclContext *UseContext, const NamedDecl *From,
929 const DeclRefExpr *Ref) {
930 SourceRange RefRange = Ref->getSourceRange();
931 replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(),
932 RefRange.getEnd(), From);
933}
934
Eric Liu495b2112016-09-19 17:40:32935void ChangeNamespaceTool::onEndOfTranslationUnit() {
936 // Move namespace blocks and insert forward declaration to old namespace.
937 for (const auto &FileAndNsMoves : MoveNamespaces) {
938 auto &NsMoves = FileAndNsMoves.second;
939 if (NsMoves.empty())
940 continue;
941 const std::string &FilePath = FileAndNsMoves.first;
942 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59943 auto &SM = *NsMoves.begin()->SourceMgr;
944 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32945 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
946 if (!ChangedCode) {
947 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
948 continue;
949 }
950 // Replacements on the changed code for moving namespaces and inserting
951 // forward declarations to old namespaces.
952 tooling::Replacements NewReplacements;
953 // Cut the changed code from the old namespace and paste the code in the new
954 // namespace.
955 for (const auto &NsMove : NsMoves) {
956 // Calculate the range of the old namespace block in the changed
957 // code.
958 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
959 const unsigned NewLength =
960 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
961 NewOffset;
962 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
963 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
964 std::string MovedCodeWrappedInNewNs =
965 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
966 // Calculate the new offset at which the code will be inserted in the
967 // changed code.
968 unsigned NewInsertionOffset =
969 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
970 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
971 MovedCodeWrappedInNewNs);
972 addOrMergeReplacement(Deletion, &NewReplacements);
973 addOrMergeReplacement(Insertion, &NewReplacements);
974 }
975 // After moving namespaces, insert forward declarations back to old
976 // namespaces.
977 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
978 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
979 unsigned NewInsertionOffset =
980 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
981 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
982 FwdDeclInsertion.ForwardDeclText);
983 addOrMergeReplacement(Insertion, &NewReplacements);
984 }
985 // Add replacements referring to the changed code to existing replacements,
986 // which refers to the original code.
987 Replaces = Replaces.merge(NewReplacements);
Antonio Maiorano0d7d9c22017-01-17 00:13:32988 auto Style = format::getStyle("file", FilePath, FallbackStyle);
989 if (!Style) {
990 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
991 continue;
992 }
Eric Liu495b2112016-09-19 17:40:32993 // Clean up old namespaces if there is nothing in it after moving.
994 auto CleanReplacements =
Antonio Maiorano0d7d9c22017-01-17 00:13:32995 format::cleanupAroundReplacements(Code, Replaces, *Style);
Eric Liu495b2112016-09-19 17:40:32996 if (!CleanReplacements) {
997 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
998 continue;
999 }
1000 FileToReplacements[FilePath] = *CleanReplacements;
1001 }
Eric Liuc265b022016-12-01 17:25:551002
1003 // Make sure we don't generate replacements for files that do not match
1004 // FilePattern.
1005 for (auto &Entry : FileToReplacements)
1006 if (!FilePatternRE.match(Entry.first))
1007 Entry.second.clear();
Eric Liu495b2112016-09-19 17:40:321008}
1009
1010} // namespace change_namespace
1011} // namespace clang