blob: b620b42e21fd2ea8e9547f295290c1ddac58a2cc [file] [log] [blame]
Eric Liu495b2112016-09-19 17:40:32 +00001//===-- ChangeNamespace.cpp - Change namespace implementation -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "ChangeNamespace.h"
10#include "clang/Format/Format.h"
11#include "clang/Lex/Lexer.h"
Eric Liuff51f012016-11-16 16:54:53 +000012#include "llvm/Support/ErrorHandling.h"
Eric Liu495b2112016-09-19 17:40:32 +000013
14using namespace clang::ast_matchers;
15
16namespace clang {
17namespace change_namespace {
18
19namespace {
20
21inline std::string
22joinNamespaces(const llvm::SmallVectorImpl<StringRef> &Namespaces) {
23 if (Namespaces.empty())
24 return "";
25 std::string Result = Namespaces.front();
26 for (auto I = Namespaces.begin() + 1, E = Namespaces.end(); I != E; ++I)
27 Result += ("::" + *I).str();
28 return Result;
29}
30
31SourceLocation startLocationForType(TypeLoc TLoc) {
32 // For elaborated types (e.g. `struct a::A`) we want the portion after the
33 // `struct` but including the namespace qualifier, `a::`.
34 if (TLoc.getTypeLocClass() == TypeLoc::Elaborated) {
35 NestedNameSpecifierLoc NestedNameSpecifier =
36 TLoc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
37 if (NestedNameSpecifier.getNestedNameSpecifier())
38 return NestedNameSpecifier.getBeginLoc();
39 TLoc = TLoc.getNextTypeLoc();
40 }
41 return TLoc.getLocStart();
42}
43
Eric Liuc265b022016-12-01 17:25:55 +000044SourceLocation endLocationForType(TypeLoc TLoc) {
Eric Liu495b2112016-09-19 17:40:32 +000045 // Dig past any namespace or keyword qualifications.
46 while (TLoc.getTypeLocClass() == TypeLoc::Elaborated ||
47 TLoc.getTypeLocClass() == TypeLoc::Qualified)
48 TLoc = TLoc.getNextTypeLoc();
49
50 // The location for template specializations (e.g. Foo<int>) includes the
51 // templated types in its location range. We want to restrict this to just
52 // before the `<` character.
53 if (TLoc.getTypeLocClass() == TypeLoc::TemplateSpecialization)
54 return TLoc.castAs<TemplateSpecializationTypeLoc>()
55 .getLAngleLoc()
56 .getLocWithOffset(-1);
57 return TLoc.getEndLoc();
58}
59
60// Returns the containing namespace of `InnerNs` by skipping `PartialNsName`.
Eric Liu6aa94162016-11-10 18:29:01 +000061// If the `InnerNs` does not have `PartialNsName` as suffix, or `PartialNsName`
62// is empty, nullptr is returned.
Eric Liu495b2112016-09-19 17:40:32 +000063// For example, if `InnerNs` is "a::b::c" and `PartialNsName` is "b::c", then
64// the NamespaceDecl of namespace "a" will be returned.
65const NamespaceDecl *getOuterNamespace(const NamespaceDecl *InnerNs,
66 llvm::StringRef PartialNsName) {
Eric Liu6aa94162016-11-10 18:29:01 +000067 if (!InnerNs || PartialNsName.empty())
68 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +000069 const auto *CurrentContext = llvm::cast<DeclContext>(InnerNs);
70 const auto *CurrentNs = InnerNs;
71 llvm::SmallVector<llvm::StringRef, 4> PartialNsNameSplitted;
Eric Liu6aa94162016-11-10 18:29:01 +000072 PartialNsName.split(PartialNsNameSplitted, "::", /*MaxSplit=*/-1,
73 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32 +000074 while (!PartialNsNameSplitted.empty()) {
75 // Get the inner-most namespace in CurrentContext.
76 while (CurrentContext && !llvm::isa<NamespaceDecl>(CurrentContext))
77 CurrentContext = CurrentContext->getParent();
78 if (!CurrentContext)
79 return nullptr;
80 CurrentNs = llvm::cast<NamespaceDecl>(CurrentContext);
81 if (PartialNsNameSplitted.back() != CurrentNs->getNameAsString())
82 return nullptr;
83 PartialNsNameSplitted.pop_back();
84 CurrentContext = CurrentContext->getParent();
85 }
86 return CurrentNs;
87}
88
Eric Liu73f49fd2016-10-12 12:34:18 +000089static std::unique_ptr<Lexer>
90getLexerStartingFromLoc(SourceLocation Loc, const SourceManager &SM,
91 const LangOptions &LangOpts) {
Eric Liu495b2112016-09-19 17:40:32 +000092 if (Loc.isMacroID() &&
93 !Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eric Liu73f49fd2016-10-12 12:34:18 +000094 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +000095 // Break down the source location.
96 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
97 // Try to load the file buffer.
98 bool InvalidTemp = false;
99 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
100 if (InvalidTemp)
Eric Liu73f49fd2016-10-12 12:34:18 +0000101 return nullptr;
Eric Liu495b2112016-09-19 17:40:32 +0000102
103 const char *TokBegin = File.data() + LocInfo.second;
104 // Lex from the start of the given location.
Eric Liu73f49fd2016-10-12 12:34:18 +0000105 return llvm::make_unique<Lexer>(SM.getLocForStartOfFile(LocInfo.first),
106 LangOpts, File.begin(), TokBegin, File.end());
107}
Eric Liu495b2112016-09-19 17:40:32 +0000108
Eric Liu73f49fd2016-10-12 12:34:18 +0000109// FIXME: get rid of this helper function if this is supported in clang-refactor
110// library.
111static SourceLocation getStartOfNextLine(SourceLocation Loc,
112 const SourceManager &SM,
113 const LangOptions &LangOpts) {
114 std::unique_ptr<Lexer> Lex = getLexerStartingFromLoc(Loc, SM, LangOpts);
115 if (!Lex.get())
116 return SourceLocation();
Eric Liu495b2112016-09-19 17:40:32 +0000117 llvm::SmallVector<char, 16> Line;
118 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
Eric Liu73f49fd2016-10-12 12:34:18 +0000119 Lex->setParsingPreprocessorDirective(true);
120 Lex->ReadToEndOfLine(&Line);
Haojian Wuef8a6dc2016-10-04 10:35:53 +0000121 auto End = Loc.getLocWithOffset(Line.size());
Eric Liu73f49fd2016-10-12 12:34:18 +0000122 return SM.getLocForEndOfFile(SM.getDecomposedLoc(Loc).first) == End
123 ? End
124 : End.getLocWithOffset(1);
Eric Liu495b2112016-09-19 17:40:32 +0000125}
126
127// Returns `R` with new range that refers to code after `Replaces` being
128// applied.
129tooling::Replacement
130getReplacementInChangedCode(const tooling::Replacements &Replaces,
131 const tooling::Replacement &R) {
132 unsigned NewStart = Replaces.getShiftedCodePosition(R.getOffset());
133 unsigned NewEnd =
134 Replaces.getShiftedCodePosition(R.getOffset() + R.getLength());
135 return tooling::Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
136 R.getReplacementText());
137}
138
139// Adds a replacement `R` into `Replaces` or merges it into `Replaces` by
140// applying all existing Replaces first if there is conflict.
141void addOrMergeReplacement(const tooling::Replacement &R,
142 tooling::Replacements *Replaces) {
143 auto Err = Replaces->add(R);
144 if (Err) {
145 llvm::consumeError(std::move(Err));
146 auto Replace = getReplacementInChangedCode(*Replaces, R);
147 *Replaces = Replaces->merge(tooling::Replacements(Replace));
148 }
149}
150
151tooling::Replacement createReplacement(SourceLocation Start, SourceLocation End,
152 llvm::StringRef ReplacementText,
153 const SourceManager &SM) {
154 if (!Start.isValid() || !End.isValid()) {
155 llvm::errs() << "start or end location were invalid\n";
156 return tooling::Replacement();
157 }
158 if (SM.getDecomposedLoc(Start).first != SM.getDecomposedLoc(End).first) {
159 llvm::errs()
160 << "start or end location were in different macro expansions\n";
161 return tooling::Replacement();
162 }
163 Start = SM.getSpellingLoc(Start);
164 End = SM.getSpellingLoc(End);
165 if (SM.getFileID(Start) != SM.getFileID(End)) {
166 llvm::errs() << "start or end location were in different files\n";
167 return tooling::Replacement();
168 }
169 return tooling::Replacement(
170 SM, CharSourceRange::getTokenRange(SM.getSpellingLoc(Start),
171 SM.getSpellingLoc(End)),
172 ReplacementText);
173}
174
Eric Liu4fe99e12016-12-14 17:01:52 +0000175void addReplacementOrDie(
176 SourceLocation Start, SourceLocation End, llvm::StringRef ReplacementText,
177 const SourceManager &SM,
178 std::map<std::string, tooling::Replacements> *FileToReplacements) {
179 const auto R = createReplacement(Start, End, ReplacementText, SM);
180 auto Err = (*FileToReplacements)[R.getFilePath()].add(R);
181 if (Err)
182 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
183}
184
Eric Liu495b2112016-09-19 17:40:32 +0000185tooling::Replacement createInsertion(SourceLocation Loc,
186 llvm::StringRef InsertText,
187 const SourceManager &SM) {
188 if (Loc.isInvalid()) {
189 llvm::errs() << "insert Location is invalid.\n";
190 return tooling::Replacement();
191 }
192 Loc = SM.getSpellingLoc(Loc);
193 return tooling::Replacement(SM, Loc, 0, InsertText);
194}
195
196// Returns the shortest qualified name for declaration `DeclName` in the
197// namespace `NsName`. For example, if `DeclName` is "a::b::X" and `NsName`
198// is "a::c::d", then "b::X" will be returned.
Eric Liu447164d2016-10-05 15:52:39 +0000199// \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:32 +0000202std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
203 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39 +0000204 DeclName = DeclName.ltrim(':');
205 NsName = NsName.ltrim(':');
Eric Liu447164d2016-10-05 15:52:39 +0000206 if (DeclName.find(':') == llvm::StringRef::npos)
Eric Liub9bf1b52016-11-08 22:44:17 +0000207 return DeclName;
Eric Liu447164d2016-10-05 15:52:39 +0000208
209 while (!DeclName.consume_front((NsName + "::").str())) {
Eric Liu495b2112016-09-19 17:40:32 +0000210 const auto Pos = NsName.find_last_of(':');
211 if (Pos == llvm::StringRef::npos)
212 return DeclName;
Eric Liu447164d2016-10-05 15:52:39 +0000213 assert(Pos > 0);
214 NsName = NsName.substr(0, Pos - 1);
Eric Liu495b2112016-09-19 17:40:32 +0000215 }
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:04 +0000223 NestedNs.split(NsSplitted, "::", /*MaxSplit=*/-1,
224 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32 +0000225 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:17 +0000235// 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:32 +0000255} // 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:55 +0000263 FilePattern(FilePattern), FilePatternRE(FilePattern) {
Eric Liu495b2112016-09-19 17:40:32 +0000264 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:32 +0000279void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32 +0000280 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17 +0000281 // 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:04 +0000286 llvm::StringRef(DiffOldNamespace)
287 .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1,
288 /*KeepEmpty=*/false);
Eric Liub9bf1b52016-11-08 22:44:17 +0000289 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);
309
310 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32 +0000311 Finder->addMatcher(
312 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
313 .bind("old_ns"),
314 this);
315
Eric Liu41552d62016-12-07 14:20:52 +0000316 // Match class forward-declarations in the old namespace.
317 // Note that forward-declarations in classes are not matched.
318 Finder->addMatcher(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())),
319 IsInMovedNs, hasParent(namespaceDecl()))
320 .bind("class_fwd_decl"),
321 this);
322
323 // Match template class forward-declarations in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000324 Finder->addMatcher(
Eric Liu41552d62016-12-07 14:20:52 +0000325 classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))),
326 IsInMovedNs, hasParent(namespaceDecl()))
327 .bind("template_class_fwd_decl"),
Eric Liu495b2112016-09-19 17:40:32 +0000328 this);
329
330 // Match references to types that are not defined in the old namespace.
331 // Forward-declarations in the old namespace are also matched since they will
332 // be moved back to the old namespace.
333 auto DeclMatcher = namedDecl(
334 hasAncestor(namespaceDecl()),
335 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48 +0000336 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32 +0000337 hasAncestor(cxxRecordDecl()),
338 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48 +0000339
Eric Liu8685c762016-12-07 17:04:07 +0000340 // Using shadow declarations in classes always refers to base class, which
341 // does not need to be qualified since it can be inferred from inheritance.
342 // Note that this does not match using alias declarations.
343 auto UsingShadowDeclInClass =
344 usingDecl(hasAnyUsingShadowDecl(decl()), hasParent(cxxRecordDecl()));
345
Eric Liu495b2112016-09-19 17:40:32 +0000346 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29 +0000347 // TypeLoc and template specialization arguments (which are not outermost)
348 // that are directly linked to types matching `DeclMatcher`. Nested name
349 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32 +0000350 Finder->addMatcher(
351 typeLoc(IsInMovedNs,
352 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29 +0000353 unless(anyOf(hasParent(typeLoc(loc(qualType(
354 allOf(hasDeclaration(DeclMatcher),
355 unless(templateSpecializationType())))))),
Eric Liu8685c762016-12-07 17:04:07 +0000356 hasParent(nestedNameSpecifierLoc()),
357 hasAncestor(isImplicit()),
358 hasAncestor(UsingShadowDeclInClass))),
Eric Liu495b2112016-09-19 17:40:32 +0000359 hasAncestor(decl().bind("dc")))
360 .bind("type"),
361 this);
Eric Liu912d0392016-09-27 12:54:48 +0000362
Eric Liu68765a82016-09-21 15:06:12 +0000363 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
364 // special case it.
Eric Liu8685c762016-12-07 17:04:07 +0000365 // Since using declarations inside classes must have the base class in the
366 // nested name specifier, we leave it to the nested name specifier matcher.
367 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()),
368 unless(UsingShadowDeclInClass))
Eric Liub9bf1b52016-11-08 22:44:17 +0000369 .bind("using_with_shadow"),
370 this);
Eric Liu912d0392016-09-27 12:54:48 +0000371
Eric Liuff51f012016-11-16 16:54:53 +0000372 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
373 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
374 // "A::A" would have already been fixed.
Eric Liu8685c762016-12-07 17:04:07 +0000375 Finder->addMatcher(
376 nestedNameSpecifierLoc(
377 hasAncestor(decl(IsInMovedNs).bind("dc")),
378 loc(nestedNameSpecifier(
379 specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
380 unless(anyOf(hasAncestor(isImplicit()),
381 hasAncestor(UsingShadowDeclInClass),
382 hasAncestor(typeLoc(loc(qualType(hasDeclaration(
383 decl(equalsBoundNode("from_decl"))))))))))
384 .bind("nested_specifier_loc"),
385 this);
Eric Liu12068d82016-09-22 11:54:00 +0000386
Eric Liuff51f012016-11-16 16:54:53 +0000387 // Matches base class initializers in constructors. TypeLocs of base class
388 // initializers do not need to be fixed. For example,
389 // class X : public a::b::Y {
390 // public:
391 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
392 // };
393 Finder->addMatcher(
394 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
395
Eric Liu12068d82016-09-22 11:54:00 +0000396 // Handle function.
Eric Liu912d0392016-09-27 12:54:48 +0000397 // Only handle functions that are defined in a namespace excluding member
398 // function, static methods (qualified by nested specifier), and functions
399 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00 +0000400 // Note that the matcher does not exclude calls to out-of-line static method
401 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48 +0000402 auto FuncMatcher =
403 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
404 hasAncestor(namespaceDecl(isAnonymous())),
405 hasAncestor(cxxRecordDecl()))),
406 hasParent(namespaceDecl()));
Eric Liuda22b3c2016-11-29 14:15:14 +0000407 Finder->addMatcher(decl(forEachDescendant(expr(anyOf(
408 callExpr(callee(FuncMatcher)).bind("call"),
409 declRefExpr(to(FuncMatcher.bind("func_decl")))
410 .bind("func_ref")))),
411 IsInMovedNs, unless(isImplicit()))
412 .bind("dc"),
413 this);
Eric Liu159f0132016-09-30 04:32:39 +0000414
415 auto GlobalVarMatcher = varDecl(
416 hasGlobalStorage(), hasParent(namespaceDecl()),
417 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
418 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
419 to(GlobalVarMatcher.bind("var_decl")))
420 .bind("var_ref"),
421 this);
Eric Liu495b2112016-09-19 17:40:32 +0000422}
423
424void ChangeNamespaceTool::run(
425 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17 +0000426 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
427 UsingDecls.insert(Using);
428 } else if (const auto *UsingNamespace =
429 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
430 "using_namespace")) {
431 UsingNamespaceDecls.insert(UsingNamespace);
432 } else if (const auto *NsDecl =
433 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32 +0000434 moveOldNamespace(Result, NsDecl);
435 } else if (const auto *FwdDecl =
Eric Liu41552d62016-12-07 14:20:52 +0000436 Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) {
437 moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl));
438 } else if (const auto *TemplateFwdDecl =
439 Result.Nodes.getNodeAs<ClassTemplateDecl>(
440 "template_class_fwd_decl")) {
441 moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl));
Eric Liub9bf1b52016-11-08 22:44:17 +0000442 } else if (const auto *UsingWithShadow =
443 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
444 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12 +0000445 } else if (const auto *Specifier =
446 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
447 "nested_specifier_loc")) {
448 SourceLocation Start = Specifier->getBeginLoc();
Eric Liuc265b022016-12-01 17:25:55 +0000449 SourceLocation End = endLocationForType(Specifier->getTypeLoc());
Eric Liu68765a82016-09-21 15:06:12 +0000450 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53 +0000451 } else if (const auto *BaseInitializer =
452 Result.Nodes.getNodeAs<CXXCtorInitializer>(
453 "base_initializer")) {
454 BaseCtorInitializerTypeLocs.push_back(
455 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00 +0000456 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu26cf68a2016-12-15 10:42:35 +0000457 // This avoids fixing types with record types as qualifier, which is not
458 // filtered by matchers in some cases, e.g. the type is templated. We should
459 // handle the record type qualifier instead.
460 if (TLoc->getTypeLocClass() == TypeLoc::Elaborated) {
461 NestedNameSpecifierLoc NestedNameSpecifier =
462 TLoc->castAs<ElaboratedTypeLoc>().getQualifierLoc();
463 const Type *SpecifierType =
464 NestedNameSpecifier.getNestedNameSpecifier()->getAsType();
465 if (SpecifierType && SpecifierType->isRecordType())
466 return;
467 }
Eric Liuc265b022016-12-01 17:25:55 +0000468 fixTypeLoc(Result, startLocationForType(*TLoc), endLocationForType(*TLoc),
Eric Liu495b2112016-09-19 17:40:32 +0000469 *TLoc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000470 } else if (const auto *VarRef =
471 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39 +0000472 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
473 assert(Var);
474 if (Var->getCanonicalDecl()->isStaticDataMember())
475 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000476 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu159f0132016-09-30 04:32:39 +0000477 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000478 fixDeclRefExpr(Result, Context->getDeclContext(),
479 llvm::cast<NamedDecl>(Var), VarRef);
480 } else if (const auto *FuncRef =
481 Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) {
482 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
483 assert(Func);
484 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
485 assert(Context && "Empty decl context.");
486 fixDeclRefExpr(Result, Context->getDeclContext(),
487 llvm::cast<NamedDecl>(Func), FuncRef);
Eric Liu12068d82016-09-22 11:54:00 +0000488 } else {
Eric Liuda22b3c2016-11-29 14:15:14 +0000489 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000490 assert(Call != nullptr && "Expecting callback for CallExpr.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000491 const FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00 +0000492 assert(Func != nullptr);
493 // Ignore out-of-line static methods since they will be handled by nested
494 // name specifiers.
495 if (Func->getCanonicalDecl()->getStorageClass() ==
Eric Liuda22b3c2016-11-29 14:15:14 +0000496 StorageClass::SC_Static &&
Eric Liu12068d82016-09-22 11:54:00 +0000497 Func->isOutOfLine())
498 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000499 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu12068d82016-09-22 11:54:00 +0000500 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000501 SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17 +0000502 replaceQualifiedSymbolInDeclContext(
503 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34 +0000504 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32 +0000505 }
506}
507
Eric Liu73f49fd2016-10-12 12:34:18 +0000508static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
509 const SourceManager &SM,
510 const LangOptions &LangOpts) {
511 std::unique_ptr<Lexer> Lex =
512 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
513 assert(Lex.get() &&
514 "Failed to create lexer from the beginning of namespace.");
515 if (!Lex.get())
516 return SourceLocation();
517 Token Tok;
518 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
519 }
520 return Tok.isNot(tok::TokenKind::l_brace)
521 ? SourceLocation()
522 : Tok.getEndLoc().getLocWithOffset(1);
523}
524
Eric Liu495b2112016-09-19 17:40:32 +0000525// Stores information about a moved namespace in `MoveNamespaces` and leaves
526// the actual movement to `onEndOfTranslationUnit()`.
527void ChangeNamespaceTool::moveOldNamespace(
528 const ast_matchers::MatchFinder::MatchResult &Result,
529 const NamespaceDecl *NsDecl) {
530 // If the namespace is empty, do nothing.
531 if (Decl::castToDeclContext(NsDecl)->decls_empty())
532 return;
533
534 // Get the range of the code in the old namespace.
Eric Liu73f49fd2016-10-12 12:34:18 +0000535 SourceLocation Start = getLocAfterNamespaceLBrace(
536 NsDecl, *Result.SourceManager, Result.Context->getLangOpts());
537 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32 +0000538 SourceLocation End = NsDecl->getRBraceLoc().getLocWithOffset(-1);
539 // Create a replacement that deletes the code in the old namespace merely for
540 // retrieving offset and length from it.
541 const auto R = createReplacement(Start, End, "", *Result.SourceManager);
542 MoveNamespace MoveNs;
543 MoveNs.Offset = R.getOffset();
544 MoveNs.Length = R.getLength();
545
546 // Insert the new namespace after `DiffOldNamespace`. For example, if
547 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
548 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
549 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
550 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01 +0000551 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
552 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000553 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01 +0000554 SourceLocation InsertionLoc = Start;
555 if (OuterNs) {
556 SourceLocation LocAfterNs =
557 getStartOfNextLine(OuterNs->getRBraceLoc(), *Result.SourceManager,
558 Result.Context->getLangOpts());
559 assert(LocAfterNs.isValid() &&
560 "Failed to get location after DiffOldNamespace");
561 InsertionLoc = LocAfterNs;
562 }
Eric Liu495b2112016-09-19 17:40:32 +0000563 MoveNs.InsertionOffset = Result.SourceManager->getFileOffset(
Eric Liu6aa94162016-11-10 18:29:01 +0000564 Result.SourceManager->getSpellingLoc(InsertionLoc));
Eric Liucc83c662016-09-19 17:58:59 +0000565 MoveNs.FID = Result.SourceManager->getFileID(Start);
566 MoveNs.SourceMgr = Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32 +0000567 MoveNamespaces[R.getFilePath()].push_back(MoveNs);
568}
569
570// Removes a class forward declaration from the code in the moved namespace and
571// creates an `InsertForwardDeclaration` to insert the forward declaration back
572// into the old namespace after moving code from the old namespace to the new
573// namespace.
574// For example, changing "a" to "x":
575// Old code:
576// namespace a {
577// class FWD;
578// class A { FWD *fwd; }
579// } // a
580// New code:
581// namespace a {
582// class FWD;
583// } // a
584// namespace x {
585// class A { a::FWD *fwd; }
586// } // x
587void ChangeNamespaceTool::moveClassForwardDeclaration(
588 const ast_matchers::MatchFinder::MatchResult &Result,
Eric Liu41552d62016-12-07 14:20:52 +0000589 const NamedDecl *FwdDecl) {
Eric Liu495b2112016-09-19 17:40:32 +0000590 SourceLocation Start = FwdDecl->getLocStart();
591 SourceLocation End = FwdDecl->getLocEnd();
592 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
593 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
594 /*SkipTrailingWhitespaceAndNewLine=*/true);
595 if (AfterSemi.isValid())
596 End = AfterSemi.getLocWithOffset(-1);
597 // Delete the forward declaration from the code to be moved.
Eric Liu4fe99e12016-12-14 17:01:52 +0000598 addReplacementOrDie(Start, End, "", *Result.SourceManager,
599 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32 +0000600 llvm::StringRef Code = Lexer::getSourceText(
601 CharSourceRange::getTokenRange(
602 Result.SourceManager->getSpellingLoc(Start),
603 Result.SourceManager->getSpellingLoc(End)),
604 *Result.SourceManager, Result.Context->getLangOpts());
605 // Insert the forward declaration back into the old namespace after moving the
606 // code from old namespace to new namespace.
607 // Insertion information is stored in `InsertFwdDecls` and actual
608 // insertion will be performed in `onEndOfTranslationUnit`.
609 // Get the (old) namespace that contains the forward declaration.
610 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
611 // The namespace contains the forward declaration, so it must not be empty.
612 assert(!NsDecl->decls_empty());
613 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
614 Code, *Result.SourceManager);
615 InsertForwardDeclaration InsertFwd;
616 InsertFwd.InsertionOffset = Insertion.getOffset();
617 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
618 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
619}
620
Eric Liub9bf1b52016-11-08 22:44:17 +0000621// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
622// FromDecl with the shortest qualified name possible when the reference is in
623// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32 +0000624void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17 +0000625 const ast_matchers::MatchFinder::MatchResult &Result,
626 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
627 const NamedDecl *FromDecl) {
628 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu4fe99e12016-12-14 17:01:52 +0000629 if (llvm::isa<TranslationUnitDecl>(NsDeclContext)) {
630 // This should not happen in usual unless the TypeLoc is in function type
631 // parameters, e.g `std::function<void(T)>`. In this case, DeclContext of
632 // `T` will be the translation unit. We simply use fully-qualified name
633 // here.
634 // Note that `FromDecl` must not be defined in the old namespace (according
635 // to `DeclMatcher`), so its fully-qualified name will not change after
636 // changing the namespace.
637 addReplacementOrDie(Start, End, FromDecl->getQualifiedNameAsString(),
638 *Result.SourceManager, &FileToReplacements);
639 return;
640 }
Eric Liu231c6552016-11-10 18:15:34 +0000641 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32 +0000642 // Calculate the name of the `NsDecl` after it is moved to new namespace.
643 std::string OldNs = NsDecl->getQualifiedNameAsString();
644 llvm::StringRef Postfix = OldNs;
645 bool Consumed = Postfix.consume_front(OldNamespace);
646 assert(Consumed && "Expect OldNS to start with OldNamespace.");
647 (void)Consumed;
648 const std::string NewNs = (NewNamespace + Postfix).str();
649
650 llvm::StringRef NestedName = Lexer::getSourceText(
651 CharSourceRange::getTokenRange(
652 Result.SourceManager->getSpellingLoc(Start),
653 Result.SourceManager->getSpellingLoc(End)),
654 *Result.SourceManager, Result.Context->getLangOpts());
655 // If the symbol is already fully qualified, no change needs to be make.
656 if (NestedName.startswith("::"))
657 return;
Eric Liub9bf1b52016-11-08 22:44:17 +0000658 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu495b2112016-09-19 17:40:32 +0000659 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17 +0000660 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
661 // Checks if there is any using namespace declarations that can shorten the
662 // qualified name.
663 for (const auto *UsingNamespace : UsingNamespaceDecls) {
664 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
665 Start))
666 continue;
667 StringRef FromDeclNameRef = FromDeclName;
668 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
669 ->getQualifiedNameAsString())) {
670 FromDeclNameRef = FromDeclNameRef.drop_front(2);
671 if (FromDeclNameRef.size() < ReplaceName.size())
672 ReplaceName = FromDeclNameRef;
673 }
674 }
675 // Checks if there is any using shadow declarations that can shorten the
676 // qualified name.
677 bool Matched = false;
678 for (const UsingDecl *Using : UsingDecls) {
679 if (Matched)
680 break;
681 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
682 for (const auto *UsingShadow : Using->shadows()) {
683 const auto *TargetDecl = UsingShadow->getTargetDecl();
684 if (TargetDecl == FromDecl) {
685 ReplaceName = FromDecl->getNameAsString();
686 Matched = true;
687 break;
688 }
689 }
690 }
691 }
Eric Liu495b2112016-09-19 17:40:32 +0000692 // If the new nested name in the new namespace is the same as it was in the
693 // old namespace, we don't create replacement.
694 if (NestedName == ReplaceName)
695 return;
Eric Liu97f87ad2016-12-07 20:08:02 +0000696 // If the reference need to be fully-qualified, add a leading "::" unless
697 // NewNamespace is the global namespace.
698 if (ReplaceName == FromDeclName && !NewNamespace.empty())
699 ReplaceName = "::" + ReplaceName;
Eric Liu4fe99e12016-12-14 17:01:52 +0000700 addReplacementOrDie(Start, End, ReplaceName, *Result.SourceManager,
701 &FileToReplacements);
Eric Liu495b2112016-09-19 17:40:32 +0000702}
703
704// Replace the [Start, End] of `Type` with the shortest qualified name when the
705// `Type` is in `NewNamespace`.
706void ChangeNamespaceTool::fixTypeLoc(
707 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
708 SourceLocation End, TypeLoc Type) {
709 // FIXME: do not rename template parameter.
710 if (Start.isInvalid() || End.isInvalid())
711 return;
Eric Liuff51f012016-11-16 16:54:53 +0000712 // Types of CXXCtorInitializers do not need to be fixed.
713 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
714 return;
Eric Liu495b2112016-09-19 17:40:32 +0000715 // The declaration which this TypeLoc refers to.
716 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
717 // `hasDeclaration` gives underlying declaration, but if the type is
718 // a typedef type, we need to use the typedef type instead.
Eric Liu26cf68a2016-12-15 10:42:35 +0000719 auto IsInMovedNs = [&](const NamedDecl *D) {
720 if (!llvm::StringRef(D->getQualifiedNameAsString())
721 .startswith(OldNamespace + "::"))
722 return false;
723 auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getLocStart());
724 if (ExpansionLoc.isInvalid())
725 return false;
726 llvm::StringRef Filename = Result.SourceManager->getFilename(ExpansionLoc);
727 return FilePatternRE.match(Filename);
728 };
729 // Make `FromDecl` the immediate declaration that `Type` refers to, i.e. if
730 // `Type` is an alias type, we make `FromDecl` the type alias declaration.
731 // Also, don't fix the \p Type if it refers to a type alias decl in the moved
732 // namespace since the alias decl will be moved along with the type reference.
Eric Liu32158862016-11-14 19:37:55 +0000733 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32 +0000734 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55 +0000735 if (IsInMovedNs(FromDecl))
736 return;
Eric Liu26cf68a2016-12-15 10:42:35 +0000737 } else if (auto *TemplateType =
738 Type.getType()->getAs<TemplateSpecializationType>()) {
739 if (TemplateType->isTypeAlias()) {
740 FromDecl = TemplateType->getTemplateName().getAsTemplateDecl();
741 if (IsInMovedNs(FromDecl))
742 return;
743 }
Eric Liu32158862016-11-14 19:37:55 +0000744 }
Piotr Padlewski08124b12016-12-14 15:29:23 +0000745 const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu495b2112016-09-19 17:40:32 +0000746 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17 +0000747 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
748 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32 +0000749}
750
Eric Liu68765a82016-09-21 15:06:12 +0000751void ChangeNamespaceTool::fixUsingShadowDecl(
752 const ast_matchers::MatchFinder::MatchResult &Result,
753 const UsingDecl *UsingDeclaration) {
754 SourceLocation Start = UsingDeclaration->getLocStart();
755 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000756 if (Start.isInvalid() || End.isInvalid())
757 return;
Eric Liu68765a82016-09-21 15:06:12 +0000758
759 assert(UsingDeclaration->shadow_size() > 0);
760 // FIXME: it might not be always accurate to use the first using-decl.
761 const NamedDecl *TargetDecl =
762 UsingDeclaration->shadow_begin()->getTargetDecl();
763 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
764 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
765 // sense. If this happens, we need to use name with the new namespace.
766 // Use fully qualified name in UsingDecl for now.
Eric Liu4fe99e12016-12-14 17:01:52 +0000767 addReplacementOrDie(Start, End, "using ::" + TargetDeclName,
768 *Result.SourceManager, &FileToReplacements);
Eric Liu68765a82016-09-21 15:06:12 +0000769}
770
Eric Liuda22b3c2016-11-29 14:15:14 +0000771void ChangeNamespaceTool::fixDeclRefExpr(
772 const ast_matchers::MatchFinder::MatchResult &Result,
773 const DeclContext *UseContext, const NamedDecl *From,
774 const DeclRefExpr *Ref) {
775 SourceRange RefRange = Ref->getSourceRange();
776 replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(),
777 RefRange.getEnd(), From);
778}
779
Eric Liu495b2112016-09-19 17:40:32 +0000780void ChangeNamespaceTool::onEndOfTranslationUnit() {
781 // Move namespace blocks and insert forward declaration to old namespace.
782 for (const auto &FileAndNsMoves : MoveNamespaces) {
783 auto &NsMoves = FileAndNsMoves.second;
784 if (NsMoves.empty())
785 continue;
786 const std::string &FilePath = FileAndNsMoves.first;
787 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59 +0000788 auto &SM = *NsMoves.begin()->SourceMgr;
789 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32 +0000790 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
791 if (!ChangedCode) {
792 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
793 continue;
794 }
795 // Replacements on the changed code for moving namespaces and inserting
796 // forward declarations to old namespaces.
797 tooling::Replacements NewReplacements;
798 // Cut the changed code from the old namespace and paste the code in the new
799 // namespace.
800 for (const auto &NsMove : NsMoves) {
801 // Calculate the range of the old namespace block in the changed
802 // code.
803 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
804 const unsigned NewLength =
805 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
806 NewOffset;
807 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
808 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
809 std::string MovedCodeWrappedInNewNs =
810 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
811 // Calculate the new offset at which the code will be inserted in the
812 // changed code.
813 unsigned NewInsertionOffset =
814 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
815 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
816 MovedCodeWrappedInNewNs);
817 addOrMergeReplacement(Deletion, &NewReplacements);
818 addOrMergeReplacement(Insertion, &NewReplacements);
819 }
820 // After moving namespaces, insert forward declarations back to old
821 // namespaces.
822 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
823 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
824 unsigned NewInsertionOffset =
825 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
826 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
827 FwdDeclInsertion.ForwardDeclText);
828 addOrMergeReplacement(Insertion, &NewReplacements);
829 }
830 // Add replacements referring to the changed code to existing replacements,
831 // which refers to the original code.
832 Replaces = Replaces.merge(NewReplacements);
833 format::FormatStyle Style =
834 format::getStyle("file", FilePath, FallbackStyle);
835 // Clean up old namespaces if there is nothing in it after moving.
836 auto CleanReplacements =
837 format::cleanupAroundReplacements(Code, Replaces, Style);
838 if (!CleanReplacements) {
839 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
840 continue;
841 }
842 FileToReplacements[FilePath] = *CleanReplacements;
843 }
Eric Liuc265b022016-12-01 17:25:55 +0000844
845 // Make sure we don't generate replacements for files that do not match
846 // FilePattern.
847 for (auto &Entry : FileToReplacements)
848 if (!FilePatternRE.match(Entry.first))
849 Entry.second.clear();
Eric Liu495b2112016-09-19 17:40:32 +0000850}
851
852} // namespace change_namespace
853} // namespace clang