blob: 5c9067f099175a527d85f58c871c6ff5ae43e82f [file] [log] [blame]
Eric Liu495b2112016-09-19 17:40:321//===-- ChangeNamespace.cpp - Change namespace implementation -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "ChangeNamespace.h"
10#include "clang/Format/Format.h"
11#include "clang/Lex/Lexer.h"
Eric Liuff51f012016-11-16 16:54:5312#include "llvm/Support/ErrorHandling.h"
Eric Liu495b2112016-09-19 17:40:3213
14using namespace clang::ast_matchers;
15
16namespace clang {
17namespace change_namespace {
18
19namespace {
20
21inline std::string
22joinNamespaces(const llvm::SmallVectorImpl<StringRef> &Namespaces) {
23 if (Namespaces.empty())
24 return "";
25 std::string Result = Namespaces.front();
26 for (auto I = Namespaces.begin() + 1, E = Namespaces.end(); I != E; ++I)
27 Result += ("::" + *I).str();
28 return Result;
29}
30
31SourceLocation startLocationForType(TypeLoc TLoc) {
32 // For elaborated types (e.g. `struct a::A`) we want the portion after the
33 // `struct` but including the namespace qualifier, `a::`.
34 if (TLoc.getTypeLocClass() == TypeLoc::Elaborated) {
35 NestedNameSpecifierLoc NestedNameSpecifier =
36 TLoc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
37 if (NestedNameSpecifier.getNestedNameSpecifier())
38 return NestedNameSpecifier.getBeginLoc();
39 TLoc = TLoc.getNextTypeLoc();
40 }
41 return TLoc.getLocStart();
42}
43
Eric Liuc265b022016-12-01 17:25:5544SourceLocation endLocationForType(TypeLoc TLoc) {
Eric Liu495b2112016-09-19 17:40:3245 // Dig past any namespace or keyword qualifications.
46 while (TLoc.getTypeLocClass() == TypeLoc::Elaborated ||
47 TLoc.getTypeLocClass() == TypeLoc::Qualified)
48 TLoc = TLoc.getNextTypeLoc();
49
50 // The location for template specializations (e.g. Foo<int>) includes the
51 // templated types in its location range. We want to restrict this to just
52 // before the `<` character.
53 if (TLoc.getTypeLocClass() == TypeLoc::TemplateSpecialization)
54 return TLoc.castAs<TemplateSpecializationTypeLoc>()
55 .getLAngleLoc()
56 .getLocWithOffset(-1);
57 return TLoc.getEndLoc();
58}
59
60// Returns the containing namespace of `InnerNs` by skipping `PartialNsName`.
Eric Liu6aa94162016-11-10 18:29:0161// If the `InnerNs` does not have `PartialNsName` as suffix, or `PartialNsName`
62// is empty, nullptr is returned.
Eric Liu495b2112016-09-19 17:40:3263// For example, if `InnerNs` is "a::b::c" and `PartialNsName` is "b::c", then
64// the NamespaceDecl of namespace "a" will be returned.
65const NamespaceDecl *getOuterNamespace(const NamespaceDecl *InnerNs,
66 llvm::StringRef PartialNsName) {
Eric Liu6aa94162016-11-10 18:29:0167 if (!InnerNs || PartialNsName.empty())
68 return nullptr;
Eric Liu495b2112016-09-19 17:40:3269 const auto *CurrentContext = llvm::cast<DeclContext>(InnerNs);
70 const auto *CurrentNs = InnerNs;
71 llvm::SmallVector<llvm::StringRef, 4> PartialNsNameSplitted;
Eric Liu6aa94162016-11-10 18:29:0172 PartialNsName.split(PartialNsNameSplitted, "::", /*MaxSplit=*/-1,
73 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:3274 while (!PartialNsNameSplitted.empty()) {
75 // Get the inner-most namespace in CurrentContext.
76 while (CurrentContext && !llvm::isa<NamespaceDecl>(CurrentContext))
77 CurrentContext = CurrentContext->getParent();
78 if (!CurrentContext)
79 return nullptr;
80 CurrentNs = llvm::cast<NamespaceDecl>(CurrentContext);
81 if (PartialNsNameSplitted.back() != CurrentNs->getNameAsString())
82 return nullptr;
83 PartialNsNameSplitted.pop_back();
84 CurrentContext = CurrentContext->getParent();
85 }
86 return CurrentNs;
87}
88
Eric Liu73f49fd2016-10-12 12:34:1889static std::unique_ptr<Lexer>
90getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM,
91 const LangOptions &LangOpts) {
Eric Liu495b2112016-09-19 17:40:3292 if (Loc.isMacroID() &&
93 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eric Liu73f49fd2016-10-12 12:34:1894 return nullptr;
Eric Liu495b2112016-09-19 17:40:3295 // Break down the source location.
96 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
97 // Try to load the file buffer.
98 bool InvalidTemp = false;
99 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
100 if (InvalidTemp)
Eric Liu73f49fd2016-10-12 12:34:18101 return nullptr;
Eric Liu495b2112016-09-19 17:40:32102
103 const char *TokBegin = File.data() + LocInfo.second;
104 // Lex from the start of the given location.
Eric Liu73f49fd2016-10-12 12:34:18105 return llvm::make_unique<Lexer>(SM.getLocForStartOfFile(LocInfo.first),
106 LangOpts, File.begin(), TokBegin, File.end());
107}
Eric Liu495b2112016-09-19 17:40:32108
Eric Liu73f49fd2016-10-12 12:34:18109// FIXME: get rid of this helper function if this is supported in clang-refactor
110// library.
111static SourceLocation getStartOfNextLine(SourceLocation Loc,
112 const SourceManager &SM,
113 const LangOptions &LangOpts) {
114 std::unique_ptr<Lexer> Lex = getLexerStartingFromLoc(Loc, SM, LangOpts);
115 if (!Lex.get())
116 return SourceLocation();
Eric Liu495b2112016-09-19 17:40:32117 llvm::SmallVector<char, 16> Line;
118 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
Eric Liu73f49fd2016-10-12 12:34:18119 Lex->setParsingPreprocessorDirective(true);
120 Lex->ReadToEndOfLine(&Line);
Haojian Wuef8a6dc2016-10-04 10:35:53121 auto End = Loc.getLocWithOffset(Line.size());
Eric Liu73f49fd2016-10-12 12:34:18122 return SM.getLocForEndOfFile(SM.getDecomposedLoc(Loc).first) == End
123 ? End
124 : End.getLocWithOffset(1);
Eric Liu495b2112016-09-19 17:40:32125}
126
127// Returns `R` with new range that refers to code after `Replaces` being
128// applied.
129tooling::Replacement
130getReplacementInChangedCode(const tooling::Replacements &Replaces,
131 const tooling::Replacement &R) {
132 unsigned NewStart = Replaces.getShiftedCodePosition(R.getOffset());
133 unsigned NewEnd =
134 Replaces.getShiftedCodePosition(R.getOffset() + R.getLength());
135 return tooling::Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
136 R.getReplacementText());
137}
138
139// Adds a replacement `R` into `Replaces` or merges it into `Replaces` by
140// applying all existing Replaces first if there is conflict.
141void addOrMergeReplacement(const tooling::Replacement &R,
142 tooling::Replacements *Replaces) {
143 auto Err = Replaces->add(R);
144 if (Err) {
145 llvm::consumeError(std::move(Err));
146 auto Replace = getReplacementInChangedCode(*Replaces, R);
147 *Replaces = Replaces->merge(tooling::Replacements(Replace));
148 }
149}
150
151tooling::Replacement createReplacement(SourceLocation Start, SourceLocation End,
152 llvm::StringRef ReplacementText,
153 const SourceManager &SM) {
154 if (!Start.isValid() || !End.isValid()) {
155 llvm::errs() << "start or end location were invalid\n";
156 return tooling::Replacement();
157 }
158 if (SM.getDecomposedLoc(Start).first != SM.getDecomposedLoc(End).first) {
159 llvm::errs()
160 << "start or end location were in different macro expansions\n";
161 return tooling::Replacement();
162 }
163 Start = SM.getSpellingLoc(Start);
164 End = SM.getSpellingLoc(End);
165 if (SM.getFileID(Start) != SM.getFileID(End)) {
166 llvm::errs() << "start or end location were in different files\n";
167 return tooling::Replacement();
168 }
169 return tooling::Replacement(
170 SM, CharSourceRange::getTokenRange(SM.getSpellingLoc(Start),
171 SM.getSpellingLoc(End)),
172 ReplacementText);
173}
174
Eric Liu4fe99e12016-12-14 17:01:52175void addReplacementOrDie(
176 SourceLocation Start, SourceLocation End, llvm::StringRef ReplacementText,
177 const SourceManager &SM,
178 std::map<std::string, tooling::Replacements> *FileToReplacements) {
179 const auto R = createReplacement(Start, End, ReplacementText, SM);
180 auto Err = (*FileToReplacements)[R.getFilePath()].add(R);
181 if (Err)
182 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
183}
184
Eric Liu495b2112016-09-19 17:40:32185tooling::Replacement createInsertion(SourceLocation Loc,
186 llvm::StringRef InsertText,
187 const SourceManager &SM) {
188 if (Loc.isInvalid()) {
189 llvm::errs() << "insert Location is invalid.\n";
190 return tooling::Replacement();
191 }
192 Loc = SM.getSpellingLoc(Loc);
193 return tooling::Replacement(SM, Loc, 0, InsertText);
194}
195
196// Returns the shortest qualified name for declaration `DeclName` in the
197// namespace `NsName`. For example, if `DeclName` is "a::b::X" and `NsName`
198// is "a::c::d", then "b::X" will be returned.
Eric Liubc715502017-01-26 15:08:44199// Note that if `DeclName` is `::b::X` and `NsName` is `::a::b`, this returns
200// "::b::X" instead of "b::X" since there will be a name conflict otherwise.
Eric Liu447164d2016-10-05 15:52:39201// \param DeclName A fully qualified name, "::a::b::X" or "a::b::X".
202// \param NsName A fully qualified name, "::a::b" or "a::b". Global namespace
203// will have empty name.
Eric Liu495b2112016-09-19 17:40:32204std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
205 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39206 DeclName = DeclName.ltrim(':');
207 NsName = NsName.ltrim(':');
Eric Liu447164d2016-10-05 15:52:39208 if (DeclName.find(':') == llvm::StringRef::npos)
Eric Liub9bf1b52016-11-08 22:44:17209 return DeclName;
Eric Liu447164d2016-10-05 15:52:39210
Eric Liubc715502017-01-26 15:08:44211 llvm::SmallVector<llvm::StringRef, 4> NsNameSplitted;
212 NsName.split(NsNameSplitted, "::", /*MaxSplit=*/-1,
213 /*KeepEmpty=*/false);
214 llvm::SmallVector<llvm::StringRef, 4> DeclNsSplitted;
215 DeclName.split(DeclNsSplitted, "::", /*MaxSplit=*/-1,
216 /*KeepEmpty=*/false);
217 llvm::StringRef UnqualifiedDeclName = DeclNsSplitted.pop_back_val();
218 // If the Decl is in global namespace, there is no need to shorten it.
219 if (DeclNsSplitted.empty())
220 return UnqualifiedDeclName;
221 // If NsName is the global namespace, we can simply use the DeclName sans
222 // leading "::".
223 if (NsNameSplitted.empty())
224 return DeclName;
225
226 if (NsNameSplitted.front() != DeclNsSplitted.front()) {
227 // The DeclName must be fully-qualified, but we still need to decide if a
228 // leading "::" is necessary. For example, if `NsName` is "a::b::c" and the
229 // `DeclName` is "b::X", then the reference must be qualified as "::b::X"
230 // to avoid conflict.
231 if (llvm::is_contained(NsNameSplitted, DeclNsSplitted.front()))
232 return ("::" + DeclName).str();
233 return DeclName;
Eric Liu495b2112016-09-19 17:40:32234 }
Eric Liubc715502017-01-26 15:08:44235 // Since there is already an overlap namespace, we know that `DeclName` can be
236 // shortened, so we reduce the longest common prefix.
237 auto DeclI = DeclNsSplitted.begin();
238 auto DeclE = DeclNsSplitted.end();
239 auto NsI = NsNameSplitted.begin();
240 auto NsE = NsNameSplitted.end();
241 for (; DeclI != DeclE && NsI != NsE && *DeclI == *NsI; ++DeclI, ++NsI) {
242 }
243 return (DeclI == DeclE)
244 ? UnqualifiedDeclName.str()
245 : (llvm::join(DeclI, DeclE, "::") + "::" + UnqualifiedDeclName)
246 .str();
Eric Liu495b2112016-09-19 17:40:32247}
248
249std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) {
250 if (Code.back() != '\n')
251 Code += "\n";
252 llvm::SmallVector<StringRef, 4> NsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04253 NestedNs.split(NsSplitted, "::", /*MaxSplit=*/-1,
254 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32255 while (!NsSplitted.empty()) {
256 // FIXME: consider code style for comments.
257 Code = ("namespace " + NsSplitted.back() + " {\n" + Code +
258 "} // namespace " + NsSplitted.back() + "\n")
259 .str();
260 NsSplitted.pop_back();
261 }
262 return Code;
263}
264
Eric Liub9bf1b52016-11-08 22:44:17265// Returns true if \p D is a nested DeclContext in \p Context
266bool isNestedDeclContext(const DeclContext *D, const DeclContext *Context) {
267 while (D) {
268 if (D == Context)
269 return true;
270 D = D->getParent();
271 }
272 return false;
273}
274
275// Returns true if \p D is visible at \p Loc with DeclContext \p DeclCtx.
276bool isDeclVisibleAtLocation(const SourceManager &SM, const Decl *D,
277 const DeclContext *DeclCtx, SourceLocation Loc) {
278 SourceLocation DeclLoc = SM.getSpellingLoc(D->getLocation());
279 Loc = SM.getSpellingLoc(Loc);
280 return SM.isBeforeInTranslationUnit(DeclLoc, Loc) &&
281 (SM.getFileID(DeclLoc) == SM.getFileID(Loc) &&
282 isNestedDeclContext(DeclCtx, D->getDeclContext()));
283}
284
Eric Liu0325a772017-02-02 17:40:38285AST_MATCHER(EnumDecl, isScoped) {
286 return Node.isScoped();
287}
288
Eric Liu495b2112016-09-19 17:40:32289} // anonymous namespace
290
291ChangeNamespaceTool::ChangeNamespaceTool(
292 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
293 std::map<std::string, tooling::Replacements> *FileToReplacements,
294 llvm::StringRef FallbackStyle)
295 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
296 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
Eric Liuc265b022016-12-01 17:25:55297 FilePattern(FilePattern), FilePatternRE(FilePattern) {
Eric Liu495b2112016-09-19 17:40:32298 FileToReplacements->clear();
299 llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted;
300 llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted;
301 llvm::StringRef(OldNamespace).split(OldNsSplitted, "::");
302 llvm::StringRef(NewNamespace).split(NewNsSplitted, "::");
303 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
304 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
305 OldNsSplitted.front() == NewNsSplitted.front()) {
306 OldNsSplitted.erase(OldNsSplitted.begin());
307 NewNsSplitted.erase(NewNsSplitted.begin());
308 }
309 DiffOldNamespace = joinNamespaces(OldNsSplitted);
310 DiffNewNamespace = joinNamespaces(NewNsSplitted);
311}
312
Eric Liu495b2112016-09-19 17:40:32313void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32314 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17315 // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the
316 // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will
317 // be "a::b". Declarations in this namespace will not be visible in the new
318 // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-".
319 llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04320 llvm::StringRef(DiffOldNamespace)
321 .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1,
322 /*KeepEmpty=*/false);
Eric Liub9bf1b52016-11-08 22:44:17323 std::string Prefix = "-";
324 if (!DiffOldNsSplitted.empty())
325 Prefix = (StringRef(FullOldNs).drop_back(DiffOldNamespace.size()) +
326 DiffOldNsSplitted.front())
327 .str();
328 auto IsInMovedNs =
329 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
330 isExpansionInFileMatching(FilePattern));
331 auto IsVisibleInNewNs = anyOf(
332 IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Prefix)))));
333 // Match using declarations.
334 Finder->addMatcher(
335 usingDecl(isExpansionInFileMatching(FilePattern), IsVisibleInNewNs)
336 .bind("using"),
337 this);
338 // Match using namespace declarations.
339 Finder->addMatcher(usingDirectiveDecl(isExpansionInFileMatching(FilePattern),
340 IsVisibleInNewNs)
341 .bind("using_namespace"),
342 this);
Eric Liu180dac62016-12-23 10:47:09343 // Match namespace alias declarations.
344 Finder->addMatcher(namespaceAliasDecl(isExpansionInFileMatching(FilePattern),
345 IsVisibleInNewNs)
346 .bind("namespace_alias"),
347 this);
Eric Liub9bf1b52016-11-08 22:44:17348
349 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32350 Finder->addMatcher(
351 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
352 .bind("old_ns"),
353 this);
354
Eric Liu41552d62016-12-07 14:20:52355 // Match class forward-declarations in the old namespace.
356 // Note that forward-declarations in classes are not matched.
357 Finder->addMatcher(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())),
358 IsInMovedNs, hasParent(namespaceDecl()))
359 .bind("class_fwd_decl"),
360 this);
361
362 // Match template class forward-declarations in the old namespace.
Eric Liu495b2112016-09-19 17:40:32363 Finder->addMatcher(
Eric Liu41552d62016-12-07 14:20:52364 classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))),
365 IsInMovedNs, hasParent(namespaceDecl()))
366 .bind("template_class_fwd_decl"),
Eric Liu495b2112016-09-19 17:40:32367 this);
368
369 // Match references to types that are not defined in the old namespace.
370 // Forward-declarations in the old namespace are also matched since they will
371 // be moved back to the old namespace.
372 auto DeclMatcher = namedDecl(
373 hasAncestor(namespaceDecl()),
374 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48375 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32376 hasAncestor(cxxRecordDecl()),
377 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48378
Eric Liu8685c762016-12-07 17:04:07379 // Using shadow declarations in classes always refers to base class, which
380 // does not need to be qualified since it can be inferred from inheritance.
381 // Note that this does not match using alias declarations.
382 auto UsingShadowDeclInClass =
383 usingDecl(hasAnyUsingShadowDecl(decl()), hasParent(cxxRecordDecl()));
384
Eric Liu495b2112016-09-19 17:40:32385 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29386 // TypeLoc and template specialization arguments (which are not outermost)
387 // that are directly linked to types matching `DeclMatcher`. Nested name
388 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32389 Finder->addMatcher(
390 typeLoc(IsInMovedNs,
391 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29392 unless(anyOf(hasParent(typeLoc(loc(qualType(
393 allOf(hasDeclaration(DeclMatcher),
394 unless(templateSpecializationType())))))),
Eric Liu8685c762016-12-07 17:04:07395 hasParent(nestedNameSpecifierLoc()),
396 hasAncestor(isImplicit()),
397 hasAncestor(UsingShadowDeclInClass))),
Eric Liu495b2112016-09-19 17:40:32398 hasAncestor(decl().bind("dc")))
399 .bind("type"),
400 this);
Eric Liu912d0392016-09-27 12:54:48401
Eric Liu68765a82016-09-21 15:06:12402 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
403 // special case it.
Eric Liu8685c762016-12-07 17:04:07404 // Since using declarations inside classes must have the base class in the
405 // nested name specifier, we leave it to the nested name specifier matcher.
406 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()),
407 unless(UsingShadowDeclInClass))
Eric Liub9bf1b52016-11-08 22:44:17408 .bind("using_with_shadow"),
409 this);
Eric Liu912d0392016-09-27 12:54:48410
Eric Liuff51f012016-11-16 16:54:53411 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
412 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
413 // "A::A" would have already been fixed.
Eric Liu8685c762016-12-07 17:04:07414 Finder->addMatcher(
415 nestedNameSpecifierLoc(
416 hasAncestor(decl(IsInMovedNs).bind("dc")),
417 loc(nestedNameSpecifier(
418 specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
419 unless(anyOf(hasAncestor(isImplicit()),
420 hasAncestor(UsingShadowDeclInClass),
421 hasAncestor(typeLoc(loc(qualType(hasDeclaration(
422 decl(equalsBoundNode("from_decl"))))))))))
423 .bind("nested_specifier_loc"),
424 this);
Eric Liu12068d82016-09-22 11:54:00425
Eric Liuff51f012016-11-16 16:54:53426 // Matches base class initializers in constructors. TypeLocs of base class
427 // initializers do not need to be fixed. For example,
428 // class X : public a::b::Y {
429 // public:
430 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
431 // };
432 Finder->addMatcher(
433 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
434
Eric Liu12068d82016-09-22 11:54:00435 // Handle function.
Eric Liu912d0392016-09-27 12:54:48436 // Only handle functions that are defined in a namespace excluding member
437 // function, static methods (qualified by nested specifier), and functions
438 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00439 // Note that the matcher does not exclude calls to out-of-line static method
440 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48441 auto FuncMatcher =
442 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
443 hasAncestor(namespaceDecl(isAnonymous())),
444 hasAncestor(cxxRecordDecl()))),
445 hasParent(namespaceDecl()));
Eric Liuda22b3c2016-11-29 14:15:14446 Finder->addMatcher(decl(forEachDescendant(expr(anyOf(
447 callExpr(callee(FuncMatcher)).bind("call"),
448 declRefExpr(to(FuncMatcher.bind("func_decl")))
449 .bind("func_ref")))),
450 IsInMovedNs, unless(isImplicit()))
451 .bind("dc"),
452 this);
Eric Liu159f0132016-09-30 04:32:39453
454 auto GlobalVarMatcher = varDecl(
455 hasGlobalStorage(), hasParent(namespaceDecl()),
456 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
457 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
458 to(GlobalVarMatcher.bind("var_decl")))
459 .bind("var_ref"),
460 this);
Eric Liu0325a772017-02-02 17:40:38461
462 // Handle unscoped enum constant.
463 auto UnscopedEnumMatcher = enumConstantDecl(hasParent(enumDecl(
464 hasParent(namespaceDecl()),
465 unless(anyOf(isScoped(), IsInMovedNs, hasAncestor(cxxRecordDecl()),
466 hasAncestor(namespaceDecl(isAnonymous())))))));
467 Finder->addMatcher(
468 declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
469 to(UnscopedEnumMatcher.bind("enum_const_decl")))
470 .bind("enum_const_ref"),
471 this);
Eric Liu495b2112016-09-19 17:40:32472}
473
474void ChangeNamespaceTool::run(
475 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17476 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
477 UsingDecls.insert(Using);
478 } else if (const auto *UsingNamespace =
479 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
480 "using_namespace")) {
481 UsingNamespaceDecls.insert(UsingNamespace);
Eric Liu180dac62016-12-23 10:47:09482 } else if (const auto *NamespaceAlias =
483 Result.Nodes.getNodeAs<NamespaceAliasDecl>(
484 "namespace_alias")) {
485 NamespaceAliasDecls.insert(NamespaceAlias);
Eric Liub9bf1b52016-11-08 22:44:17486 } else if (const auto *NsDecl =
487 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32488 moveOldNamespace(Result, NsDecl);
489 } else if (const auto *FwdDecl =
Eric Liu41552d62016-12-07 14:20:52490 Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) {
491 moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl));
492 } else if (const auto *TemplateFwdDecl =
493 Result.Nodes.getNodeAs<ClassTemplateDecl>(
494 "template_class_fwd_decl")) {
495 moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl));
Eric Liub9bf1b52016-11-08 22:44:17496 } else if (const auto *UsingWithShadow =
497 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
498 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12499 } else if (const auto *Specifier =
500 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
501 "nested_specifier_loc")) {
502 SourceLocation Start = Specifier->getBeginLoc();
Eric Liuc265b022016-12-01 17:25:55503 SourceLocation End = endLocationForType(Specifier->getTypeLoc());
Eric Liu68765a82016-09-21 15:06:12504 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53505 } else if (const auto *BaseInitializer =
506 Result.Nodes.getNodeAs<CXXCtorInitializer>(
507 "base_initializer")) {
508 BaseCtorInitializerTypeLocs.push_back(
509 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00510 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu26cf68a2016-12-15 10:42:35511 // This avoids fixing types with record types as qualifier, which is not
512 // filtered by matchers in some cases, e.g. the type is templated. We should
513 // handle the record type qualifier instead.
Eric Liu0c0aea02016-12-15 13:02:41514 TypeLoc Loc = *TLoc;
515 while (Loc.getTypeLocClass() == TypeLoc::Qualified)
516 Loc = Loc.getNextTypeLoc();
517 if (Loc.getTypeLocClass() == TypeLoc::Elaborated) {
Eric Liu26cf68a2016-12-15 10:42:35518 NestedNameSpecifierLoc NestedNameSpecifier =
Eric Liu0c0aea02016-12-15 13:02:41519 Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
Eric Liu26cf68a2016-12-15 10:42:35520 const Type *SpecifierType =
521 NestedNameSpecifier.getNestedNameSpecifier()->getAsType();
522 if (SpecifierType && SpecifierType->isRecordType())
523 return;
524 }
Eric Liu0c0aea02016-12-15 13:02:41525 fixTypeLoc(Result, startLocationForType(Loc), endLocationForType(Loc), Loc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19526 } else if (const auto *VarRef =
527 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39528 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
529 assert(Var);
530 if (Var->getCanonicalDecl()->isStaticDataMember())
531 return;
Eric Liuda22b3c2016-11-29 14:15:14532 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu159f0132016-09-30 04:32:39533 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14534 fixDeclRefExpr(Result, Context->getDeclContext(),
535 llvm::cast<NamedDecl>(Var), VarRef);
Eric Liu0325a772017-02-02 17:40:38536 } else if (const auto *EnumConstRef =
537 Result.Nodes.getNodeAs<DeclRefExpr>("enum_const_ref")) {
538 // Do not rename the reference if it is already scoped by the EnumDecl name.
539 if (EnumConstRef->hasQualifier() &&
Eric Liu28c30ce2017-02-02 19:46:12540 EnumConstRef->getQualifier()->getKind() ==
541 NestedNameSpecifier::SpecifierKind::TypeSpec &&
Eric Liu0325a772017-02-02 17:40:38542 EnumConstRef->getQualifier()->getAsType()->isEnumeralType())
543 return;
544 const auto *EnumConstDecl =
545 Result.Nodes.getNodeAs<EnumConstantDecl>("enum_const_decl");
546 assert(EnumConstDecl);
547 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
548 assert(Context && "Empty decl context.");
549 // FIXME: this would qualify "ns::VALUE" as "ns::EnumValue::VALUE". Fix it
550 // if it turns out to be an issue.
551 fixDeclRefExpr(Result, Context->getDeclContext(),
552 llvm::cast<NamedDecl>(EnumConstDecl), EnumConstRef);
Eric Liuda22b3c2016-11-29 14:15:14553 } else if (const auto *FuncRef =
554 Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) {
Eric Liue3f35e42016-12-20 14:39:04555 // If this reference has been processed as a function call, we do not
556 // process it again.
557 if (ProcessedFuncRefs.count(FuncRef))
558 return;
559 ProcessedFuncRefs.insert(FuncRef);
Eric Liuda22b3c2016-11-29 14:15:14560 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
561 assert(Func);
562 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
563 assert(Context && "Empty decl context.");
564 fixDeclRefExpr(Result, Context->getDeclContext(),
565 llvm::cast<NamedDecl>(Func), FuncRef);
Eric Liu12068d82016-09-22 11:54:00566 } else {
Eric Liuda22b3c2016-11-29 14:15:14567 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19568 assert(Call != nullptr && "Expecting callback for CallExpr.");
Eric Liue3f35e42016-12-20 14:39:04569 const auto *CalleeFuncRef =
570 llvm::cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit());
571 ProcessedFuncRefs.insert(CalleeFuncRef);
Eric Liuda22b3c2016-11-29 14:15:14572 const FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00573 assert(Func != nullptr);
Eric Liue3f35e42016-12-20 14:39:04574 // FIXME: ignore overloaded operators. This would miss cases where operators
575 // are called by qualified names (i.e. "ns::operator <"). Ignore such
576 // cases for now.
577 if (Func->isOverloadedOperator())
578 return;
Eric Liu12068d82016-09-22 11:54:00579 // Ignore out-of-line static methods since they will be handled by nested
580 // name specifiers.
581 if (Func->getCanonicalDecl()->getStorageClass() ==
Eric Liuda22b3c2016-11-29 14:15:14582 StorageClass::SC_Static &&
Eric Liu12068d82016-09-22 11:54:00583 Func->isOutOfLine())
584 return;
Eric Liuda22b3c2016-11-29 14:15:14585 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu12068d82016-09-22 11:54:00586 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14587 SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17588 replaceQualifiedSymbolInDeclContext(
589 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34590 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32591 }
592}
593
Eric Liu73f49fd2016-10-12 12:34:18594static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
595 const SourceManager &SM,
596 const LangOptions &LangOpts) {
597 std::unique_ptr<Lexer> Lex =
598 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
599 assert(Lex.get() &&
600 "Failed to create lexer from the beginning of namespace.");
601 if (!Lex.get())
602 return SourceLocation();
603 Token Tok;
604 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
605 }
606 return Tok.isNot(tok::TokenKind::l_brace)
607 ? SourceLocation()
608 : Tok.getEndLoc().getLocWithOffset(1);
609}
610
Eric Liu495b2112016-09-19 17:40:32611// Stores information about a moved namespace in `MoveNamespaces` and leaves
612// the actual movement to `onEndOfTranslationUnit()`.
613void ChangeNamespaceTool::moveOldNamespace(
614 const ast_matchers::MatchFinder::MatchResult &Result,
615 const NamespaceDecl *NsDecl) {
616 // If the namespace is empty, do nothing.
617 if (Decl::castToDeclContext(NsDecl)->decls_empty())
618 return;
619
Eric Liuee5104b2017-01-04 14:49:08620 const SourceManager &SM = *Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32621 // Get the range of the code in the old namespace.
Eric Liuee5104b2017-01-04 14:49:08622 SourceLocation Start =
623 getLocAfterNamespaceLBrace(NsDecl, SM, Result.Context->getLangOpts());
Eric Liu73f49fd2016-10-12 12:34:18624 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32625 MoveNamespace MoveNs;
Eric Liuee5104b2017-01-04 14:49:08626 MoveNs.Offset = SM.getFileOffset(Start);
627 // The range of the moved namespace is from the location just past the left
628 // brace to the location right before the right brace.
629 MoveNs.Length = SM.getFileOffset(NsDecl->getRBraceLoc()) - MoveNs.Offset;
Eric Liu495b2112016-09-19 17:40:32630
631 // Insert the new namespace after `DiffOldNamespace`. For example, if
632 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
633 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
634 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
635 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01636 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
637 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32638 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01639 SourceLocation InsertionLoc = Start;
640 if (OuterNs) {
Eric Liuee5104b2017-01-04 14:49:08641 SourceLocation LocAfterNs = getStartOfNextLine(
642 OuterNs->getRBraceLoc(), SM, Result.Context->getLangOpts());
Eric Liu6aa94162016-11-10 18:29:01643 assert(LocAfterNs.isValid() &&
644 "Failed to get location after DiffOldNamespace");
645 InsertionLoc = LocAfterNs;
646 }
Eric Liuee5104b2017-01-04 14:49:08647 MoveNs.InsertionOffset = SM.getFileOffset(SM.getSpellingLoc(InsertionLoc));
648 MoveNs.FID = SM.getFileID(Start);
Eric Liucc83c662016-09-19 17:58:59649 MoveNs.SourceMgr = Result.SourceManager;
Eric Liuee5104b2017-01-04 14:49:08650 MoveNamespaces[SM.getFilename(Start)].push_back(MoveNs);
Eric Liu495b2112016-09-19 17:40:32651}
652
653// Removes a class forward declaration from the code in the moved namespace and
654// creates an `InsertForwardDeclaration` to insert the forward declaration back
655// into the old namespace after moving code from the old namespace to the new
656// namespace.
657// For example, changing "a" to "x":
658// Old code:
659// namespace a {
660// class FWD;
661// class A { FWD *fwd; }
662// } // a
663// New code:
664// namespace a {
665// class FWD;
666// } // a
667// namespace x {
668// class A { a::FWD *fwd; }
669// } // x
670void ChangeNamespaceTool::moveClassForwardDeclaration(
671 const ast_matchers::MatchFinder::MatchResult &Result,
Eric Liu41552d62016-12-07 14:20:52672 const NamedDecl *FwdDecl) {
Eric Liu495b2112016-09-19 17:40:32673 SourceLocation Start = FwdDecl->getLocStart();
674 SourceLocation End = FwdDecl->getLocEnd();
675 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
676 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
677 /*SkipTrailingWhitespaceAndNewLine=*/true);
678 if (AfterSemi.isValid())
679 End = AfterSemi.getLocWithOffset(-1);
680 // Delete the forward declaration from the code to be moved.
Eric Liu4fe99e12016-12-14 17:01:52681 addReplacementOrDie(Start, End, "", *Result.SourceManager,
682 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32683 llvm::StringRef Code = Lexer::getSourceText(
684 CharSourceRange::getTokenRange(
685 Result.SourceManager->getSpellingLoc(Start),
686 Result.SourceManager->getSpellingLoc(End)),
687 *Result.SourceManager, Result.Context->getLangOpts());
688 // Insert the forward declaration back into the old namespace after moving the
689 // code from old namespace to new namespace.
690 // Insertion information is stored in `InsertFwdDecls` and actual
691 // insertion will be performed in `onEndOfTranslationUnit`.
692 // Get the (old) namespace that contains the forward declaration.
693 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
694 // The namespace contains the forward declaration, so it must not be empty.
695 assert(!NsDecl->decls_empty());
696 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
697 Code, *Result.SourceManager);
698 InsertForwardDeclaration InsertFwd;
699 InsertFwd.InsertionOffset = Insertion.getOffset();
700 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
701 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
702}
703
Eric Liub9bf1b52016-11-08 22:44:17704// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
705// FromDecl with the shortest qualified name possible when the reference is in
706// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32707void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17708 const ast_matchers::MatchFinder::MatchResult &Result,
709 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
710 const NamedDecl *FromDecl) {
711 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu4fe99e12016-12-14 17:01:52712 if (llvm::isa<TranslationUnitDecl>(NsDeclContext)) {
713 // This should not happen in usual unless the TypeLoc is in function type
714 // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of
715 // `T` will be the translation unit. We simply use fully-qualified name
716 // here.
717 // Note that `FromDecl` must not be defined in the old namespace (according
718 // to `DeclMatcher`), so its fully-qualified name will not change after
719 // changing the namespace.
720 addReplacementOrDie(Start, End, FromDecl->getQualifiedNameAsString(),
721 *Result.SourceManager, &FileToReplacements);
722 return;
723 }
Eric Liu231c6552016-11-10 18:15:34724 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32725 // Calculate the name of the `NsDecl` after it is moved to new namespace.
726 std::string OldNs = NsDecl->getQualifiedNameAsString();
727 llvm::StringRef Postfix = OldNs;
728 bool Consumed = Postfix.consume_front(OldNamespace);
729 assert(Consumed && "Expect OldNS to start with OldNamespace.");
730 (void)Consumed;
731 const std::string NewNs = (NewNamespace + Postfix).str();
732
733 llvm::StringRef NestedName = Lexer::getSourceText(
734 CharSourceRange::getTokenRange(
735 Result.SourceManager->getSpellingLoc(Start),
736 Result.SourceManager->getSpellingLoc(End)),
737 *Result.SourceManager, Result.Context->getLangOpts());
Eric Liub9bf1b52016-11-08 22:44:17738 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu495b2112016-09-19 17:40:32739 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17740 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
741 // Checks if there is any using namespace declarations that can shorten the
742 // qualified name.
743 for (const auto *UsingNamespace : UsingNamespaceDecls) {
744 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
745 Start))
746 continue;
747 StringRef FromDeclNameRef = FromDeclName;
748 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
749 ->getQualifiedNameAsString())) {
750 FromDeclNameRef = FromDeclNameRef.drop_front(2);
751 if (FromDeclNameRef.size() < ReplaceName.size())
752 ReplaceName = FromDeclNameRef;
753 }
754 }
Eric Liu180dac62016-12-23 10:47:09755 // Checks if there is any namespace alias declarations that can shorten the
756 // qualified name.
757 for (const auto *NamespaceAlias : NamespaceAliasDecls) {
758 if (!isDeclVisibleAtLocation(*Result.SourceManager, NamespaceAlias, DeclCtx,
759 Start))
760 continue;
761 StringRef FromDeclNameRef = FromDeclName;
762 if (FromDeclNameRef.consume_front(
763 NamespaceAlias->getNamespace()->getQualifiedNameAsString() +
764 "::")) {
765 std::string AliasName = NamespaceAlias->getNameAsString();
766 std::string AliasQualifiedName =
767 NamespaceAlias->getQualifiedNameAsString();
768 // We only consider namespace aliases define in the global namepspace or
769 // in namespaces that are directly visible from the reference, i.e.
770 // ancestor of the `OldNs`. Note that declarations in ancestor namespaces
771 // but not visible in the new namespace is filtered out by
772 // "IsVisibleInNewNs" matcher.
773 if (AliasQualifiedName != AliasName) {
774 // The alias is defined in some namespace.
775 assert(StringRef(AliasQualifiedName).endswith("::" + AliasName));
776 llvm::StringRef AliasNs =
777 StringRef(AliasQualifiedName).drop_back(AliasName.size() + 2);
778 if (!llvm::StringRef(OldNs).startswith(AliasNs))
779 continue;
780 }
781 std::string NameWithAliasNamespace =
782 (AliasName + "::" + FromDeclNameRef).str();
783 if (NameWithAliasNamespace.size() < ReplaceName.size())
784 ReplaceName = NameWithAliasNamespace;
785 }
786 }
Eric Liub9bf1b52016-11-08 22:44:17787 // Checks if there is any using shadow declarations that can shorten the
788 // qualified name.
789 bool Matched = false;
790 for (const UsingDecl *Using : UsingDecls) {
791 if (Matched)
792 break;
793 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
794 for (const auto *UsingShadow : Using->shadows()) {
795 const auto *TargetDecl = UsingShadow->getTargetDecl();
Eric Liuae7de712017-02-02 15:29:54796 if (TargetDecl->getQualifiedNameAsString() ==
797 FromDecl->getQualifiedNameAsString()) {
Eric Liub9bf1b52016-11-08 22:44:17798 ReplaceName = FromDecl->getNameAsString();
799 Matched = true;
800 break;
801 }
802 }
803 }
804 }
Eric Liu495b2112016-09-19 17:40:32805 // If the new nested name in the new namespace is the same as it was in the
806 // old namespace, we don't create replacement.
Eric Liu91229162017-01-26 16:31:32807 if (NestedName == ReplaceName ||
808 (NestedName.startswith("::") && NestedName.drop_front(2) == ReplaceName))
Eric Liu495b2112016-09-19 17:40:32809 return;
Eric Liu97f87ad2016-12-07 20:08:02810 // If the reference need to be fully-qualified, add a leading "::" unless
811 // NewNamespace is the global namespace.
812 if (ReplaceName == FromDeclName && !NewNamespace.empty())
813 ReplaceName = "::" + ReplaceName;
Eric Liu4fe99e12016-12-14 17:01:52814 addReplacementOrDie(Start, End, ReplaceName, *Result.SourceManager,
815 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32816}
817
818// Replace the [Start, End] of `Type` with the shortest qualified name when the
819// `Type` is in `NewNamespace`.
820void ChangeNamespaceTool::fixTypeLoc(
821 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
822 SourceLocation End, TypeLoc Type) {
823 // FIXME: do not rename template parameter.
824 if (Start.isInvalid() || End.isInvalid())
825 return;
Eric Liuff51f012016-11-16 16:54:53826 // Types of CXXCtorInitializers do not need to be fixed.
827 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
828 return;
Eric Liu495b2112016-09-19 17:40:32829 // The declaration which this TypeLoc refers to.
830 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
831 // `hasDeclaration` gives underlying declaration, but if the type is
832 // a typedef type, we need to use the typedef type instead.
Eric Liu26cf68a2016-12-15 10:42:35833 auto IsInMovedNs = [&](const NamedDecl *D) {
834 if (!llvm::StringRef(D->getQualifiedNameAsString())
835 .startswith(OldNamespace + "::"))
836 return false;
837 auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getLocStart());
838 if (ExpansionLoc.isInvalid())
839 return false;
840 llvm::StringRef Filename = Result.SourceManager->getFilename(ExpansionLoc);
841 return FilePatternRE.match(Filename);
842 };
843 // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if
844 // `Type` is an alias type, we make `FromDecl` the type alias declaration.
845 // Also, don't fix the \p Type if it refers to a type alias decl in the moved
846 // namespace since the alias decl will be moved along with the type reference.
Eric Liu32158862016-11-14 19:37:55847 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32848 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55849 if (IsInMovedNs(FromDecl))
850 return;
Eric Liu26cf68a2016-12-15 10:42:35851 } else if (auto *TemplateType =
852 Type.getType()->getAs<TemplateSpecializationType>()) {
853 if (TemplateType->isTypeAlias()) {
854 FromDecl = TemplateType->getTemplateName().getAsTemplateDecl();
855 if (IsInMovedNs(FromDecl))
856 return;
857 }
Eric Liu32158862016-11-14 19:37:55858 }
Piotr Padlewski08124b12016-12-14 15:29:23859 const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu495b2112016-09-19 17:40:32860 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17861 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
862 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32863}
864
Eric Liu68765a82016-09-21 15:06:12865void ChangeNamespaceTool::fixUsingShadowDecl(
866 const ast_matchers::MatchFinder::MatchResult &Result,
867 const UsingDecl *UsingDeclaration) {
868 SourceLocation Start = UsingDeclaration->getLocStart();
869 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19870 if (Start.isInvalid() || End.isInvalid())
871 return;
Eric Liu68765a82016-09-21 15:06:12872
873 assert(UsingDeclaration->shadow_size() > 0);
874 // FIXME: it might not be always accurate to use the first using-decl.
875 const NamedDecl *TargetDecl =
876 UsingDeclaration->shadow_begin()->getTargetDecl();
877 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
878 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
879 // sense. If this happens, we need to use name with the new namespace.
880 // Use fully qualified name in UsingDecl for now.
Eric Liu4fe99e12016-12-14 17:01:52881 addReplacementOrDie(Start, End, "using ::" + TargetDeclName,
882 *Result.SourceManager, &FileToReplacements);
Eric Liu68765a82016-09-21 15:06:12883}
884
Eric Liuda22b3c2016-11-29 14:15:14885void ChangeNamespaceTool::fixDeclRefExpr(
886 const ast_matchers::MatchFinder::MatchResult &Result,
887 const DeclContext *UseContext, const NamedDecl *From,
888 const DeclRefExpr *Ref) {
889 SourceRange RefRange = Ref->getSourceRange();
890 replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(),
891 RefRange.getEnd(), From);
892}
893
Eric Liu495b2112016-09-19 17:40:32894void ChangeNamespaceTool::onEndOfTranslationUnit() {
895 // Move namespace blocks and insert forward declaration to old namespace.
896 for (const auto &FileAndNsMoves : MoveNamespaces) {
897 auto &NsMoves = FileAndNsMoves.second;
898 if (NsMoves.empty())
899 continue;
900 const std::string &FilePath = FileAndNsMoves.first;
901 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59902 auto &SM = *NsMoves.begin()->SourceMgr;
903 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32904 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
905 if (!ChangedCode) {
906 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
907 continue;
908 }
909 // Replacements on the changed code for moving namespaces and inserting
910 // forward declarations to old namespaces.
911 tooling::Replacements NewReplacements;
912 // Cut the changed code from the old namespace and paste the code in the new
913 // namespace.
914 for (const auto &NsMove : NsMoves) {
915 // Calculate the range of the old namespace block in the changed
916 // code.
917 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
918 const unsigned NewLength =
919 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
920 NewOffset;
921 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
922 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
923 std::string MovedCodeWrappedInNewNs =
924 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
925 // Calculate the new offset at which the code will be inserted in the
926 // changed code.
927 unsigned NewInsertionOffset =
928 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
929 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
930 MovedCodeWrappedInNewNs);
931 addOrMergeReplacement(Deletion, &NewReplacements);
932 addOrMergeReplacement(Insertion, &NewReplacements);
933 }
934 // After moving namespaces, insert forward declarations back to old
935 // namespaces.
936 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
937 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
938 unsigned NewInsertionOffset =
939 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
940 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
941 FwdDeclInsertion.ForwardDeclText);
942 addOrMergeReplacement(Insertion, &NewReplacements);
943 }
944 // Add replacements referring to the changed code to existing replacements,
945 // which refers to the original code.
946 Replaces = Replaces.merge(NewReplacements);
Antonio Maiorano0d7d9c22017-01-17 00:13:32947 auto Style = format::getStyle("file", FilePath, FallbackStyle);
948 if (!Style) {
949 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
950 continue;
951 }
Eric Liu495b2112016-09-19 17:40:32952 // Clean up old namespaces if there is nothing in it after moving.
953 auto CleanReplacements =
Antonio Maiorano0d7d9c22017-01-17 00:13:32954 format::cleanupAroundReplacements(Code, Replaces, *Style);
Eric Liu495b2112016-09-19 17:40:32955 if (!CleanReplacements) {
956 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
957 continue;
958 }
959 FileToReplacements[FilePath] = *CleanReplacements;
960 }
Eric Liuc265b022016-12-01 17:25:55961
962 // Make sure we don't generate replacements for files that do not match
963 // FilePattern.
964 for (auto &Entry : FileToReplacements)
965 if (!FilePatternRE.match(Entry.first))
966 Entry.second.clear();
Eric Liu495b2112016-09-19 17:40:32967}
968
969} // namespace change_namespace
970} // namespace clang