blob: 0b90de414c543628010f8d589a44846b8d9b1d52 [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
Eric Liu8bc24162017-03-21 12:41:59 +000031// 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:32 +000039SourceLocation 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:55 +000052SourceLocation endLocationForType(TypeLoc TLoc) {
Eric Liu495b2112016-09-19 17:40:32 +000053 // 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:01 +000069// If the `InnerNs` does not have `PartialNsName` as suffix, or `PartialNsName`
70// is empty, nullptr is returned.
Eric Liu495b2112016-09-19 17:40:32 +000071// 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:01 +000075 if (!InnerNs || PartialNsName.empty())
76 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +000077 const auto *CurrentContext = llvm::cast<DeclContext>(InnerNs);
78 const auto *CurrentNs = InnerNs;
Eric Liu8bc24162017-03-21 12:41:59 +000079 auto PartialNsNameSplitted = splitSymbolName(PartialNsName);
Eric Liu495b2112016-09-19 17:40:32 +000080 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:18 +000095static std::unique_ptr<Lexer>
96getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM,
97 const LangOptions &LangOpts) {
Eric Liu495b2112016-09-19 17:40:32 +000098 if (Loc.isMacroID() &&
99 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eric Liu73f49fd2016-10-12 12:34:18 +0000100 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +0000101 // 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:18 +0000107 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +0000108
109 const char *TokBegin = File.data() + LocInfo.second;
110 // Lex from the start of the given location.
Eric Liu73f49fd2016-10-12 12:34:18 +0000111 return llvm::make_unique<Lexer>(SM.getLocForStartOfFile(LocInfo.first),
112 LangOpts, File.begin(), TokBegin, File.end());
113}
Eric Liu495b2112016-09-19 17:40:32 +0000114
Eric Liu73f49fd2016-10-12 12:34:18 +0000115// 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:32 +0000123 llvm::SmallVector<char, 16> Line;
124 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
Eric Liu73f49fd2016-10-12 12:34:18 +0000125 Lex->setParsingPreprocessorDirective(true);
126 Lex->ReadToEndOfLine(&Line);
Haojian Wuef8a6dc2016-10-04 10:35:53 +0000127 auto End = Loc.getLocWithOffset(Line.size());
Eric Liu73f49fd2016-10-12 12:34:18 +0000128 return SM.getLocForEndOfFile(SM.getDecomposedLoc(Loc).first) == End
129 ? End
130 : End.getLocWithOffset(1);
Eric Liu495b2112016-09-19 17:40:32 +0000131}
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:52 +0000181void 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:32 +0000191tooling::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:44 +0000205// 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:39 +0000207// \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:32 +0000210std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
211 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39 +0000212 DeclName = DeclName.ltrim(':');
213 NsName = NsName.ltrim(':');
Eric Liu447164d2016-10-05 15:52:39 +0000214 if (DeclName.find(':') == llvm::StringRef::npos)
Eric Liub9bf1b52016-11-08 22:44:17 +0000215 return DeclName;
Eric Liu447164d2016-10-05 15:52:39 +0000216
Eric Liu8bc24162017-03-21 12:41:59 +0000217 auto NsNameSplitted = splitSymbolName(NsName);
218 auto DeclNsSplitted = splitSymbolName(DeclName);
Eric Liubc715502017-01-26 15:08:44 +0000219 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:32 +0000236 }
Eric Liubc715502017-01-26 15:08:44 +0000237 // 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:32 +0000249}
250
251std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) {
252 if (Code.back() != '\n')
253 Code += "\n";
Eric Liu8bc24162017-03-21 12:41:59 +0000254 auto NsSplitted = splitSymbolName(NestedNs);
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) {
Eric Liua13c4192017-02-13 17:24:14 +0000278 SourceLocation DeclLoc = SM.getSpellingLoc(D->getLocStart());
Eric Liub9bf1b52016-11-08 22:44:17 +0000279 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:59 +0000285// 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:38 +0000307AST_MATCHER(EnumDecl, isScoped) {
308 return Node.isScoped();
309}
310
Eric Liu284b97c2017-03-17 14:05:39 +0000311bool 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:32 +0000320} // anonymous namespace
321
322ChangeNamespaceTool::ChangeNamespaceTool(
323 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
Eric Liu7fccc992017-02-24 11:54:45 +0000324 llvm::ArrayRef<std::string> WhiteListedSymbolPatterns,
Eric Liu495b2112016-09-19 17:40:32 +0000325 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:55 +0000329 FilePattern(FilePattern), FilePatternRE(FilePattern) {
Eric Liu495b2112016-09-19 17:40:32 +0000330 FileToReplacements->clear();
Eric Liu8bc24162017-03-21 12:41:59 +0000331 auto OldNsSplitted = splitSymbolName(OldNamespace);
332 auto NewNsSplitted = splitSymbolName(NewNamespace);
Eric Liu495b2112016-09-19 17:40:32 +0000333 // 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:45 +0000341
342 for (const auto &Pattern : WhiteListedSymbolPatterns)
343 WhiteListedSymbolRegexes.emplace_back(Pattern);
Eric Liu495b2112016-09-19 17:40:32 +0000344}
345
Eric Liu495b2112016-09-19 17:40:32 +0000346void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32 +0000347 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17 +0000348 // 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:04 +0000353 llvm::StringRef(DiffOldNamespace)
354 .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1,
355 /*KeepEmpty=*/false);
Eric Liub9bf1b52016-11-08 22:44:17 +0000356 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:09 +0000376 // Match namespace alias declarations.
377 Finder->addMatcher(namespaceAliasDecl(isExpansionInFileMatching(FilePattern),
378 IsVisibleInNewNs)
379 .bind("namespace_alias"),
380 this);
Eric Liub9bf1b52016-11-08 22:44:17 +0000381
382 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32 +0000383 Finder->addMatcher(
384 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
385 .bind("old_ns"),
386 this);
387
Eric Liu41552d62016-12-07 14:20:52 +0000388 // 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:32 +0000396 Finder->addMatcher(
Eric Liu41552d62016-12-07 14:20:52 +0000397 classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))),
398 IsInMovedNs, hasParent(namespaceDecl()))
399 .bind("template_class_fwd_decl"),
Eric Liu495b2112016-09-19 17:40:32 +0000400 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:48 +0000408 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32 +0000409 hasAncestor(cxxRecordDecl()),
410 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48 +0000411
Eric Liu8685c762016-12-07 17:04:07 +0000412 // 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:32 +0000418 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29 +0000419 // 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:32 +0000422 Finder->addMatcher(
423 typeLoc(IsInMovedNs,
424 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29 +0000425 unless(anyOf(hasParent(typeLoc(loc(qualType(
426 allOf(hasDeclaration(DeclMatcher),
427 unless(templateSpecializationType())))))),
Eric Liu8685c762016-12-07 17:04:07 +0000428 hasParent(nestedNameSpecifierLoc()),
429 hasAncestor(isImplicit()),
430 hasAncestor(UsingShadowDeclInClass))),
Eric Liu495b2112016-09-19 17:40:32 +0000431 hasAncestor(decl().bind("dc")))
432 .bind("type"),
433 this);
Eric Liu912d0392016-09-27 12:54:48 +0000434
Eric Liu68765a82016-09-21 15:06:12 +0000435 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
436 // special case it.
Eric Liu8685c762016-12-07 17:04:07 +0000437 // Since using declarations inside classes must have the base class in the
438 // nested name specifier, we leave it to the nested name specifier matcher.
439 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()),
440 unless(UsingShadowDeclInClass))
Eric Liub9bf1b52016-11-08 22:44:17 +0000441 .bind("using_with_shadow"),
442 this);
Eric Liu912d0392016-09-27 12:54:48 +0000443
Eric Liuff51f012016-11-16 16:54:53 +0000444 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
445 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
446 // "A::A" would have already been fixed.
Eric Liu8685c762016-12-07 17:04:07 +0000447 Finder->addMatcher(
448 nestedNameSpecifierLoc(
449 hasAncestor(decl(IsInMovedNs).bind("dc")),
450 loc(nestedNameSpecifier(
451 specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
452 unless(anyOf(hasAncestor(isImplicit()),
453 hasAncestor(UsingShadowDeclInClass),
454 hasAncestor(typeLoc(loc(qualType(hasDeclaration(
455 decl(equalsBoundNode("from_decl"))))))))))
456 .bind("nested_specifier_loc"),
457 this);
Eric Liu12068d82016-09-22 11:54:00 +0000458
Eric Liuff51f012016-11-16 16:54:53 +0000459 // Matches base class initializers in constructors. TypeLocs of base class
460 // initializers do not need to be fixed. For example,
461 // class X : public a::b::Y {
462 // public:
463 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
464 // };
465 Finder->addMatcher(
466 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
467
Eric Liu12068d82016-09-22 11:54:00 +0000468 // Handle function.
Eric Liu912d0392016-09-27 12:54:48 +0000469 // Only handle functions that are defined in a namespace excluding member
470 // function, static methods (qualified by nested specifier), and functions
471 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00 +0000472 // Note that the matcher does not exclude calls to out-of-line static method
473 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48 +0000474 auto FuncMatcher =
475 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
476 hasAncestor(namespaceDecl(isAnonymous())),
477 hasAncestor(cxxRecordDecl()))),
478 hasParent(namespaceDecl()));
Eric Liuda22b3c2016-11-29 14:15:14 +0000479 Finder->addMatcher(decl(forEachDescendant(expr(anyOf(
480 callExpr(callee(FuncMatcher)).bind("call"),
481 declRefExpr(to(FuncMatcher.bind("func_decl")))
482 .bind("func_ref")))),
483 IsInMovedNs, unless(isImplicit()))
484 .bind("dc"),
485 this);
Eric Liu159f0132016-09-30 04:32:39 +0000486
487 auto GlobalVarMatcher = varDecl(
488 hasGlobalStorage(), hasParent(namespaceDecl()),
489 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
490 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
491 to(GlobalVarMatcher.bind("var_decl")))
492 .bind("var_ref"),
493 this);
Eric Liu0325a772017-02-02 17:40:38 +0000494
495 // Handle unscoped enum constant.
496 auto UnscopedEnumMatcher = enumConstantDecl(hasParent(enumDecl(
497 hasParent(namespaceDecl()),
498 unless(anyOf(isScoped(), IsInMovedNs, hasAncestor(cxxRecordDecl()),
499 hasAncestor(namespaceDecl(isAnonymous())))))));
500 Finder->addMatcher(
501 declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
502 to(UnscopedEnumMatcher.bind("enum_const_decl")))
503 .bind("enum_const_ref"),
504 this);
Eric Liu495b2112016-09-19 17:40:32 +0000505}
506
507void ChangeNamespaceTool::run(
508 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17 +0000509 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
510 UsingDecls.insert(Using);
511 } else if (const auto *UsingNamespace =
512 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
513 "using_namespace")) {
514 UsingNamespaceDecls.insert(UsingNamespace);
Eric Liu180dac62016-12-23 10:47:09 +0000515 } else if (const auto *NamespaceAlias =
516 Result.Nodes.getNodeAs<NamespaceAliasDecl>(
517 "namespace_alias")) {
518 NamespaceAliasDecls.insert(NamespaceAlias);
Eric Liub9bf1b52016-11-08 22:44:17 +0000519 } else if (const auto *NsDecl =
520 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32 +0000521 moveOldNamespace(Result, NsDecl);
522 } else if (const auto *FwdDecl =
Eric Liu41552d62016-12-07 14:20:52 +0000523 Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) {
524 moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl));
525 } else if (const auto *TemplateFwdDecl =
526 Result.Nodes.getNodeAs<ClassTemplateDecl>(
527 "template_class_fwd_decl")) {
528 moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl));
Eric Liub9bf1b52016-11-08 22:44:17 +0000529 } else if (const auto *UsingWithShadow =
530 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
531 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12 +0000532 } else if (const auto *Specifier =
533 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
534 "nested_specifier_loc")) {
535 SourceLocation Start = Specifier->getBeginLoc();
Eric Liuc265b022016-12-01 17:25:55 +0000536 SourceLocation End = endLocationForType(Specifier->getTypeLoc());
Eric Liu68765a82016-09-21 15:06:12 +0000537 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53 +0000538 } else if (const auto *BaseInitializer =
539 Result.Nodes.getNodeAs<CXXCtorInitializer>(
540 "base_initializer")) {
541 BaseCtorInitializerTypeLocs.push_back(
542 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00 +0000543 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu26cf68a2016-12-15 10:42:35 +0000544 // This avoids fixing types with record types as qualifier, which is not
545 // filtered by matchers in some cases, e.g. the type is templated. We should
546 // handle the record type qualifier instead.
Eric Liu0c0aea02016-12-15 13:02:41 +0000547 TypeLoc Loc = *TLoc;
548 while (Loc.getTypeLocClass() == TypeLoc::Qualified)
549 Loc = Loc.getNextTypeLoc();
550 if (Loc.getTypeLocClass() == TypeLoc::Elaborated) {
Eric Liu26cf68a2016-12-15 10:42:35 +0000551 NestedNameSpecifierLoc NestedNameSpecifier =
Eric Liu0c0aea02016-12-15 13:02:41 +0000552 Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
Eric Liu26cf68a2016-12-15 10:42:35 +0000553 const Type *SpecifierType =
554 NestedNameSpecifier.getNestedNameSpecifier()->getAsType();
555 if (SpecifierType && SpecifierType->isRecordType())
556 return;
557 }
Eric Liu0c0aea02016-12-15 13:02:41 +0000558 fixTypeLoc(Result, startLocationForType(Loc), endLocationForType(Loc), Loc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000559 } else if (const auto *VarRef =
560 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39 +0000561 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
562 assert(Var);
563 if (Var->getCanonicalDecl()->isStaticDataMember())
564 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000565 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu159f0132016-09-30 04:32:39 +0000566 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000567 fixDeclRefExpr(Result, Context->getDeclContext(),
568 llvm::cast<NamedDecl>(Var), VarRef);
Eric Liu0325a772017-02-02 17:40:38 +0000569 } else if (const auto *EnumConstRef =
570 Result.Nodes.getNodeAs<DeclRefExpr>("enum_const_ref")) {
571 // Do not rename the reference if it is already scoped by the EnumDecl name.
572 if (EnumConstRef->hasQualifier() &&
Eric Liu28c30ce2017-02-02 19:46:12 +0000573 EnumConstRef->getQualifier()->getKind() ==
574 NestedNameSpecifier::SpecifierKind::TypeSpec &&
Eric Liu0325a772017-02-02 17:40:38 +0000575 EnumConstRef->getQualifier()->getAsType()->isEnumeralType())
576 return;
577 const auto *EnumConstDecl =
578 Result.Nodes.getNodeAs<EnumConstantDecl>("enum_const_decl");
579 assert(EnumConstDecl);
580 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
581 assert(Context && "Empty decl context.");
582 // FIXME: this would qualify "ns::VALUE" as "ns::EnumValue::VALUE". Fix it
583 // if it turns out to be an issue.
584 fixDeclRefExpr(Result, Context->getDeclContext(),
585 llvm::cast<NamedDecl>(EnumConstDecl), EnumConstRef);
Eric Liuda22b3c2016-11-29 14:15:14 +0000586 } else if (const auto *FuncRef =
587 Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) {
Eric Liue3f35e42016-12-20 14:39:04 +0000588 // If this reference has been processed as a function call, we do not
589 // process it again.
590 if (ProcessedFuncRefs.count(FuncRef))
591 return;
592 ProcessedFuncRefs.insert(FuncRef);
Eric Liuda22b3c2016-11-29 14:15:14 +0000593 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
594 assert(Func);
595 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
596 assert(Context && "Empty decl context.");
597 fixDeclRefExpr(Result, Context->getDeclContext(),
598 llvm::cast<NamedDecl>(Func), FuncRef);
Eric Liu12068d82016-09-22 11:54:00 +0000599 } else {
Eric Liuda22b3c2016-11-29 14:15:14 +0000600 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000601 assert(Call != nullptr && "Expecting callback for CallExpr.");
Eric Liue3f35e42016-12-20 14:39:04 +0000602 const auto *CalleeFuncRef =
603 llvm::cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit());
604 ProcessedFuncRefs.insert(CalleeFuncRef);
Eric Liuda22b3c2016-11-29 14:15:14 +0000605 const FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00 +0000606 assert(Func != nullptr);
Eric Liue3f35e42016-12-20 14:39:04 +0000607 // FIXME: ignore overloaded operators. This would miss cases where operators
608 // are called by qualified names (i.e. "ns::operator <"). Ignore such
609 // cases for now.
610 if (Func->isOverloadedOperator())
611 return;
Eric Liu12068d82016-09-22 11:54:00 +0000612 // Ignore out-of-line static methods since they will be handled by nested
613 // name specifiers.
614 if (Func->getCanonicalDecl()->getStorageClass() ==
Eric Liuda22b3c2016-11-29 14:15:14 +0000615 StorageClass::SC_Static &&
Eric Liu12068d82016-09-22 11:54:00 +0000616 Func->isOutOfLine())
617 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000618 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu12068d82016-09-22 11:54:00 +0000619 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000620 SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17 +0000621 replaceQualifiedSymbolInDeclContext(
622 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34 +0000623 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32 +0000624 }
625}
626
Eric Liu73f49fd2016-10-12 12:34:18 +0000627static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
628 const SourceManager &SM,
629 const LangOptions &LangOpts) {
630 std::unique_ptr<Lexer> Lex =
631 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
632 assert(Lex.get() &&
633 "Failed to create lexer from the beginning of namespace.");
634 if (!Lex.get())
635 return SourceLocation();
636 Token Tok;
637 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
638 }
639 return Tok.isNot(tok::TokenKind::l_brace)
640 ? SourceLocation()
641 : Tok.getEndLoc().getLocWithOffset(1);
642}
643
Eric Liu495b2112016-09-19 17:40:32 +0000644// Stores information about a moved namespace in `MoveNamespaces` and leaves
645// the actual movement to `onEndOfTranslationUnit()`.
646void ChangeNamespaceTool::moveOldNamespace(
647 const ast_matchers::MatchFinder::MatchResult &Result,
648 const NamespaceDecl *NsDecl) {
649 // If the namespace is empty, do nothing.
650 if (Decl::castToDeclContext(NsDecl)->decls_empty())
651 return;
652
Eric Liuee5104b2017-01-04 14:49:08 +0000653 const SourceManager &SM = *Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32 +0000654 // Get the range of the code in the old namespace.
Eric Liuee5104b2017-01-04 14:49:08 +0000655 SourceLocation Start =
656 getLocAfterNamespaceLBrace(NsDecl, SM, Result.Context->getLangOpts());
Eric Liu73f49fd2016-10-12 12:34:18 +0000657 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32 +0000658 MoveNamespace MoveNs;
Eric Liuee5104b2017-01-04 14:49:08 +0000659 MoveNs.Offset = SM.getFileOffset(Start);
660 // The range of the moved namespace is from the location just past the left
661 // brace to the location right before the right brace.
662 MoveNs.Length = SM.getFileOffset(NsDecl->getRBraceLoc()) - MoveNs.Offset;
Eric Liu495b2112016-09-19 17:40:32 +0000663
664 // Insert the new namespace after `DiffOldNamespace`. For example, if
665 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
666 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
667 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
668 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01 +0000669 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
670 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000671 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01 +0000672 SourceLocation InsertionLoc = Start;
673 if (OuterNs) {
Eric Liuee5104b2017-01-04 14:49:08 +0000674 SourceLocation LocAfterNs = getStartOfNextLine(
675 OuterNs->getRBraceLoc(), SM, Result.Context->getLangOpts());
Eric Liu6aa94162016-11-10 18:29:01 +0000676 assert(LocAfterNs.isValid() &&
677 "Failed to get location after DiffOldNamespace");
678 InsertionLoc = LocAfterNs;
679 }
Eric Liuee5104b2017-01-04 14:49:08 +0000680 MoveNs.InsertionOffset = SM.getFileOffset(SM.getSpellingLoc(InsertionLoc));
681 MoveNs.FID = SM.getFileID(Start);
Eric Liucc83c662016-09-19 17:58:59 +0000682 MoveNs.SourceMgr = Result.SourceManager;
Eric Liuee5104b2017-01-04 14:49:08 +0000683 MoveNamespaces[SM.getFilename(Start)].push_back(MoveNs);
Eric Liu495b2112016-09-19 17:40:32 +0000684}
685
686// Removes a class forward declaration from the code in the moved namespace and
687// creates an `InsertForwardDeclaration` to insert the forward declaration back
688// into the old namespace after moving code from the old namespace to the new
689// namespace.
690// For example, changing "a" to "x":
691// Old code:
692// namespace a {
693// class FWD;
694// class A { FWD *fwd; }
695// } // a
696// New code:
697// namespace a {
698// class FWD;
699// } // a
700// namespace x {
701// class A { a::FWD *fwd; }
702// } // x
703void ChangeNamespaceTool::moveClassForwardDeclaration(
704 const ast_matchers::MatchFinder::MatchResult &Result,
Eric Liu41552d62016-12-07 14:20:52 +0000705 const NamedDecl *FwdDecl) {
Eric Liu495b2112016-09-19 17:40:32 +0000706 SourceLocation Start = FwdDecl->getLocStart();
707 SourceLocation End = FwdDecl->getLocEnd();
Eric Liu41367152017-03-01 10:29:39 +0000708 const SourceManager &SM = *Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32 +0000709 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
Eric Liu41367152017-03-01 10:29:39 +0000710 End, tok::semi, SM, Result.Context->getLangOpts(),
Eric Liu495b2112016-09-19 17:40:32 +0000711 /*SkipTrailingWhitespaceAndNewLine=*/true);
712 if (AfterSemi.isValid())
713 End = AfterSemi.getLocWithOffset(-1);
714 // Delete the forward declaration from the code to be moved.
Eric Liu41367152017-03-01 10:29:39 +0000715 addReplacementOrDie(Start, End, "", SM, &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32 +0000716 llvm::StringRef Code = Lexer::getSourceText(
Eric Liu41367152017-03-01 10:29:39 +0000717 CharSourceRange::getTokenRange(SM.getSpellingLoc(Start),
718 SM.getSpellingLoc(End)),
719 SM, Result.Context->getLangOpts());
Eric Liu495b2112016-09-19 17:40:32 +0000720 // Insert the forward declaration back into the old namespace after moving the
721 // code from old namespace to new namespace.
722 // Insertion information is stored in `InsertFwdDecls` and actual
723 // insertion will be performed in `onEndOfTranslationUnit`.
724 // Get the (old) namespace that contains the forward declaration.
725 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
726 // The namespace contains the forward declaration, so it must not be empty.
727 assert(!NsDecl->decls_empty());
Eric Liu41367152017-03-01 10:29:39 +0000728 const auto Insertion = createInsertion(
729 getLocAfterNamespaceLBrace(NsDecl, SM, Result.Context->getLangOpts()),
730 Code, SM);
Eric Liu495b2112016-09-19 17:40:32 +0000731 InsertForwardDeclaration InsertFwd;
732 InsertFwd.InsertionOffset = Insertion.getOffset();
733 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
734 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
735}
736
Eric Liub9bf1b52016-11-08 22:44:17 +0000737// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
738// FromDecl with the shortest qualified name possible when the reference is in
739// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32 +0000740void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17 +0000741 const ast_matchers::MatchFinder::MatchResult &Result,
742 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
743 const NamedDecl *FromDecl) {
744 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu4fe99e12016-12-14 17:01:52 +0000745 if (llvm::isa<TranslationUnitDecl>(NsDeclContext)) {
746 // This should not happen in usual unless the TypeLoc is in function type
747 // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of
748 // `T` will be the translation unit. We simply use fully-qualified name
749 // here.
750 // Note that `FromDecl` must not be defined in the old namespace (according
751 // to `DeclMatcher`), so its fully-qualified name will not change after
752 // changing the namespace.
753 addReplacementOrDie(Start, End, FromDecl->getQualifiedNameAsString(),
754 *Result.SourceManager, &FileToReplacements);
755 return;
756 }
Eric Liu231c6552016-11-10 18:15:34 +0000757 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32 +0000758 // Calculate the name of the `NsDecl` after it is moved to new namespace.
759 std::string OldNs = NsDecl->getQualifiedNameAsString();
760 llvm::StringRef Postfix = OldNs;
761 bool Consumed = Postfix.consume_front(OldNamespace);
762 assert(Consumed && "Expect OldNS to start with OldNamespace.");
763 (void)Consumed;
764 const std::string NewNs = (NewNamespace + Postfix).str();
765
766 llvm::StringRef NestedName = Lexer::getSourceText(
767 CharSourceRange::getTokenRange(
768 Result.SourceManager->getSpellingLoc(Start),
769 Result.SourceManager->getSpellingLoc(End)),
770 *Result.SourceManager, Result.Context->getLangOpts());
Eric Liub9bf1b52016-11-08 22:44:17 +0000771 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu7fccc992017-02-24 11:54:45 +0000772 for (llvm::Regex &RE : WhiteListedSymbolRegexes)
773 if (RE.match(FromDeclName))
774 return;
Eric Liu495b2112016-09-19 17:40:32 +0000775 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17 +0000776 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
777 // Checks if there is any using namespace declarations that can shorten the
778 // qualified name.
779 for (const auto *UsingNamespace : UsingNamespaceDecls) {
780 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
781 Start))
782 continue;
783 StringRef FromDeclNameRef = FromDeclName;
784 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
785 ->getQualifiedNameAsString())) {
786 FromDeclNameRef = FromDeclNameRef.drop_front(2);
787 if (FromDeclNameRef.size() < ReplaceName.size())
788 ReplaceName = FromDeclNameRef;
789 }
790 }
Eric Liu180dac62016-12-23 10:47:09 +0000791 // Checks if there is any namespace alias declarations that can shorten the
792 // qualified name.
793 for (const auto *NamespaceAlias : NamespaceAliasDecls) {
794 if (!isDeclVisibleAtLocation(*Result.SourceManager, NamespaceAlias, DeclCtx,
795 Start))
796 continue;
797 StringRef FromDeclNameRef = FromDeclName;
798 if (FromDeclNameRef.consume_front(
799 NamespaceAlias->getNamespace()->getQualifiedNameAsString() +
800 "::")) {
801 std::string AliasName = NamespaceAlias->getNameAsString();
802 std::string AliasQualifiedName =
803 NamespaceAlias->getQualifiedNameAsString();
804 // We only consider namespace aliases define in the global namepspace or
805 // in namespaces that are directly visible from the reference, i.e.
806 // ancestor of the `OldNs`. Note that declarations in ancestor namespaces
807 // but not visible in the new namespace is filtered out by
808 // "IsVisibleInNewNs" matcher.
809 if (AliasQualifiedName != AliasName) {
810 // The alias is defined in some namespace.
811 assert(StringRef(AliasQualifiedName).endswith("::" + AliasName));
812 llvm::StringRef AliasNs =
813 StringRef(AliasQualifiedName).drop_back(AliasName.size() + 2);
814 if (!llvm::StringRef(OldNs).startswith(AliasNs))
815 continue;
816 }
817 std::string NameWithAliasNamespace =
818 (AliasName + "::" + FromDeclNameRef).str();
819 if (NameWithAliasNamespace.size() < ReplaceName.size())
820 ReplaceName = NameWithAliasNamespace;
821 }
822 }
Eric Liub9bf1b52016-11-08 22:44:17 +0000823 // Checks if there is any using shadow declarations that can shorten the
824 // qualified name.
825 bool Matched = false;
826 for (const UsingDecl *Using : UsingDecls) {
827 if (Matched)
828 break;
829 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
830 for (const auto *UsingShadow : Using->shadows()) {
831 const auto *TargetDecl = UsingShadow->getTargetDecl();
Eric Liuae7de712017-02-02 15:29:54 +0000832 if (TargetDecl->getQualifiedNameAsString() ==
833 FromDecl->getQualifiedNameAsString()) {
Eric Liub9bf1b52016-11-08 22:44:17 +0000834 ReplaceName = FromDecl->getNameAsString();
835 Matched = true;
836 break;
837 }
838 }
839 }
840 }
Eric Liu495b2112016-09-19 17:40:32 +0000841 // If the new nested name in the new namespace is the same as it was in the
842 // old namespace, we don't create replacement.
Eric Liu91229162017-01-26 16:31:32 +0000843 if (NestedName == ReplaceName ||
844 (NestedName.startswith("::") && NestedName.drop_front(2) == ReplaceName))
Eric Liu495b2112016-09-19 17:40:32 +0000845 return;
Eric Liu97f87ad2016-12-07 20:08:02 +0000846 // If the reference need to be fully-qualified, add a leading "::" unless
847 // NewNamespace is the global namespace.
Eric Liu8bc24162017-03-21 12:41:59 +0000848 if (ReplaceName == FromDeclName && !NewNamespace.empty() &&
849 conflictInNamespace(ReplaceName, NewNamespace))
Eric Liu97f87ad2016-12-07 20:08:02 +0000850 ReplaceName = "::" + ReplaceName;
Eric Liu4fe99e12016-12-14 17:01:52 +0000851 addReplacementOrDie(Start, End, ReplaceName, *Result.SourceManager,
852 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32 +0000853}
854
855// Replace the [Start, End] of `Type` with the shortest qualified name when the
856// `Type` is in `NewNamespace`.
857void ChangeNamespaceTool::fixTypeLoc(
858 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
859 SourceLocation End, TypeLoc Type) {
860 // FIXME: do not rename template parameter.
861 if (Start.isInvalid() || End.isInvalid())
862 return;
Eric Liuff51f012016-11-16 16:54:53 +0000863 // Types of CXXCtorInitializers do not need to be fixed.
864 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
865 return;
Eric Liu284b97c2017-03-17 14:05:39 +0000866 if (isTemplateParameter(Type))
867 return;
Eric Liu495b2112016-09-19 17:40:32 +0000868 // The declaration which this TypeLoc refers to.
869 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
870 // `hasDeclaration` gives underlying declaration, but if the type is
871 // a typedef type, we need to use the typedef type instead.
Eric Liu26cf68a2016-12-15 10:42:35 +0000872 auto IsInMovedNs = [&](const NamedDecl *D) {
873 if (!llvm::StringRef(D->getQualifiedNameAsString())
874 .startswith(OldNamespace + "::"))
875 return false;
876 auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getLocStart());
877 if (ExpansionLoc.isInvalid())
878 return false;
879 llvm::StringRef Filename = Result.SourceManager->getFilename(ExpansionLoc);
880 return FilePatternRE.match(Filename);
881 };
882 // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if
883 // `Type` is an alias type, we make `FromDecl` the type alias declaration.
884 // Also, don't fix the \p Type if it refers to a type alias decl in the moved
885 // namespace since the alias decl will be moved along with the type reference.
Eric Liu32158862016-11-14 19:37:55 +0000886 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32 +0000887 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55 +0000888 if (IsInMovedNs(FromDecl))
889 return;
Eric Liu26cf68a2016-12-15 10:42:35 +0000890 } else if (auto *TemplateType =
891 Type.getType()->getAs<TemplateSpecializationType>()) {
892 if (TemplateType->isTypeAlias()) {
893 FromDecl = TemplateType->getTemplateName().getAsTemplateDecl();
894 if (IsInMovedNs(FromDecl))
895 return;
896 }
Eric Liu32158862016-11-14 19:37:55 +0000897 }
Piotr Padlewski08124b12016-12-14 15:29:23 +0000898 const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu495b2112016-09-19 17:40:32 +0000899 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17 +0000900 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
901 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32 +0000902}
903
Eric Liu68765a82016-09-21 15:06:12 +0000904void ChangeNamespaceTool::fixUsingShadowDecl(
905 const ast_matchers::MatchFinder::MatchResult &Result,
906 const UsingDecl *UsingDeclaration) {
907 SourceLocation Start = UsingDeclaration->getLocStart();
908 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000909 if (Start.isInvalid() || End.isInvalid())
910 return;
Eric Liu68765a82016-09-21 15:06:12 +0000911
912 assert(UsingDeclaration->shadow_size() > 0);
913 // FIXME: it might not be always accurate to use the first using-decl.
914 const NamedDecl *TargetDecl =
915 UsingDeclaration->shadow_begin()->getTargetDecl();
916 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
917 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
918 // sense. If this happens, we need to use name with the new namespace.
919 // Use fully qualified name in UsingDecl for now.
Eric Liu4fe99e12016-12-14 17:01:52 +0000920 addReplacementOrDie(Start, End, "using ::" + TargetDeclName,
921 *Result.SourceManager, &FileToReplacements);
Eric Liu68765a82016-09-21 15:06:12 +0000922}
923
Eric Liuda22b3c2016-11-29 14:15:14 +0000924void ChangeNamespaceTool::fixDeclRefExpr(
925 const ast_matchers::MatchFinder::MatchResult &Result,
926 const DeclContext *UseContext, const NamedDecl *From,
927 const DeclRefExpr *Ref) {
928 SourceRange RefRange = Ref->getSourceRange();
929 replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(),
930 RefRange.getEnd(), From);
931}
932
Eric Liu495b2112016-09-19 17:40:32 +0000933void ChangeNamespaceTool::onEndOfTranslationUnit() {
934 // Move namespace blocks and insert forward declaration to old namespace.
935 for (const auto &FileAndNsMoves : MoveNamespaces) {
936 auto &NsMoves = FileAndNsMoves.second;
937 if (NsMoves.empty())
938 continue;
939 const std::string &FilePath = FileAndNsMoves.first;
940 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59 +0000941 auto &SM = *NsMoves.begin()->SourceMgr;
942 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32 +0000943 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
944 if (!ChangedCode) {
945 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
946 continue;
947 }
948 // Replacements on the changed code for moving namespaces and inserting
949 // forward declarations to old namespaces.
950 tooling::Replacements NewReplacements;
951 // Cut the changed code from the old namespace and paste the code in the new
952 // namespace.
953 for (const auto &NsMove : NsMoves) {
954 // Calculate the range of the old namespace block in the changed
955 // code.
956 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
957 const unsigned NewLength =
958 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
959 NewOffset;
960 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
961 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
962 std::string MovedCodeWrappedInNewNs =
963 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
964 // Calculate the new offset at which the code will be inserted in the
965 // changed code.
966 unsigned NewInsertionOffset =
967 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
968 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
969 MovedCodeWrappedInNewNs);
970 addOrMergeReplacement(Deletion, &NewReplacements);
971 addOrMergeReplacement(Insertion, &NewReplacements);
972 }
973 // After moving namespaces, insert forward declarations back to old
974 // namespaces.
975 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
976 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
977 unsigned NewInsertionOffset =
978 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
979 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
980 FwdDeclInsertion.ForwardDeclText);
981 addOrMergeReplacement(Insertion, &NewReplacements);
982 }
983 // Add replacements referring to the changed code to existing replacements,
984 // which refers to the original code.
985 Replaces = Replaces.merge(NewReplacements);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000986 auto Style = format::getStyle("file", FilePath, FallbackStyle);
987 if (!Style) {
988 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
989 continue;
990 }
Eric Liu495b2112016-09-19 17:40:32 +0000991 // Clean up old namespaces if there is nothing in it after moving.
992 auto CleanReplacements =
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000993 format::cleanupAroundReplacements(Code, Replaces, *Style);
Eric Liu495b2112016-09-19 17:40:32 +0000994 if (!CleanReplacements) {
995 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
996 continue;
997 }
998 FileToReplacements[FilePath] = *CleanReplacements;
999 }
Eric Liuc265b022016-12-01 17:25:55 +00001000
1001 // Make sure we don't generate replacements for files that do not match
1002 // FilePattern.
1003 for (auto &Entry : FileToReplacements)
1004 if (!FilePatternRE.match(Entry.first))
1005 Entry.second.clear();
Eric Liu495b2112016-09-19 17:40:32 +00001006}
1007
1008} // namespace change_namespace
1009} // namespace clang