blob: 35ea707e1e44e58f9c73943ce3d8eaf52ec4da5c [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 Liu447164d2016-10-05 15:52:39199// \param DeclName A fully qualified name, "::a::b::X" or "a::b::X".
200// \param NsName A fully qualified name, "::a::b" or "a::b". Global namespace
201// will have empty name.
Eric Liu495b2112016-09-19 17:40:32202std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
203 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39204 DeclName = DeclName.ltrim(':');
205 NsName = NsName.ltrim(':');
Eric Liu447164d2016-10-05 15:52:39206 if (DeclName.find(':') == llvm::StringRef::npos)
Eric Liub9bf1b52016-11-08 22:44:17207 return DeclName;
Eric Liu447164d2016-10-05 15:52:39208
209 while (!DeclName.consume_front((NsName + "::").str())) {
Eric Liu495b2112016-09-19 17:40:32210 const auto Pos = NsName.find_last_of(':');
211 if (Pos == llvm::StringRef::npos)
212 return DeclName;
Eric Liu447164d2016-10-05 15:52:39213 assert(Pos > 0);
214 NsName = NsName.substr(0, Pos - 1);
Eric Liu495b2112016-09-19 17:40:32215 }
216 return DeclName;
217}
218
219std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) {
220 if (Code.back() != '\n')
221 Code += "\n";
222 llvm::SmallVector<StringRef, 4> NsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04223 NestedNs.split(NsSplitted, "::", /*MaxSplit=*/-1,
224 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32225 while (!NsSplitted.empty()) {
226 // FIXME: consider code style for comments.
227 Code = ("namespace " + NsSplitted.back() + " {\n" + Code +
228 "} // namespace " + NsSplitted.back() + "\n")
229 .str();
230 NsSplitted.pop_back();
231 }
232 return Code;
233}
234
Eric Liub9bf1b52016-11-08 22:44:17235// Returns true if \p D is a nested DeclContext in \p Context
236bool isNestedDeclContext(const DeclContext *D, const DeclContext *Context) {
237 while (D) {
238 if (D == Context)
239 return true;
240 D = D->getParent();
241 }
242 return false;
243}
244
245// Returns true if \p D is visible at \p Loc with DeclContext \p DeclCtx.
246bool isDeclVisibleAtLocation(const SourceManager &SM, const Decl *D,
247 const DeclContext *DeclCtx, SourceLocation Loc) {
248 SourceLocation DeclLoc = SM.getSpellingLoc(D->getLocation());
249 Loc = SM.getSpellingLoc(Loc);
250 return SM.isBeforeInTranslationUnit(DeclLoc, Loc) &&
251 (SM.getFileID(DeclLoc) == SM.getFileID(Loc) &&
252 isNestedDeclContext(DeclCtx, D->getDeclContext()));
253}
254
Eric Liu495b2112016-09-19 17:40:32255} // anonymous namespace
256
257ChangeNamespaceTool::ChangeNamespaceTool(
258 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
259 std::map<std::string, tooling::Replacements> *FileToReplacements,
260 llvm::StringRef FallbackStyle)
261 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
262 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
Eric Liuc265b022016-12-01 17:25:55263 FilePattern(FilePattern), FilePatternRE(FilePattern) {
Eric Liu495b2112016-09-19 17:40:32264 FileToReplacements->clear();
265 llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted;
266 llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted;
267 llvm::StringRef(OldNamespace).split(OldNsSplitted, "::");
268 llvm::StringRef(NewNamespace).split(NewNsSplitted, "::");
269 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
270 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
271 OldNsSplitted.front() == NewNsSplitted.front()) {
272 OldNsSplitted.erase(OldNsSplitted.begin());
273 NewNsSplitted.erase(NewNsSplitted.begin());
274 }
275 DiffOldNamespace = joinNamespaces(OldNsSplitted);
276 DiffNewNamespace = joinNamespaces(NewNsSplitted);
277}
278
Eric Liu495b2112016-09-19 17:40:32279void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32280 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17281 // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the
282 // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will
283 // be "a::b". Declarations in this namespace will not be visible in the new
284 // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-".
285 llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04286 llvm::StringRef(DiffOldNamespace)
287 .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1,
288 /*KeepEmpty=*/false);
Eric Liub9bf1b52016-11-08 22:44:17289 std::string Prefix = "-";
290 if (!DiffOldNsSplitted.empty())
291 Prefix = (StringRef(FullOldNs).drop_back(DiffOldNamespace.size()) +
292 DiffOldNsSplitted.front())
293 .str();
294 auto IsInMovedNs =
295 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
296 isExpansionInFileMatching(FilePattern));
297 auto IsVisibleInNewNs = anyOf(
298 IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Prefix)))));
299 // Match using declarations.
300 Finder->addMatcher(
301 usingDecl(isExpansionInFileMatching(FilePattern), IsVisibleInNewNs)
302 .bind("using"),
303 this);
304 // Match using namespace declarations.
305 Finder->addMatcher(usingDirectiveDecl(isExpansionInFileMatching(FilePattern),
306 IsVisibleInNewNs)
307 .bind("using_namespace"),
308 this);
Eric Liu180dac62016-12-23 10:47:09309 // Match namespace alias declarations.
310 Finder->addMatcher(namespaceAliasDecl(isExpansionInFileMatching(FilePattern),
311 IsVisibleInNewNs)
312 .bind("namespace_alias"),
313 this);
Eric Liub9bf1b52016-11-08 22:44:17314
315 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32316 Finder->addMatcher(
317 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
318 .bind("old_ns"),
319 this);
320
Eric Liu41552d62016-12-07 14:20:52321 // Match class forward-declarations in the old namespace.
322 // Note that forward-declarations in classes are not matched.
323 Finder->addMatcher(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())),
324 IsInMovedNs, hasParent(namespaceDecl()))
325 .bind("class_fwd_decl"),
326 this);
327
328 // Match template class forward-declarations in the old namespace.
Eric Liu495b2112016-09-19 17:40:32329 Finder->addMatcher(
Eric Liu41552d62016-12-07 14:20:52330 classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))),
331 IsInMovedNs, hasParent(namespaceDecl()))
332 .bind("template_class_fwd_decl"),
Eric Liu495b2112016-09-19 17:40:32333 this);
334
335 // Match references to types that are not defined in the old namespace.
336 // Forward-declarations in the old namespace are also matched since they will
337 // be moved back to the old namespace.
338 auto DeclMatcher = namedDecl(
339 hasAncestor(namespaceDecl()),
340 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48341 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32342 hasAncestor(cxxRecordDecl()),
343 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48344
Eric Liu8685c762016-12-07 17:04:07345 // Using shadow declarations in classes always refers to base class, which
346 // does not need to be qualified since it can be inferred from inheritance.
347 // Note that this does not match using alias declarations.
348 auto UsingShadowDeclInClass =
349 usingDecl(hasAnyUsingShadowDecl(decl()), hasParent(cxxRecordDecl()));
350
Eric Liu495b2112016-09-19 17:40:32351 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29352 // TypeLoc and template specialization arguments (which are not outermost)
353 // that are directly linked to types matching `DeclMatcher`. Nested name
354 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32355 Finder->addMatcher(
356 typeLoc(IsInMovedNs,
357 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29358 unless(anyOf(hasParent(typeLoc(loc(qualType(
359 allOf(hasDeclaration(DeclMatcher),
360 unless(templateSpecializationType())))))),
Eric Liu8685c762016-12-07 17:04:07361 hasParent(nestedNameSpecifierLoc()),
362 hasAncestor(isImplicit()),
363 hasAncestor(UsingShadowDeclInClass))),
Eric Liu495b2112016-09-19 17:40:32364 hasAncestor(decl().bind("dc")))
365 .bind("type"),
366 this);
Eric Liu912d0392016-09-27 12:54:48367
Eric Liu68765a82016-09-21 15:06:12368 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
369 // special case it.
Eric Liu8685c762016-12-07 17:04:07370 // Since using declarations inside classes must have the base class in the
371 // nested name specifier, we leave it to the nested name specifier matcher.
372 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()),
373 unless(UsingShadowDeclInClass))
Eric Liub9bf1b52016-11-08 22:44:17374 .bind("using_with_shadow"),
375 this);
Eric Liu912d0392016-09-27 12:54:48376
Eric Liuff51f012016-11-16 16:54:53377 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
378 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
379 // "A::A" would have already been fixed.
Eric Liu8685c762016-12-07 17:04:07380 Finder->addMatcher(
381 nestedNameSpecifierLoc(
382 hasAncestor(decl(IsInMovedNs).bind("dc")),
383 loc(nestedNameSpecifier(
384 specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
385 unless(anyOf(hasAncestor(isImplicit()),
386 hasAncestor(UsingShadowDeclInClass),
387 hasAncestor(typeLoc(loc(qualType(hasDeclaration(
388 decl(equalsBoundNode("from_decl"))))))))))
389 .bind("nested_specifier_loc"),
390 this);
Eric Liu12068d82016-09-22 11:54:00391
Eric Liuff51f012016-11-16 16:54:53392 // Matches base class initializers in constructors. TypeLocs of base class
393 // initializers do not need to be fixed. For example,
394 // class X : public a::b::Y {
395 // public:
396 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
397 // };
398 Finder->addMatcher(
399 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
400
Eric Liu12068d82016-09-22 11:54:00401 // Handle function.
Eric Liu912d0392016-09-27 12:54:48402 // Only handle functions that are defined in a namespace excluding member
403 // function, static methods (qualified by nested specifier), and functions
404 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00405 // Note that the matcher does not exclude calls to out-of-line static method
406 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48407 auto FuncMatcher =
408 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
409 hasAncestor(namespaceDecl(isAnonymous())),
410 hasAncestor(cxxRecordDecl()))),
411 hasParent(namespaceDecl()));
Eric Liuda22b3c2016-11-29 14:15:14412 Finder->addMatcher(decl(forEachDescendant(expr(anyOf(
413 callExpr(callee(FuncMatcher)).bind("call"),
414 declRefExpr(to(FuncMatcher.bind("func_decl")))
415 .bind("func_ref")))),
416 IsInMovedNs, unless(isImplicit()))
417 .bind("dc"),
418 this);
Eric Liu159f0132016-09-30 04:32:39419
420 auto GlobalVarMatcher = varDecl(
421 hasGlobalStorage(), hasParent(namespaceDecl()),
422 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
423 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
424 to(GlobalVarMatcher.bind("var_decl")))
425 .bind("var_ref"),
426 this);
Eric Liu495b2112016-09-19 17:40:32427}
428
429void ChangeNamespaceTool::run(
430 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17431 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
432 UsingDecls.insert(Using);
433 } else if (const auto *UsingNamespace =
434 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
435 "using_namespace")) {
436 UsingNamespaceDecls.insert(UsingNamespace);
Eric Liu180dac62016-12-23 10:47:09437 } else if (const auto *NamespaceAlias =
438 Result.Nodes.getNodeAs<NamespaceAliasDecl>(
439 "namespace_alias")) {
440 NamespaceAliasDecls.insert(NamespaceAlias);
Eric Liub9bf1b52016-11-08 22:44:17441 } else if (const auto *NsDecl =
442 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32443 moveOldNamespace(Result, NsDecl);
444 } else if (const auto *FwdDecl =
Eric Liu41552d62016-12-07 14:20:52445 Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) {
446 moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl));
447 } else if (const auto *TemplateFwdDecl =
448 Result.Nodes.getNodeAs<ClassTemplateDecl>(
449 "template_class_fwd_decl")) {
450 moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl));
Eric Liub9bf1b52016-11-08 22:44:17451 } else if (const auto *UsingWithShadow =
452 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
453 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12454 } else if (const auto *Specifier =
455 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
456 "nested_specifier_loc")) {
457 SourceLocation Start = Specifier->getBeginLoc();
Eric Liuc265b022016-12-01 17:25:55458 SourceLocation End = endLocationForType(Specifier->getTypeLoc());
Eric Liu68765a82016-09-21 15:06:12459 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53460 } else if (const auto *BaseInitializer =
461 Result.Nodes.getNodeAs<CXXCtorInitializer>(
462 "base_initializer")) {
463 BaseCtorInitializerTypeLocs.push_back(
464 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00465 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu26cf68a2016-12-15 10:42:35466 // This avoids fixing types with record types as qualifier, which is not
467 // filtered by matchers in some cases, e.g. the type is templated. We should
468 // handle the record type qualifier instead.
Eric Liu0c0aea02016-12-15 13:02:41469 TypeLoc Loc = *TLoc;
470 while (Loc.getTypeLocClass() == TypeLoc::Qualified)
471 Loc = Loc.getNextTypeLoc();
472 if (Loc.getTypeLocClass() == TypeLoc::Elaborated) {
Eric Liu26cf68a2016-12-15 10:42:35473 NestedNameSpecifierLoc NestedNameSpecifier =
Eric Liu0c0aea02016-12-15 13:02:41474 Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
Eric Liu26cf68a2016-12-15 10:42:35475 const Type *SpecifierType =
476 NestedNameSpecifier.getNestedNameSpecifier()->getAsType();
477 if (SpecifierType && SpecifierType->isRecordType())
478 return;
479 }
Eric Liu0c0aea02016-12-15 13:02:41480 fixTypeLoc(Result, startLocationForType(Loc), endLocationForType(Loc), Loc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19481 } else if (const auto *VarRef =
482 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39483 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
484 assert(Var);
485 if (Var->getCanonicalDecl()->isStaticDataMember())
486 return;
Eric Liuda22b3c2016-11-29 14:15:14487 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu159f0132016-09-30 04:32:39488 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14489 fixDeclRefExpr(Result, Context->getDeclContext(),
490 llvm::cast<NamedDecl>(Var), VarRef);
491 } else if (const auto *FuncRef =
492 Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) {
Eric Liue3f35e42016-12-20 14:39:04493 // If this reference has been processed as a function call, we do not
494 // process it again.
495 if (ProcessedFuncRefs.count(FuncRef))
496 return;
497 ProcessedFuncRefs.insert(FuncRef);
Eric Liuda22b3c2016-11-29 14:15:14498 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
499 assert(Func);
500 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
501 assert(Context && "Empty decl context.");
502 fixDeclRefExpr(Result, Context->getDeclContext(),
503 llvm::cast<NamedDecl>(Func), FuncRef);
Eric Liu12068d82016-09-22 11:54:00504 } else {
Eric Liuda22b3c2016-11-29 14:15:14505 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19506 assert(Call != nullptr && "Expecting callback for CallExpr.");
Eric Liue3f35e42016-12-20 14:39:04507 const auto *CalleeFuncRef =
508 llvm::cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit());
509 ProcessedFuncRefs.insert(CalleeFuncRef);
Eric Liuda22b3c2016-11-29 14:15:14510 const FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00511 assert(Func != nullptr);
Eric Liue3f35e42016-12-20 14:39:04512 // FIXME: ignore overloaded operators. This would miss cases where operators
513 // are called by qualified names (i.e. "ns::operator <"). Ignore such
514 // cases for now.
515 if (Func->isOverloadedOperator())
516 return;
Eric Liu12068d82016-09-22 11:54:00517 // Ignore out-of-line static methods since they will be handled by nested
518 // name specifiers.
519 if (Func->getCanonicalDecl()->getStorageClass() ==
Eric Liuda22b3c2016-11-29 14:15:14520 StorageClass::SC_Static &&
Eric Liu12068d82016-09-22 11:54:00521 Func->isOutOfLine())
522 return;
Eric Liuda22b3c2016-11-29 14:15:14523 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu12068d82016-09-22 11:54:00524 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14525 SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17526 replaceQualifiedSymbolInDeclContext(
527 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34528 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32529 }
530}
531
Eric Liu73f49fd2016-10-12 12:34:18532static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
533 const SourceManager &SM,
534 const LangOptions &LangOpts) {
535 std::unique_ptr<Lexer> Lex =
536 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
537 assert(Lex.get() &&
538 "Failed to create lexer from the beginning of namespace.");
539 if (!Lex.get())
540 return SourceLocation();
541 Token Tok;
542 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
543 }
544 return Tok.isNot(tok::TokenKind::l_brace)
545 ? SourceLocation()
546 : Tok.getEndLoc().getLocWithOffset(1);
547}
548
Eric Liu495b2112016-09-19 17:40:32549// Stores information about a moved namespace in `MoveNamespaces` and leaves
550// the actual movement to `onEndOfTranslationUnit()`.
551void ChangeNamespaceTool::moveOldNamespace(
552 const ast_matchers::MatchFinder::MatchResult &Result,
553 const NamespaceDecl *NsDecl) {
554 // If the namespace is empty, do nothing.
555 if (Decl::castToDeclContext(NsDecl)->decls_empty())
556 return;
557
Eric Liuee5104b2017-01-04 14:49:08558 const SourceManager &SM = *Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32559 // Get the range of the code in the old namespace.
Eric Liuee5104b2017-01-04 14:49:08560 SourceLocation Start =
561 getLocAfterNamespaceLBrace(NsDecl, SM, Result.Context->getLangOpts());
Eric Liu73f49fd2016-10-12 12:34:18562 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32563 MoveNamespace MoveNs;
Eric Liuee5104b2017-01-04 14:49:08564 MoveNs.Offset = SM.getFileOffset(Start);
565 // The range of the moved namespace is from the location just past the left
566 // brace to the location right before the right brace.
567 MoveNs.Length = SM.getFileOffset(NsDecl->getRBraceLoc()) - MoveNs.Offset;
Eric Liu495b2112016-09-19 17:40:32568
569 // Insert the new namespace after `DiffOldNamespace`. For example, if
570 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
571 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
572 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
573 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01574 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
575 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32576 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01577 SourceLocation InsertionLoc = Start;
578 if (OuterNs) {
Eric Liuee5104b2017-01-04 14:49:08579 SourceLocation LocAfterNs = getStartOfNextLine(
580 OuterNs->getRBraceLoc(), SM, Result.Context->getLangOpts());
Eric Liu6aa94162016-11-10 18:29:01581 assert(LocAfterNs.isValid() &&
582 "Failed to get location after DiffOldNamespace");
583 InsertionLoc = LocAfterNs;
584 }
Eric Liuee5104b2017-01-04 14:49:08585 MoveNs.InsertionOffset = SM.getFileOffset(SM.getSpellingLoc(InsertionLoc));
586 MoveNs.FID = SM.getFileID(Start);
Eric Liucc83c662016-09-19 17:58:59587 MoveNs.SourceMgr = Result.SourceManager;
Eric Liuee5104b2017-01-04 14:49:08588 MoveNamespaces[SM.getFilename(Start)].push_back(MoveNs);
Eric Liu495b2112016-09-19 17:40:32589}
590
591// Removes a class forward declaration from the code in the moved namespace and
592// creates an `InsertForwardDeclaration` to insert the forward declaration back
593// into the old namespace after moving code from the old namespace to the new
594// namespace.
595// For example, changing "a" to "x":
596// Old code:
597// namespace a {
598// class FWD;
599// class A { FWD *fwd; }
600// } // a
601// New code:
602// namespace a {
603// class FWD;
604// } // a
605// namespace x {
606// class A { a::FWD *fwd; }
607// } // x
608void ChangeNamespaceTool::moveClassForwardDeclaration(
609 const ast_matchers::MatchFinder::MatchResult &Result,
Eric Liu41552d62016-12-07 14:20:52610 const NamedDecl *FwdDecl) {
Eric Liu495b2112016-09-19 17:40:32611 SourceLocation Start = FwdDecl->getLocStart();
612 SourceLocation End = FwdDecl->getLocEnd();
613 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
614 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
615 /*SkipTrailingWhitespaceAndNewLine=*/true);
616 if (AfterSemi.isValid())
617 End = AfterSemi.getLocWithOffset(-1);
618 // Delete the forward declaration from the code to be moved.
Eric Liu4fe99e12016-12-14 17:01:52619 addReplacementOrDie(Start, End, "", *Result.SourceManager,
620 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32621 llvm::StringRef Code = Lexer::getSourceText(
622 CharSourceRange::getTokenRange(
623 Result.SourceManager->getSpellingLoc(Start),
624 Result.SourceManager->getSpellingLoc(End)),
625 *Result.SourceManager, Result.Context->getLangOpts());
626 // Insert the forward declaration back into the old namespace after moving the
627 // code from old namespace to new namespace.
628 // Insertion information is stored in `InsertFwdDecls` and actual
629 // insertion will be performed in `onEndOfTranslationUnit`.
630 // Get the (old) namespace that contains the forward declaration.
631 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
632 // The namespace contains the forward declaration, so it must not be empty.
633 assert(!NsDecl->decls_empty());
634 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
635 Code, *Result.SourceManager);
636 InsertForwardDeclaration InsertFwd;
637 InsertFwd.InsertionOffset = Insertion.getOffset();
638 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
639 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
640}
641
Eric Liub9bf1b52016-11-08 22:44:17642// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
643// FromDecl with the shortest qualified name possible when the reference is in
644// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32645void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17646 const ast_matchers::MatchFinder::MatchResult &Result,
647 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
648 const NamedDecl *FromDecl) {
649 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu4fe99e12016-12-14 17:01:52650 if (llvm::isa<TranslationUnitDecl>(NsDeclContext)) {
651 // This should not happen in usual unless the TypeLoc is in function type
652 // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of
653 // `T` will be the translation unit. We simply use fully-qualified name
654 // here.
655 // Note that `FromDecl` must not be defined in the old namespace (according
656 // to `DeclMatcher`), so its fully-qualified name will not change after
657 // changing the namespace.
658 addReplacementOrDie(Start, End, FromDecl->getQualifiedNameAsString(),
659 *Result.SourceManager, &FileToReplacements);
660 return;
661 }
Eric Liu231c6552016-11-10 18:15:34662 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32663 // Calculate the name of the `NsDecl` after it is moved to new namespace.
664 std::string OldNs = NsDecl->getQualifiedNameAsString();
665 llvm::StringRef Postfix = OldNs;
666 bool Consumed = Postfix.consume_front(OldNamespace);
667 assert(Consumed && "Expect OldNS to start with OldNamespace.");
668 (void)Consumed;
669 const std::string NewNs = (NewNamespace + Postfix).str();
670
671 llvm::StringRef NestedName = Lexer::getSourceText(
672 CharSourceRange::getTokenRange(
673 Result.SourceManager->getSpellingLoc(Start),
674 Result.SourceManager->getSpellingLoc(End)),
675 *Result.SourceManager, Result.Context->getLangOpts());
676 // If the symbol is already fully qualified, no change needs to be make.
677 if (NestedName.startswith("::"))
678 return;
Eric Liub9bf1b52016-11-08 22:44:17679 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu495b2112016-09-19 17:40:32680 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17681 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
682 // Checks if there is any using namespace declarations that can shorten the
683 // qualified name.
684 for (const auto *UsingNamespace : UsingNamespaceDecls) {
685 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
686 Start))
687 continue;
688 StringRef FromDeclNameRef = FromDeclName;
689 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
690 ->getQualifiedNameAsString())) {
691 FromDeclNameRef = FromDeclNameRef.drop_front(2);
692 if (FromDeclNameRef.size() < ReplaceName.size())
693 ReplaceName = FromDeclNameRef;
694 }
695 }
Eric Liu180dac62016-12-23 10:47:09696 // Checks if there is any namespace alias declarations that can shorten the
697 // qualified name.
698 for (const auto *NamespaceAlias : NamespaceAliasDecls) {
699 if (!isDeclVisibleAtLocation(*Result.SourceManager, NamespaceAlias, DeclCtx,
700 Start))
701 continue;
702 StringRef FromDeclNameRef = FromDeclName;
703 if (FromDeclNameRef.consume_front(
704 NamespaceAlias->getNamespace()->getQualifiedNameAsString() +
705 "::")) {
706 std::string AliasName = NamespaceAlias->getNameAsString();
707 std::string AliasQualifiedName =
708 NamespaceAlias->getQualifiedNameAsString();
709 // We only consider namespace aliases define in the global namepspace or
710 // in namespaces that are directly visible from the reference, i.e.
711 // ancestor of the `OldNs`. Note that declarations in ancestor namespaces
712 // but not visible in the new namespace is filtered out by
713 // "IsVisibleInNewNs" matcher.
714 if (AliasQualifiedName != AliasName) {
715 // The alias is defined in some namespace.
716 assert(StringRef(AliasQualifiedName).endswith("::" + AliasName));
717 llvm::StringRef AliasNs =
718 StringRef(AliasQualifiedName).drop_back(AliasName.size() + 2);
719 if (!llvm::StringRef(OldNs).startswith(AliasNs))
720 continue;
721 }
722 std::string NameWithAliasNamespace =
723 (AliasName + "::" + FromDeclNameRef).str();
724 if (NameWithAliasNamespace.size() < ReplaceName.size())
725 ReplaceName = NameWithAliasNamespace;
726 }
727 }
Eric Liub9bf1b52016-11-08 22:44:17728 // Checks if there is any using shadow declarations that can shorten the
729 // qualified name.
730 bool Matched = false;
731 for (const UsingDecl *Using : UsingDecls) {
732 if (Matched)
733 break;
734 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
735 for (const auto *UsingShadow : Using->shadows()) {
736 const auto *TargetDecl = UsingShadow->getTargetDecl();
737 if (TargetDecl == FromDecl) {
738 ReplaceName = FromDecl->getNameAsString();
739 Matched = true;
740 break;
741 }
742 }
743 }
744 }
Eric Liu495b2112016-09-19 17:40:32745 // If the new nested name in the new namespace is the same as it was in the
746 // old namespace, we don't create replacement.
747 if (NestedName == ReplaceName)
748 return;
Eric Liu97f87ad2016-12-07 20:08:02749 // If the reference need to be fully-qualified, add a leading "::" unless
750 // NewNamespace is the global namespace.
751 if (ReplaceName == FromDeclName && !NewNamespace.empty())
752 ReplaceName = "::" + ReplaceName;
Eric Liu4fe99e12016-12-14 17:01:52753 addReplacementOrDie(Start, End, ReplaceName, *Result.SourceManager,
754 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32755}
756
757// Replace the [Start, End] of `Type` with the shortest qualified name when the
758// `Type` is in `NewNamespace`.
759void ChangeNamespaceTool::fixTypeLoc(
760 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
761 SourceLocation End, TypeLoc Type) {
762 // FIXME: do not rename template parameter.
763 if (Start.isInvalid() || End.isInvalid())
764 return;
Eric Liuff51f012016-11-16 16:54:53765 // Types of CXXCtorInitializers do not need to be fixed.
766 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
767 return;
Eric Liu495b2112016-09-19 17:40:32768 // The declaration which this TypeLoc refers to.
769 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
770 // `hasDeclaration` gives underlying declaration, but if the type is
771 // a typedef type, we need to use the typedef type instead.
Eric Liu26cf68a2016-12-15 10:42:35772 auto IsInMovedNs = [&](const NamedDecl *D) {
773 if (!llvm::StringRef(D->getQualifiedNameAsString())
774 .startswith(OldNamespace + "::"))
775 return false;
776 auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getLocStart());
777 if (ExpansionLoc.isInvalid())
778 return false;
779 llvm::StringRef Filename = Result.SourceManager->getFilename(ExpansionLoc);
780 return FilePatternRE.match(Filename);
781 };
782 // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if
783 // `Type` is an alias type, we make `FromDecl` the type alias declaration.
784 // Also, don't fix the \p Type if it refers to a type alias decl in the moved
785 // namespace since the alias decl will be moved along with the type reference.
Eric Liu32158862016-11-14 19:37:55786 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32787 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55788 if (IsInMovedNs(FromDecl))
789 return;
Eric Liu26cf68a2016-12-15 10:42:35790 } else if (auto *TemplateType =
791 Type.getType()->getAs<TemplateSpecializationType>()) {
792 if (TemplateType->isTypeAlias()) {
793 FromDecl = TemplateType->getTemplateName().getAsTemplateDecl();
794 if (IsInMovedNs(FromDecl))
795 return;
796 }
Eric Liu32158862016-11-14 19:37:55797 }
Piotr Padlewski08124b12016-12-14 15:29:23798 const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu495b2112016-09-19 17:40:32799 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17800 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
801 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32802}
803
Eric Liu68765a82016-09-21 15:06:12804void ChangeNamespaceTool::fixUsingShadowDecl(
805 const ast_matchers::MatchFinder::MatchResult &Result,
806 const UsingDecl *UsingDeclaration) {
807 SourceLocation Start = UsingDeclaration->getLocStart();
808 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19809 if (Start.isInvalid() || End.isInvalid())
810 return;
Eric Liu68765a82016-09-21 15:06:12811
812 assert(UsingDeclaration->shadow_size() > 0);
813 // FIXME: it might not be always accurate to use the first using-decl.
814 const NamedDecl *TargetDecl =
815 UsingDeclaration->shadow_begin()->getTargetDecl();
816 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
817 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
818 // sense. If this happens, we need to use name with the new namespace.
819 // Use fully qualified name in UsingDecl for now.
Eric Liu4fe99e12016-12-14 17:01:52820 addReplacementOrDie(Start, End, "using ::" + TargetDeclName,
821 *Result.SourceManager, &FileToReplacements);
Eric Liu68765a82016-09-21 15:06:12822}
823
Eric Liuda22b3c2016-11-29 14:15:14824void ChangeNamespaceTool::fixDeclRefExpr(
825 const ast_matchers::MatchFinder::MatchResult &Result,
826 const DeclContext *UseContext, const NamedDecl *From,
827 const DeclRefExpr *Ref) {
828 SourceRange RefRange = Ref->getSourceRange();
829 replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(),
830 RefRange.getEnd(), From);
831}
832
Eric Liu495b2112016-09-19 17:40:32833void ChangeNamespaceTool::onEndOfTranslationUnit() {
834 // Move namespace blocks and insert forward declaration to old namespace.
835 for (const auto &FileAndNsMoves : MoveNamespaces) {
836 auto &NsMoves = FileAndNsMoves.second;
837 if (NsMoves.empty())
838 continue;
839 const std::string &FilePath = FileAndNsMoves.first;
840 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59841 auto &SM = *NsMoves.begin()->SourceMgr;
842 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32843 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
844 if (!ChangedCode) {
845 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
846 continue;
847 }
848 // Replacements on the changed code for moving namespaces and inserting
849 // forward declarations to old namespaces.
850 tooling::Replacements NewReplacements;
851 // Cut the changed code from the old namespace and paste the code in the new
852 // namespace.
853 for (const auto &NsMove : NsMoves) {
854 // Calculate the range of the old namespace block in the changed
855 // code.
856 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
857 const unsigned NewLength =
858 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
859 NewOffset;
860 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
861 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
862 std::string MovedCodeWrappedInNewNs =
863 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
864 // Calculate the new offset at which the code will be inserted in the
865 // changed code.
866 unsigned NewInsertionOffset =
867 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
868 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
869 MovedCodeWrappedInNewNs);
870 addOrMergeReplacement(Deletion, &NewReplacements);
871 addOrMergeReplacement(Insertion, &NewReplacements);
872 }
873 // After moving namespaces, insert forward declarations back to old
874 // namespaces.
875 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
876 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
877 unsigned NewInsertionOffset =
878 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
879 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
880 FwdDeclInsertion.ForwardDeclText);
881 addOrMergeReplacement(Insertion, &NewReplacements);
882 }
883 // Add replacements referring to the changed code to existing replacements,
884 // which refers to the original code.
885 Replaces = Replaces.merge(NewReplacements);
Antonio Maiorano0d7d9c22017-01-17 00:13:32886 auto Style = format::getStyle("file", FilePath, FallbackStyle);
887 if (!Style) {
888 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
889 continue;
890 }
Eric Liu495b2112016-09-19 17:40:32891 // Clean up old namespaces if there is nothing in it after moving.
892 auto CleanReplacements =
Antonio Maiorano0d7d9c22017-01-17 00:13:32893 format::cleanupAroundReplacements(Code, Replaces, *Style);
Eric Liu495b2112016-09-19 17:40:32894 if (!CleanReplacements) {
895 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
896 continue;
897 }
898 FileToReplacements[FilePath] = *CleanReplacements;
899 }
Eric Liuc265b022016-12-01 17:25:55900
901 // Make sure we don't generate replacements for files that do not match
902 // FilePattern.
903 for (auto &Entry : FileToReplacements)
904 if (!FilePatternRE.match(Entry.first))
905 Entry.second.clear();
Eric Liu495b2112016-09-19 17:40:32906}
907
908} // namespace change_namespace
909} // namespace clang