blob: 4806f1ef1239c704b60ec5018ef4ecdf3e37fbfb [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
175tooling::Replacement createInsertion(SourceLocation Loc,
176 llvm::StringRef InsertText,
177 const SourceManager &SM) {
178 if (Loc.isInvalid()) {
179 llvm::errs() << "insert Location is invalid.\n";
180 return tooling::Replacement();
181 }
182 Loc = SM.getSpellingLoc(Loc);
183 return tooling::Replacement(SM, Loc, 0, InsertText);
184}
185
186// Returns the shortest qualified name for declaration `DeclName` in the
187// namespace `NsName`. For example, if `DeclName` is "a::b::X" and `NsName`
188// is "a::c::d", then "b::X" will be returned.
Eric Liu447164d2016-10-05 15:52:39 +0000189// \param DeclName A fully qualified name, "::a::b::X" or "a::b::X".
190// \param NsName A fully qualified name, "::a::b" or "a::b". Global namespace
191// will have empty name.
Eric Liu495b2112016-09-19 17:40:32 +0000192std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName,
193 llvm::StringRef NsName) {
Eric Liu447164d2016-10-05 15:52:39 +0000194 DeclName = DeclName.ltrim(':');
195 NsName = NsName.ltrim(':');
Eric Liu447164d2016-10-05 15:52:39 +0000196 if (DeclName.find(':') == llvm::StringRef::npos)
Eric Liub9bf1b52016-11-08 22:44:17 +0000197 return DeclName;
Eric Liu447164d2016-10-05 15:52:39 +0000198
199 while (!DeclName.consume_front((NsName + "::").str())) {
Eric Liu495b2112016-09-19 17:40:32 +0000200 const auto Pos = NsName.find_last_of(':');
201 if (Pos == llvm::StringRef::npos)
202 return DeclName;
Eric Liu447164d2016-10-05 15:52:39 +0000203 assert(Pos > 0);
204 NsName = NsName.substr(0, Pos - 1);
Eric Liu495b2112016-09-19 17:40:32 +0000205 }
206 return DeclName;
207}
208
209std::string wrapCodeInNamespace(StringRef NestedNs, std::string Code) {
210 if (Code.back() != '\n')
211 Code += "\n";
212 llvm::SmallVector<StringRef, 4> NsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04 +0000213 NestedNs.split(NsSplitted, "::", /*MaxSplit=*/-1,
214 /*KeepEmpty=*/false);
Eric Liu495b2112016-09-19 17:40:32 +0000215 while (!NsSplitted.empty()) {
216 // FIXME: consider code style for comments.
217 Code = ("namespace " + NsSplitted.back() + " {\n" + Code +
218 "} // namespace " + NsSplitted.back() + "\n")
219 .str();
220 NsSplitted.pop_back();
221 }
222 return Code;
223}
224
Eric Liub9bf1b52016-11-08 22:44:17 +0000225// Returns true if \p D is a nested DeclContext in \p Context
226bool isNestedDeclContext(const DeclContext *D, const DeclContext *Context) {
227 while (D) {
228 if (D == Context)
229 return true;
230 D = D->getParent();
231 }
232 return false;
233}
234
235// Returns true if \p D is visible at \p Loc with DeclContext \p DeclCtx.
236bool isDeclVisibleAtLocation(const SourceManager &SM, const Decl *D,
237 const DeclContext *DeclCtx, SourceLocation Loc) {
238 SourceLocation DeclLoc = SM.getSpellingLoc(D->getLocation());
239 Loc = SM.getSpellingLoc(Loc);
240 return SM.isBeforeInTranslationUnit(DeclLoc, Loc) &&
241 (SM.getFileID(DeclLoc) == SM.getFileID(Loc) &&
242 isNestedDeclContext(DeclCtx, D->getDeclContext()));
243}
244
Eric Liu495b2112016-09-19 17:40:32 +0000245} // anonymous namespace
246
247ChangeNamespaceTool::ChangeNamespaceTool(
248 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
249 std::map<std::string, tooling::Replacements> *FileToReplacements,
250 llvm::StringRef FallbackStyle)
251 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
252 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
Eric Liuc265b022016-12-01 17:25:55 +0000253 FilePattern(FilePattern), FilePatternRE(FilePattern) {
Eric Liu495b2112016-09-19 17:40:32 +0000254 FileToReplacements->clear();
255 llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted;
256 llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted;
257 llvm::StringRef(OldNamespace).split(OldNsSplitted, "::");
258 llvm::StringRef(NewNamespace).split(NewNsSplitted, "::");
259 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
260 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
261 OldNsSplitted.front() == NewNsSplitted.front()) {
262 OldNsSplitted.erase(OldNsSplitted.begin());
263 NewNsSplitted.erase(NewNsSplitted.begin());
264 }
265 DiffOldNamespace = joinNamespaces(OldNsSplitted);
266 DiffNewNamespace = joinNamespaces(NewNsSplitted);
267}
268
Eric Liu495b2112016-09-19 17:40:32 +0000269void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32 +0000270 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17 +0000271 // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the
272 // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will
273 // be "a::b". Declarations in this namespace will not be visible in the new
274 // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-".
275 llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted;
Eric Liu2dd0e1b2016-12-05 11:17:04 +0000276 llvm::StringRef(DiffOldNamespace)
277 .split(DiffOldNsSplitted, "::", /*MaxSplit=*/-1,
278 /*KeepEmpty=*/false);
Eric Liub9bf1b52016-11-08 22:44:17 +0000279 std::string Prefix = "-";
280 if (!DiffOldNsSplitted.empty())
281 Prefix = (StringRef(FullOldNs).drop_back(DiffOldNamespace.size()) +
282 DiffOldNsSplitted.front())
283 .str();
284 auto IsInMovedNs =
285 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
286 isExpansionInFileMatching(FilePattern));
287 auto IsVisibleInNewNs = anyOf(
288 IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Prefix)))));
289 // Match using declarations.
290 Finder->addMatcher(
291 usingDecl(isExpansionInFileMatching(FilePattern), IsVisibleInNewNs)
292 .bind("using"),
293 this);
294 // Match using namespace declarations.
295 Finder->addMatcher(usingDirectiveDecl(isExpansionInFileMatching(FilePattern),
296 IsVisibleInNewNs)
297 .bind("using_namespace"),
298 this);
299
300 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32 +0000301 Finder->addMatcher(
302 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
303 .bind("old_ns"),
304 this);
305
Eric Liu41552d62016-12-07 14:20:52 +0000306 // Match class forward-declarations in the old namespace.
307 // Note that forward-declarations in classes are not matched.
308 Finder->addMatcher(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())),
309 IsInMovedNs, hasParent(namespaceDecl()))
310 .bind("class_fwd_decl"),
311 this);
312
313 // Match template class forward-declarations in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000314 Finder->addMatcher(
Eric Liu41552d62016-12-07 14:20:52 +0000315 classTemplateDecl(unless(hasDescendant(cxxRecordDecl(isDefinition()))),
316 IsInMovedNs, hasParent(namespaceDecl()))
317 .bind("template_class_fwd_decl"),
Eric Liu495b2112016-09-19 17:40:32 +0000318 this);
319
320 // Match references to types that are not defined in the old namespace.
321 // Forward-declarations in the old namespace are also matched since they will
322 // be moved back to the old namespace.
323 auto DeclMatcher = namedDecl(
324 hasAncestor(namespaceDecl()),
325 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48 +0000326 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32 +0000327 hasAncestor(cxxRecordDecl()),
328 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48 +0000329
Eric Liu8685c762016-12-07 17:04:07 +0000330 // Using shadow declarations in classes always refers to base class, which
331 // does not need to be qualified since it can be inferred from inheritance.
332 // Note that this does not match using alias declarations.
333 auto UsingShadowDeclInClass =
334 usingDecl(hasAnyUsingShadowDecl(decl()), hasParent(cxxRecordDecl()));
335
Eric Liu495b2112016-09-19 17:40:32 +0000336 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29 +0000337 // TypeLoc and template specialization arguments (which are not outermost)
338 // that are directly linked to types matching `DeclMatcher`. Nested name
339 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32 +0000340 Finder->addMatcher(
341 typeLoc(IsInMovedNs,
342 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29 +0000343 unless(anyOf(hasParent(typeLoc(loc(qualType(
344 allOf(hasDeclaration(DeclMatcher),
345 unless(templateSpecializationType())))))),
Eric Liu8685c762016-12-07 17:04:07 +0000346 hasParent(nestedNameSpecifierLoc()),
347 hasAncestor(isImplicit()),
348 hasAncestor(UsingShadowDeclInClass))),
Eric Liu495b2112016-09-19 17:40:32 +0000349 hasAncestor(decl().bind("dc")))
350 .bind("type"),
351 this);
Eric Liu912d0392016-09-27 12:54:48 +0000352
Eric Liu68765a82016-09-21 15:06:12 +0000353 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
354 // special case it.
Eric Liu8685c762016-12-07 17:04:07 +0000355 // Since using declarations inside classes must have the base class in the
356 // nested name specifier, we leave it to the nested name specifier matcher.
357 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()),
358 unless(UsingShadowDeclInClass))
Eric Liub9bf1b52016-11-08 22:44:17 +0000359 .bind("using_with_shadow"),
360 this);
Eric Liu912d0392016-09-27 12:54:48 +0000361
Eric Liuff51f012016-11-16 16:54:53 +0000362 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
363 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
364 // "A::A" would have already been fixed.
Eric Liu8685c762016-12-07 17:04:07 +0000365 Finder->addMatcher(
366 nestedNameSpecifierLoc(
367 hasAncestor(decl(IsInMovedNs).bind("dc")),
368 loc(nestedNameSpecifier(
369 specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
370 unless(anyOf(hasAncestor(isImplicit()),
371 hasAncestor(UsingShadowDeclInClass),
372 hasAncestor(typeLoc(loc(qualType(hasDeclaration(
373 decl(equalsBoundNode("from_decl"))))))))))
374 .bind("nested_specifier_loc"),
375 this);
Eric Liu12068d82016-09-22 11:54:00 +0000376
Eric Liuff51f012016-11-16 16:54:53 +0000377 // Matches base class initializers in constructors. TypeLocs of base class
378 // initializers do not need to be fixed. For example,
379 // class X : public a::b::Y {
380 // public:
381 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
382 // };
383 Finder->addMatcher(
384 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
385
Eric Liu12068d82016-09-22 11:54:00 +0000386 // Handle function.
Eric Liu912d0392016-09-27 12:54:48 +0000387 // Only handle functions that are defined in a namespace excluding member
388 // function, static methods (qualified by nested specifier), and functions
389 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00 +0000390 // Note that the matcher does not exclude calls to out-of-line static method
391 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48 +0000392 auto FuncMatcher =
393 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
394 hasAncestor(namespaceDecl(isAnonymous())),
395 hasAncestor(cxxRecordDecl()))),
396 hasParent(namespaceDecl()));
Eric Liuda22b3c2016-11-29 14:15:14 +0000397 Finder->addMatcher(decl(forEachDescendant(expr(anyOf(
398 callExpr(callee(FuncMatcher)).bind("call"),
399 declRefExpr(to(FuncMatcher.bind("func_decl")))
400 .bind("func_ref")))),
401 IsInMovedNs, unless(isImplicit()))
402 .bind("dc"),
403 this);
Eric Liu159f0132016-09-30 04:32:39 +0000404
405 auto GlobalVarMatcher = varDecl(
406 hasGlobalStorage(), hasParent(namespaceDecl()),
407 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
408 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
409 to(GlobalVarMatcher.bind("var_decl")))
410 .bind("var_ref"),
411 this);
Eric Liu495b2112016-09-19 17:40:32 +0000412}
413
414void ChangeNamespaceTool::run(
415 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17 +0000416 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
417 UsingDecls.insert(Using);
418 } else if (const auto *UsingNamespace =
419 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
420 "using_namespace")) {
421 UsingNamespaceDecls.insert(UsingNamespace);
422 } else if (const auto *NsDecl =
423 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32 +0000424 moveOldNamespace(Result, NsDecl);
425 } else if (const auto *FwdDecl =
Eric Liu41552d62016-12-07 14:20:52 +0000426 Result.Nodes.getNodeAs<CXXRecordDecl>("class_fwd_decl")) {
427 moveClassForwardDeclaration(Result, cast<NamedDecl>(FwdDecl));
428 } else if (const auto *TemplateFwdDecl =
429 Result.Nodes.getNodeAs<ClassTemplateDecl>(
430 "template_class_fwd_decl")) {
431 moveClassForwardDeclaration(Result, cast<NamedDecl>(TemplateFwdDecl));
Eric Liub9bf1b52016-11-08 22:44:17 +0000432 } else if (const auto *UsingWithShadow =
433 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
434 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12 +0000435 } else if (const auto *Specifier =
436 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
437 "nested_specifier_loc")) {
438 SourceLocation Start = Specifier->getBeginLoc();
Eric Liuc265b022016-12-01 17:25:55 +0000439 SourceLocation End = endLocationForType(Specifier->getTypeLoc());
Eric Liu68765a82016-09-21 15:06:12 +0000440 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53 +0000441 } else if (const auto *BaseInitializer =
442 Result.Nodes.getNodeAs<CXXCtorInitializer>(
443 "base_initializer")) {
444 BaseCtorInitializerTypeLocs.push_back(
445 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00 +0000446 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liuc265b022016-12-01 17:25:55 +0000447 fixTypeLoc(Result, startLocationForType(*TLoc), endLocationForType(*TLoc),
Eric Liu495b2112016-09-19 17:40:32 +0000448 *TLoc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000449 } else if (const auto *VarRef =
450 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39 +0000451 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
452 assert(Var);
453 if (Var->getCanonicalDecl()->isStaticDataMember())
454 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000455 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu159f0132016-09-30 04:32:39 +0000456 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000457 fixDeclRefExpr(Result, Context->getDeclContext(),
458 llvm::cast<NamedDecl>(Var), VarRef);
459 } else if (const auto *FuncRef =
460 Result.Nodes.getNodeAs<DeclRefExpr>("func_ref")) {
461 const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
462 assert(Func);
463 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
464 assert(Context && "Empty decl context.");
465 fixDeclRefExpr(Result, Context->getDeclContext(),
466 llvm::cast<NamedDecl>(Func), FuncRef);
Eric Liu12068d82016-09-22 11:54:00 +0000467 } else {
Eric Liuda22b3c2016-11-29 14:15:14 +0000468 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000469 assert(Call != nullptr && "Expecting callback for CallExpr.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000470 const FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00 +0000471 assert(Func != nullptr);
472 // Ignore out-of-line static methods since they will be handled by nested
473 // name specifiers.
474 if (Func->getCanonicalDecl()->getStorageClass() ==
Eric Liuda22b3c2016-11-29 14:15:14 +0000475 StorageClass::SC_Static &&
Eric Liu12068d82016-09-22 11:54:00 +0000476 Func->isOutOfLine())
477 return;
Eric Liuda22b3c2016-11-29 14:15:14 +0000478 const auto *Context = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu12068d82016-09-22 11:54:00 +0000479 assert(Context && "Empty decl context.");
Eric Liuda22b3c2016-11-29 14:15:14 +0000480 SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17 +0000481 replaceQualifiedSymbolInDeclContext(
482 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34 +0000483 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32 +0000484 }
485}
486
Eric Liu73f49fd2016-10-12 12:34:18 +0000487static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
488 const SourceManager &SM,
489 const LangOptions &LangOpts) {
490 std::unique_ptr<Lexer> Lex =
491 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
492 assert(Lex.get() &&
493 "Failed to create lexer from the beginning of namespace.");
494 if (!Lex.get())
495 return SourceLocation();
496 Token Tok;
497 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
498 }
499 return Tok.isNot(tok::TokenKind::l_brace)
500 ? SourceLocation()
501 : Tok.getEndLoc().getLocWithOffset(1);
502}
503
Eric Liu495b2112016-09-19 17:40:32 +0000504// Stores information about a moved namespace in `MoveNamespaces` and leaves
505// the actual movement to `onEndOfTranslationUnit()`.
506void ChangeNamespaceTool::moveOldNamespace(
507 const ast_matchers::MatchFinder::MatchResult &Result,
508 const NamespaceDecl *NsDecl) {
509 // If the namespace is empty, do nothing.
510 if (Decl::castToDeclContext(NsDecl)->decls_empty())
511 return;
512
513 // Get the range of the code in the old namespace.
Eric Liu73f49fd2016-10-12 12:34:18 +0000514 SourceLocation Start = getLocAfterNamespaceLBrace(
515 NsDecl, *Result.SourceManager, Result.Context->getLangOpts());
516 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32 +0000517 SourceLocation End = NsDecl->getRBraceLoc().getLocWithOffset(-1);
518 // Create a replacement that deletes the code in the old namespace merely for
519 // retrieving offset and length from it.
520 const auto R = createReplacement(Start, End, "", *Result.SourceManager);
521 MoveNamespace MoveNs;
522 MoveNs.Offset = R.getOffset();
523 MoveNs.Length = R.getLength();
524
525 // Insert the new namespace after `DiffOldNamespace`. For example, if
526 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
527 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
528 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
529 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01 +0000530 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
531 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000532 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01 +0000533 SourceLocation InsertionLoc = Start;
534 if (OuterNs) {
535 SourceLocation LocAfterNs =
536 getStartOfNextLine(OuterNs->getRBraceLoc(), *Result.SourceManager,
537 Result.Context->getLangOpts());
538 assert(LocAfterNs.isValid() &&
539 "Failed to get location after DiffOldNamespace");
540 InsertionLoc = LocAfterNs;
541 }
Eric Liu495b2112016-09-19 17:40:32 +0000542 MoveNs.InsertionOffset = Result.SourceManager->getFileOffset(
Eric Liu6aa94162016-11-10 18:29:01 +0000543 Result.SourceManager->getSpellingLoc(InsertionLoc));
Eric Liucc83c662016-09-19 17:58:59 +0000544 MoveNs.FID = Result.SourceManager->getFileID(Start);
545 MoveNs.SourceMgr = Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32 +0000546 MoveNamespaces[R.getFilePath()].push_back(MoveNs);
547}
548
549// Removes a class forward declaration from the code in the moved namespace and
550// creates an `InsertForwardDeclaration` to insert the forward declaration back
551// into the old namespace after moving code from the old namespace to the new
552// namespace.
553// For example, changing "a" to "x":
554// Old code:
555// namespace a {
556// class FWD;
557// class A { FWD *fwd; }
558// } // a
559// New code:
560// namespace a {
561// class FWD;
562// } // a
563// namespace x {
564// class A { a::FWD *fwd; }
565// } // x
566void ChangeNamespaceTool::moveClassForwardDeclaration(
567 const ast_matchers::MatchFinder::MatchResult &Result,
Eric Liu41552d62016-12-07 14:20:52 +0000568 const NamedDecl *FwdDecl) {
Eric Liu495b2112016-09-19 17:40:32 +0000569 SourceLocation Start = FwdDecl->getLocStart();
570 SourceLocation End = FwdDecl->getLocEnd();
571 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
572 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
573 /*SkipTrailingWhitespaceAndNewLine=*/true);
574 if (AfterSemi.isValid())
575 End = AfterSemi.getLocWithOffset(-1);
576 // Delete the forward declaration from the code to be moved.
577 const auto Deletion =
578 createReplacement(Start, End, "", *Result.SourceManager);
Eric Liuff51f012016-11-16 16:54:53 +0000579 auto Err = FileToReplacements[Deletion.getFilePath()].add(Deletion);
580 if (Err)
581 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
Eric Liu495b2112016-09-19 17:40:32 +0000582 llvm::StringRef Code = Lexer::getSourceText(
583 CharSourceRange::getTokenRange(
584 Result.SourceManager->getSpellingLoc(Start),
585 Result.SourceManager->getSpellingLoc(End)),
586 *Result.SourceManager, Result.Context->getLangOpts());
587 // Insert the forward declaration back into the old namespace after moving the
588 // code from old namespace to new namespace.
589 // Insertion information is stored in `InsertFwdDecls` and actual
590 // insertion will be performed in `onEndOfTranslationUnit`.
591 // Get the (old) namespace that contains the forward declaration.
592 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
593 // The namespace contains the forward declaration, so it must not be empty.
594 assert(!NsDecl->decls_empty());
595 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
596 Code, *Result.SourceManager);
597 InsertForwardDeclaration InsertFwd;
598 InsertFwd.InsertionOffset = Insertion.getOffset();
599 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
600 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
601}
602
Eric Liub9bf1b52016-11-08 22:44:17 +0000603// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
604// FromDecl with the shortest qualified name possible when the reference is in
605// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32 +0000606void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17 +0000607 const ast_matchers::MatchFinder::MatchResult &Result,
608 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
609 const NamedDecl *FromDecl) {
610 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu231c6552016-11-10 18:15:34 +0000611 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32 +0000612 // Calculate the name of the `NsDecl` after it is moved to new namespace.
613 std::string OldNs = NsDecl->getQualifiedNameAsString();
614 llvm::StringRef Postfix = OldNs;
615 bool Consumed = Postfix.consume_front(OldNamespace);
616 assert(Consumed && "Expect OldNS to start with OldNamespace.");
617 (void)Consumed;
618 const std::string NewNs = (NewNamespace + Postfix).str();
619
620 llvm::StringRef NestedName = Lexer::getSourceText(
621 CharSourceRange::getTokenRange(
622 Result.SourceManager->getSpellingLoc(Start),
623 Result.SourceManager->getSpellingLoc(End)),
624 *Result.SourceManager, Result.Context->getLangOpts());
625 // If the symbol is already fully qualified, no change needs to be make.
626 if (NestedName.startswith("::"))
627 return;
Eric Liub9bf1b52016-11-08 22:44:17 +0000628 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu495b2112016-09-19 17:40:32 +0000629 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17 +0000630 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
631 // Checks if there is any using namespace declarations that can shorten the
632 // qualified name.
633 for (const auto *UsingNamespace : UsingNamespaceDecls) {
634 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
635 Start))
636 continue;
637 StringRef FromDeclNameRef = FromDeclName;
638 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
639 ->getQualifiedNameAsString())) {
640 FromDeclNameRef = FromDeclNameRef.drop_front(2);
641 if (FromDeclNameRef.size() < ReplaceName.size())
642 ReplaceName = FromDeclNameRef;
643 }
644 }
645 // Checks if there is any using shadow declarations that can shorten the
646 // qualified name.
647 bool Matched = false;
648 for (const UsingDecl *Using : UsingDecls) {
649 if (Matched)
650 break;
651 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
652 for (const auto *UsingShadow : Using->shadows()) {
653 const auto *TargetDecl = UsingShadow->getTargetDecl();
654 if (TargetDecl == FromDecl) {
655 ReplaceName = FromDecl->getNameAsString();
656 Matched = true;
657 break;
658 }
659 }
660 }
661 }
Eric Liu495b2112016-09-19 17:40:32 +0000662 // If the new nested name in the new namespace is the same as it was in the
663 // old namespace, we don't create replacement.
664 if (NestedName == ReplaceName)
665 return;
Eric Liu97f87ad2016-12-07 20:08:02 +0000666 // If the reference need to be fully-qualified, add a leading "::" unless
667 // NewNamespace is the global namespace.
668 if (ReplaceName == FromDeclName && !NewNamespace.empty())
669 ReplaceName = "::" + ReplaceName;
Eric Liu495b2112016-09-19 17:40:32 +0000670 auto R = createReplacement(Start, End, ReplaceName, *Result.SourceManager);
Eric Liuff51f012016-11-16 16:54:53 +0000671 auto Err = FileToReplacements[R.getFilePath()].add(R);
672 if (Err)
673 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
Eric Liu495b2112016-09-19 17:40:32 +0000674}
675
676// Replace the [Start, End] of `Type` with the shortest qualified name when the
677// `Type` is in `NewNamespace`.
678void ChangeNamespaceTool::fixTypeLoc(
679 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
680 SourceLocation End, TypeLoc Type) {
681 // FIXME: do not rename template parameter.
682 if (Start.isInvalid() || End.isInvalid())
683 return;
Eric Liuff51f012016-11-16 16:54:53 +0000684 // Types of CXXCtorInitializers do not need to be fixed.
685 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
686 return;
Eric Liu495b2112016-09-19 17:40:32 +0000687 // The declaration which this TypeLoc refers to.
688 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
689 // `hasDeclaration` gives underlying declaration, but if the type is
690 // a typedef type, we need to use the typedef type instead.
Eric Liu32158862016-11-14 19:37:55 +0000691 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32 +0000692 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55 +0000693 auto IsInMovedNs = [&](const NamedDecl *D) {
694 if (!llvm::StringRef(D->getQualifiedNameAsString())
695 .startswith(OldNamespace + "::"))
696 return false;
697 auto ExpansionLoc =
698 Result.SourceManager->getExpansionLoc(D->getLocStart());
699 if (ExpansionLoc.isInvalid())
700 return false;
701 llvm::StringRef Filename =
702 Result.SourceManager->getFilename(ExpansionLoc);
Eric Liuc265b022016-12-01 17:25:55 +0000703 return FilePatternRE.match(Filename);
Eric Liu32158862016-11-14 19:37:55 +0000704 };
705 // Don't fix the \p Type if it refers to a type alias decl in the moved
706 // namespace since the alias decl will be moved along with the type
707 // reference.
708 if (IsInMovedNs(FromDecl))
709 return;
710 }
Eric Liu495b2112016-09-19 17:40:32 +0000711
Piotr Padlewski08124b12016-12-14 15:29:23 +0000712 const auto *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
Eric Liu495b2112016-09-19 17:40:32 +0000713 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17 +0000714 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
715 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32 +0000716}
717
Eric Liu68765a82016-09-21 15:06:12 +0000718void ChangeNamespaceTool::fixUsingShadowDecl(
719 const ast_matchers::MatchFinder::MatchResult &Result,
720 const UsingDecl *UsingDeclaration) {
721 SourceLocation Start = UsingDeclaration->getLocStart();
722 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000723 if (Start.isInvalid() || End.isInvalid())
724 return;
Eric Liu68765a82016-09-21 15:06:12 +0000725
726 assert(UsingDeclaration->shadow_size() > 0);
727 // FIXME: it might not be always accurate to use the first using-decl.
728 const NamedDecl *TargetDecl =
729 UsingDeclaration->shadow_begin()->getTargetDecl();
730 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
731 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
732 // sense. If this happens, we need to use name with the new namespace.
733 // Use fully qualified name in UsingDecl for now.
734 auto R = createReplacement(Start, End, "using ::" + TargetDeclName,
735 *Result.SourceManager);
Eric Liuff51f012016-11-16 16:54:53 +0000736 auto Err = FileToReplacements[R.getFilePath()].add(R);
737 if (Err)
738 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
Eric Liu68765a82016-09-21 15:06:12 +0000739}
740
Eric Liuda22b3c2016-11-29 14:15:14 +0000741void ChangeNamespaceTool::fixDeclRefExpr(
742 const ast_matchers::MatchFinder::MatchResult &Result,
743 const DeclContext *UseContext, const NamedDecl *From,
744 const DeclRefExpr *Ref) {
745 SourceRange RefRange = Ref->getSourceRange();
746 replaceQualifiedSymbolInDeclContext(Result, UseContext, RefRange.getBegin(),
747 RefRange.getEnd(), From);
748}
749
Eric Liu495b2112016-09-19 17:40:32 +0000750void ChangeNamespaceTool::onEndOfTranslationUnit() {
751 // Move namespace blocks and insert forward declaration to old namespace.
752 for (const auto &FileAndNsMoves : MoveNamespaces) {
753 auto &NsMoves = FileAndNsMoves.second;
754 if (NsMoves.empty())
755 continue;
756 const std::string &FilePath = FileAndNsMoves.first;
757 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59 +0000758 auto &SM = *NsMoves.begin()->SourceMgr;
759 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32 +0000760 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
761 if (!ChangedCode) {
762 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
763 continue;
764 }
765 // Replacements on the changed code for moving namespaces and inserting
766 // forward declarations to old namespaces.
767 tooling::Replacements NewReplacements;
768 // Cut the changed code from the old namespace and paste the code in the new
769 // namespace.
770 for (const auto &NsMove : NsMoves) {
771 // Calculate the range of the old namespace block in the changed
772 // code.
773 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
774 const unsigned NewLength =
775 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
776 NewOffset;
777 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
778 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
779 std::string MovedCodeWrappedInNewNs =
780 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
781 // Calculate the new offset at which the code will be inserted in the
782 // changed code.
783 unsigned NewInsertionOffset =
784 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
785 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
786 MovedCodeWrappedInNewNs);
787 addOrMergeReplacement(Deletion, &NewReplacements);
788 addOrMergeReplacement(Insertion, &NewReplacements);
789 }
790 // After moving namespaces, insert forward declarations back to old
791 // namespaces.
792 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
793 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
794 unsigned NewInsertionOffset =
795 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
796 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
797 FwdDeclInsertion.ForwardDeclText);
798 addOrMergeReplacement(Insertion, &NewReplacements);
799 }
800 // Add replacements referring to the changed code to existing replacements,
801 // which refers to the original code.
802 Replaces = Replaces.merge(NewReplacements);
803 format::FormatStyle Style =
804 format::getStyle("file", FilePath, FallbackStyle);
805 // Clean up old namespaces if there is nothing in it after moving.
806 auto CleanReplacements =
807 format::cleanupAroundReplacements(Code, Replaces, Style);
808 if (!CleanReplacements) {
809 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
810 continue;
811 }
812 FileToReplacements[FilePath] = *CleanReplacements;
813 }
Eric Liuc265b022016-12-01 17:25:55 +0000814
815 // Make sure we don't generate replacements for files that do not match
816 // FilePattern.
817 for (auto &Entry : FileToReplacements)
818 if (!FilePatternRE.match(Entry.first))
819 Entry.second.clear();
Eric Liu495b2112016-09-19 17:40:32 +0000820}
821
822} // namespace change_namespace
823} // namespace clang