blob: fbbde4397cc8d92ebf3ad81ea194cec2c17d503b [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
44SourceLocation EndLocationForType(TypeLoc TLoc) {
45 // 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;
213 NestedNs.split(NsSplitted, "::");
214 while (!NsSplitted.empty()) {
215 // FIXME: consider code style for comments.
216 Code = ("namespace " + NsSplitted.back() + " {\n" + Code +
217 "} // namespace " + NsSplitted.back() + "\n")
218 .str();
219 NsSplitted.pop_back();
220 }
221 return Code;
222}
223
Eric Liub9bf1b52016-11-08 22:44:17 +0000224// Returns true if \p D is a nested DeclContext in \p Context
225bool isNestedDeclContext(const DeclContext *D, const DeclContext *Context) {
226 while (D) {
227 if (D == Context)
228 return true;
229 D = D->getParent();
230 }
231 return false;
232}
233
234// Returns true if \p D is visible at \p Loc with DeclContext \p DeclCtx.
235bool isDeclVisibleAtLocation(const SourceManager &SM, const Decl *D,
236 const DeclContext *DeclCtx, SourceLocation Loc) {
237 SourceLocation DeclLoc = SM.getSpellingLoc(D->getLocation());
238 Loc = SM.getSpellingLoc(Loc);
239 return SM.isBeforeInTranslationUnit(DeclLoc, Loc) &&
240 (SM.getFileID(DeclLoc) == SM.getFileID(Loc) &&
241 isNestedDeclContext(DeclCtx, D->getDeclContext()));
242}
243
Eric Liu495b2112016-09-19 17:40:32 +0000244} // anonymous namespace
245
246ChangeNamespaceTool::ChangeNamespaceTool(
247 llvm::StringRef OldNs, llvm::StringRef NewNs, llvm::StringRef FilePattern,
248 std::map<std::string, tooling::Replacements> *FileToReplacements,
249 llvm::StringRef FallbackStyle)
250 : FallbackStyle(FallbackStyle), FileToReplacements(*FileToReplacements),
251 OldNamespace(OldNs.ltrim(':')), NewNamespace(NewNs.ltrim(':')),
252 FilePattern(FilePattern) {
253 FileToReplacements->clear();
254 llvm::SmallVector<llvm::StringRef, 4> OldNsSplitted;
255 llvm::SmallVector<llvm::StringRef, 4> NewNsSplitted;
256 llvm::StringRef(OldNamespace).split(OldNsSplitted, "::");
257 llvm::StringRef(NewNamespace).split(NewNsSplitted, "::");
258 // Calculates `DiffOldNamespace` and `DiffNewNamespace`.
259 while (!OldNsSplitted.empty() && !NewNsSplitted.empty() &&
260 OldNsSplitted.front() == NewNsSplitted.front()) {
261 OldNsSplitted.erase(OldNsSplitted.begin());
262 NewNsSplitted.erase(NewNsSplitted.begin());
263 }
264 DiffOldNamespace = joinNamespaces(OldNsSplitted);
265 DiffNewNamespace = joinNamespaces(NewNsSplitted);
266}
267
Eric Liu495b2112016-09-19 17:40:32 +0000268void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Eric Liu495b2112016-09-19 17:40:32 +0000269 std::string FullOldNs = "::" + OldNamespace;
Eric Liub9bf1b52016-11-08 22:44:17 +0000270 // Prefix is the outer-most namespace in DiffOldNamespace. For example, if the
271 // OldNamespace is "a::b::c" and DiffOldNamespace is "b::c", then Prefix will
272 // be "a::b". Declarations in this namespace will not be visible in the new
273 // namespace. If DiffOldNamespace is empty, Prefix will be a invalid name "-".
274 llvm::SmallVector<llvm::StringRef, 4> DiffOldNsSplitted;
275 llvm::StringRef(DiffOldNamespace).split(DiffOldNsSplitted, "::");
276 std::string Prefix = "-";
277 if (!DiffOldNsSplitted.empty())
278 Prefix = (StringRef(FullOldNs).drop_back(DiffOldNamespace.size()) +
279 DiffOldNsSplitted.front())
280 .str();
281 auto IsInMovedNs =
282 allOf(hasAncestor(namespaceDecl(hasName(FullOldNs)).bind("ns_decl")),
283 isExpansionInFileMatching(FilePattern));
284 auto IsVisibleInNewNs = anyOf(
285 IsInMovedNs, unless(hasAncestor(namespaceDecl(hasName(Prefix)))));
286 // Match using declarations.
287 Finder->addMatcher(
288 usingDecl(isExpansionInFileMatching(FilePattern), IsVisibleInNewNs)
289 .bind("using"),
290 this);
291 // Match using namespace declarations.
292 Finder->addMatcher(usingDirectiveDecl(isExpansionInFileMatching(FilePattern),
293 IsVisibleInNewNs)
294 .bind("using_namespace"),
295 this);
296
297 // Match old namespace blocks.
Eric Liu495b2112016-09-19 17:40:32 +0000298 Finder->addMatcher(
299 namespaceDecl(hasName(FullOldNs), isExpansionInFileMatching(FilePattern))
300 .bind("old_ns"),
301 this);
302
Eric Liu495b2112016-09-19 17:40:32 +0000303 // Match forward-declarations in the old namespace.
304 Finder->addMatcher(
305 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), IsInMovedNs)
306 .bind("fwd_decl"),
307 this);
308
309 // Match references to types that are not defined in the old namespace.
310 // Forward-declarations in the old namespace are also matched since they will
311 // be moved back to the old namespace.
312 auto DeclMatcher = namedDecl(
313 hasAncestor(namespaceDecl()),
314 unless(anyOf(
Eric Liu912d0392016-09-27 12:54:48 +0000315 isImplicit(), hasAncestor(namespaceDecl(isAnonymous())),
Eric Liu495b2112016-09-19 17:40:32 +0000316 hasAncestor(cxxRecordDecl()),
317 allOf(IsInMovedNs, unless(cxxRecordDecl(unless(isDefinition())))))));
Eric Liu912d0392016-09-27 12:54:48 +0000318
Eric Liu495b2112016-09-19 17:40:32 +0000319 // Match TypeLocs on the declaration. Carefully match only the outermost
Eric Liu8393cb02016-10-31 08:28:29 +0000320 // TypeLoc and template specialization arguments (which are not outermost)
321 // that are directly linked to types matching `DeclMatcher`. Nested name
322 // specifier locs are handled separately below.
Eric Liu495b2112016-09-19 17:40:32 +0000323 Finder->addMatcher(
324 typeLoc(IsInMovedNs,
325 loc(qualType(hasDeclaration(DeclMatcher.bind("from_decl")))),
Eric Liu8393cb02016-10-31 08:28:29 +0000326 unless(anyOf(hasParent(typeLoc(loc(qualType(
327 allOf(hasDeclaration(DeclMatcher),
328 unless(templateSpecializationType())))))),
Eric Liu495b2112016-09-19 17:40:32 +0000329 hasParent(nestedNameSpecifierLoc()))),
330 hasAncestor(decl().bind("dc")))
331 .bind("type"),
332 this);
Eric Liu912d0392016-09-27 12:54:48 +0000333
Eric Liu68765a82016-09-21 15:06:12 +0000334 // Types in `UsingShadowDecl` is not matched by `typeLoc` above, so we need to
335 // special case it.
Eric Liub9bf1b52016-11-08 22:44:17 +0000336 Finder->addMatcher(usingDecl(IsInMovedNs, hasAnyUsingShadowDecl(decl()))
337 .bind("using_with_shadow"),
338 this);
Eric Liu912d0392016-09-27 12:54:48 +0000339
Eric Liuff51f012016-11-16 16:54:53 +0000340 // Handle types in nested name specifier. Specifiers that are in a TypeLoc
341 // matched above are not matched, e.g. "A::" in "A::A" is not matched since
342 // "A::A" would have already been fixed.
Eric Liu68765a82016-09-21 15:06:12 +0000343 Finder->addMatcher(nestedNameSpecifierLoc(
344 hasAncestor(decl(IsInMovedNs).bind("dc")),
345 loc(nestedNameSpecifier(specifiesType(
Eric Liuff51f012016-11-16 16:54:53 +0000346 hasDeclaration(DeclMatcher.bind("from_decl"))))),
347 unless(hasAncestor(typeLoc(loc(qualType(hasDeclaration(
348 decl(equalsBoundNode("from_decl")))))))))
Eric Liu68765a82016-09-21 15:06:12 +0000349 .bind("nested_specifier_loc"),
350 this);
Eric Liu12068d82016-09-22 11:54:00 +0000351
Eric Liuff51f012016-11-16 16:54:53 +0000352 // Matches base class initializers in constructors. TypeLocs of base class
353 // initializers do not need to be fixed. For example,
354 // class X : public a::b::Y {
355 // public:
356 // X() : Y::Y() {} // Y::Y do not need namespace specifier.
357 // };
358 Finder->addMatcher(
359 cxxCtorInitializer(isBaseInitializer()).bind("base_initializer"), this);
360
Eric Liu12068d82016-09-22 11:54:00 +0000361 // Handle function.
Eric Liu912d0392016-09-27 12:54:48 +0000362 // Only handle functions that are defined in a namespace excluding member
363 // function, static methods (qualified by nested specifier), and functions
364 // defined in the global namespace.
Eric Liu12068d82016-09-22 11:54:00 +0000365 // Note that the matcher does not exclude calls to out-of-line static method
366 // definitions, so we need to exclude them in the callback handler.
Eric Liu912d0392016-09-27 12:54:48 +0000367 auto FuncMatcher =
368 functionDecl(unless(anyOf(cxxMethodDecl(), IsInMovedNs,
369 hasAncestor(namespaceDecl(isAnonymous())),
370 hasAncestor(cxxRecordDecl()))),
371 hasParent(namespaceDecl()));
Eric Liu12068d82016-09-22 11:54:00 +0000372 Finder->addMatcher(
373 decl(forEachDescendant(callExpr(callee(FuncMatcher)).bind("call")),
Eric Liu912d0392016-09-27 12:54:48 +0000374 IsInMovedNs, unless(isImplicit()))
Eric Liu12068d82016-09-22 11:54:00 +0000375 .bind("dc"),
376 this);
Eric Liu159f0132016-09-30 04:32:39 +0000377
378 auto GlobalVarMatcher = varDecl(
379 hasGlobalStorage(), hasParent(namespaceDecl()),
380 unless(anyOf(IsInMovedNs, hasAncestor(namespaceDecl(isAnonymous())))));
381 Finder->addMatcher(declRefExpr(IsInMovedNs, hasAncestor(decl().bind("dc")),
382 to(GlobalVarMatcher.bind("var_decl")))
383 .bind("var_ref"),
384 this);
Eric Liu495b2112016-09-19 17:40:32 +0000385}
386
387void ChangeNamespaceTool::run(
388 const ast_matchers::MatchFinder::MatchResult &Result) {
Eric Liub9bf1b52016-11-08 22:44:17 +0000389 if (const auto *Using = Result.Nodes.getNodeAs<UsingDecl>("using")) {
390 UsingDecls.insert(Using);
391 } else if (const auto *UsingNamespace =
392 Result.Nodes.getNodeAs<UsingDirectiveDecl>(
393 "using_namespace")) {
394 UsingNamespaceDecls.insert(UsingNamespace);
395 } else if (const auto *NsDecl =
396 Result.Nodes.getNodeAs<NamespaceDecl>("old_ns")) {
Eric Liu495b2112016-09-19 17:40:32 +0000397 moveOldNamespace(Result, NsDecl);
398 } else if (const auto *FwdDecl =
399 Result.Nodes.getNodeAs<CXXRecordDecl>("fwd_decl")) {
400 moveClassForwardDeclaration(Result, FwdDecl);
Eric Liub9bf1b52016-11-08 22:44:17 +0000401 } else if (const auto *UsingWithShadow =
402 Result.Nodes.getNodeAs<UsingDecl>("using_with_shadow")) {
403 fixUsingShadowDecl(Result, UsingWithShadow);
Eric Liu68765a82016-09-21 15:06:12 +0000404 } else if (const auto *Specifier =
405 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>(
406 "nested_specifier_loc")) {
407 SourceLocation Start = Specifier->getBeginLoc();
408 SourceLocation End = EndLocationForType(Specifier->getTypeLoc());
409 fixTypeLoc(Result, Start, End, Specifier->getTypeLoc());
Eric Liuff51f012016-11-16 16:54:53 +0000410 } else if (const auto *BaseInitializer =
411 Result.Nodes.getNodeAs<CXXCtorInitializer>(
412 "base_initializer")) {
413 BaseCtorInitializerTypeLocs.push_back(
414 BaseInitializer->getTypeSourceInfo()->getTypeLoc());
Eric Liu12068d82016-09-22 11:54:00 +0000415 } else if (const auto *TLoc = Result.Nodes.getNodeAs<TypeLoc>("type")) {
Eric Liu495b2112016-09-19 17:40:32 +0000416 fixTypeLoc(Result, startLocationForType(*TLoc), EndLocationForType(*TLoc),
417 *TLoc);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000418 } else if (const auto *VarRef =
419 Result.Nodes.getNodeAs<DeclRefExpr>("var_ref")) {
Eric Liu159f0132016-09-30 04:32:39 +0000420 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var_decl");
421 assert(Var);
422 if (Var->getCanonicalDecl()->isStaticDataMember())
423 return;
Eric Liu159f0132016-09-30 04:32:39 +0000424 const clang::Decl *Context = Result.Nodes.getNodeAs<clang::Decl>("dc");
425 assert(Context && "Empty decl context.");
426 clang::SourceRange VarRefRange = VarRef->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17 +0000427 replaceQualifiedSymbolInDeclContext(
428 Result, Context->getDeclContext(), VarRefRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34 +0000429 VarRefRange.getEnd(), llvm::cast<NamedDecl>(Var));
Eric Liu12068d82016-09-22 11:54:00 +0000430 } else {
Eric Liu159f0132016-09-30 04:32:39 +0000431 const auto *Call = Result.Nodes.getNodeAs<clang::CallExpr>("call");
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000432 assert(Call != nullptr && "Expecting callback for CallExpr.");
433 const clang::FunctionDecl *Func = Call->getDirectCallee();
Eric Liu12068d82016-09-22 11:54:00 +0000434 assert(Func != nullptr);
435 // Ignore out-of-line static methods since they will be handled by nested
436 // name specifiers.
437 if (Func->getCanonicalDecl()->getStorageClass() ==
438 clang::StorageClass::SC_Static &&
439 Func->isOutOfLine())
440 return;
Eric Liu12068d82016-09-22 11:54:00 +0000441 const clang::Decl *Context = Result.Nodes.getNodeAs<clang::Decl>("dc");
442 assert(Context && "Empty decl context.");
443 clang::SourceRange CalleeRange = Call->getCallee()->getSourceRange();
Eric Liub9bf1b52016-11-08 22:44:17 +0000444 replaceQualifiedSymbolInDeclContext(
445 Result, Context->getDeclContext(), CalleeRange.getBegin(),
Eric Liu231c6552016-11-10 18:15:34 +0000446 CalleeRange.getEnd(), llvm::cast<NamedDecl>(Func));
Eric Liu495b2112016-09-19 17:40:32 +0000447 }
448}
449
Eric Liu73f49fd2016-10-12 12:34:18 +0000450static SourceLocation getLocAfterNamespaceLBrace(const NamespaceDecl *NsDecl,
451 const SourceManager &SM,
452 const LangOptions &LangOpts) {
453 std::unique_ptr<Lexer> Lex =
454 getLexerStartingFromLoc(NsDecl->getLocStart(), SM, LangOpts);
455 assert(Lex.get() &&
456 "Failed to create lexer from the beginning of namespace.");
457 if (!Lex.get())
458 return SourceLocation();
459 Token Tok;
460 while (!Lex->LexFromRawLexer(Tok) && Tok.isNot(tok::TokenKind::l_brace)) {
461 }
462 return Tok.isNot(tok::TokenKind::l_brace)
463 ? SourceLocation()
464 : Tok.getEndLoc().getLocWithOffset(1);
465}
466
Eric Liu495b2112016-09-19 17:40:32 +0000467// Stores information about a moved namespace in `MoveNamespaces` and leaves
468// the actual movement to `onEndOfTranslationUnit()`.
469void ChangeNamespaceTool::moveOldNamespace(
470 const ast_matchers::MatchFinder::MatchResult &Result,
471 const NamespaceDecl *NsDecl) {
472 // If the namespace is empty, do nothing.
473 if (Decl::castToDeclContext(NsDecl)->decls_empty())
474 return;
475
476 // Get the range of the code in the old namespace.
Eric Liu73f49fd2016-10-12 12:34:18 +0000477 SourceLocation Start = getLocAfterNamespaceLBrace(
478 NsDecl, *Result.SourceManager, Result.Context->getLangOpts());
479 assert(Start.isValid() && "Can't find l_brace for namespace.");
Eric Liu495b2112016-09-19 17:40:32 +0000480 SourceLocation End = NsDecl->getRBraceLoc().getLocWithOffset(-1);
481 // Create a replacement that deletes the code in the old namespace merely for
482 // retrieving offset and length from it.
483 const auto R = createReplacement(Start, End, "", *Result.SourceManager);
484 MoveNamespace MoveNs;
485 MoveNs.Offset = R.getOffset();
486 MoveNs.Length = R.getLength();
487
488 // Insert the new namespace after `DiffOldNamespace`. For example, if
489 // `OldNamespace` is "a::b::c" and `NewNamespace` is `a::x::y`, then
490 // "x::y" will be inserted inside the existing namespace "a" and after "a::b".
491 // `OuterNs` is the first namespace in `DiffOldNamespace`, e.g. "namespace b"
492 // in the above example.
Eric Liu6aa94162016-11-10 18:29:01 +0000493 // If there is no outer namespace (i.e. DiffOldNamespace is empty), the new
494 // namespace will be a nested namespace in the old namespace.
Eric Liu495b2112016-09-19 17:40:32 +0000495 const NamespaceDecl *OuterNs = getOuterNamespace(NsDecl, DiffOldNamespace);
Eric Liu6aa94162016-11-10 18:29:01 +0000496 SourceLocation InsertionLoc = Start;
497 if (OuterNs) {
498 SourceLocation LocAfterNs =
499 getStartOfNextLine(OuterNs->getRBraceLoc(), *Result.SourceManager,
500 Result.Context->getLangOpts());
501 assert(LocAfterNs.isValid() &&
502 "Failed to get location after DiffOldNamespace");
503 InsertionLoc = LocAfterNs;
504 }
Eric Liu495b2112016-09-19 17:40:32 +0000505 MoveNs.InsertionOffset = Result.SourceManager->getFileOffset(
Eric Liu6aa94162016-11-10 18:29:01 +0000506 Result.SourceManager->getSpellingLoc(InsertionLoc));
Eric Liucc83c662016-09-19 17:58:59 +0000507 MoveNs.FID = Result.SourceManager->getFileID(Start);
508 MoveNs.SourceMgr = Result.SourceManager;
Eric Liu495b2112016-09-19 17:40:32 +0000509 MoveNamespaces[R.getFilePath()].push_back(MoveNs);
510}
511
512// Removes a class forward declaration from the code in the moved namespace and
513// creates an `InsertForwardDeclaration` to insert the forward declaration back
514// into the old namespace after moving code from the old namespace to the new
515// namespace.
516// For example, changing "a" to "x":
517// Old code:
518// namespace a {
519// class FWD;
520// class A { FWD *fwd; }
521// } // a
522// New code:
523// namespace a {
524// class FWD;
525// } // a
526// namespace x {
527// class A { a::FWD *fwd; }
528// } // x
529void ChangeNamespaceTool::moveClassForwardDeclaration(
530 const ast_matchers::MatchFinder::MatchResult &Result,
531 const CXXRecordDecl *FwdDecl) {
532 SourceLocation Start = FwdDecl->getLocStart();
533 SourceLocation End = FwdDecl->getLocEnd();
534 SourceLocation AfterSemi = Lexer::findLocationAfterToken(
535 End, tok::semi, *Result.SourceManager, Result.Context->getLangOpts(),
536 /*SkipTrailingWhitespaceAndNewLine=*/true);
537 if (AfterSemi.isValid())
538 End = AfterSemi.getLocWithOffset(-1);
539 // Delete the forward declaration from the code to be moved.
540 const auto Deletion =
541 createReplacement(Start, End, "", *Result.SourceManager);
Eric Liuff51f012016-11-16 16:54:53 +0000542 auto Err = FileToReplacements[Deletion.getFilePath()].add(Deletion);
543 if (Err)
544 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
Eric Liu495b2112016-09-19 17:40:32 +0000545 llvm::StringRef Code = Lexer::getSourceText(
546 CharSourceRange::getTokenRange(
547 Result.SourceManager->getSpellingLoc(Start),
548 Result.SourceManager->getSpellingLoc(End)),
549 *Result.SourceManager, Result.Context->getLangOpts());
550 // Insert the forward declaration back into the old namespace after moving the
551 // code from old namespace to new namespace.
552 // Insertion information is stored in `InsertFwdDecls` and actual
553 // insertion will be performed in `onEndOfTranslationUnit`.
554 // Get the (old) namespace that contains the forward declaration.
555 const auto *NsDecl = Result.Nodes.getNodeAs<NamespaceDecl>("ns_decl");
556 // The namespace contains the forward declaration, so it must not be empty.
557 assert(!NsDecl->decls_empty());
558 const auto Insertion = createInsertion(NsDecl->decls_begin()->getLocStart(),
559 Code, *Result.SourceManager);
560 InsertForwardDeclaration InsertFwd;
561 InsertFwd.InsertionOffset = Insertion.getOffset();
562 InsertFwd.ForwardDeclText = Insertion.getReplacementText().str();
563 InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd);
564}
565
Eric Liub9bf1b52016-11-08 22:44:17 +0000566// Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p
567// FromDecl with the shortest qualified name possible when the reference is in
568// `NewNamespace`.
Eric Liu495b2112016-09-19 17:40:32 +0000569void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
Eric Liub9bf1b52016-11-08 22:44:17 +0000570 const ast_matchers::MatchFinder::MatchResult &Result,
571 const DeclContext *DeclCtx, SourceLocation Start, SourceLocation End,
572 const NamedDecl *FromDecl) {
573 const auto *NsDeclContext = DeclCtx->getEnclosingNamespaceContext();
Eric Liu231c6552016-11-10 18:15:34 +0000574 const auto *NsDecl = llvm::cast<NamespaceDecl>(NsDeclContext);
Eric Liu495b2112016-09-19 17:40:32 +0000575 // Calculate the name of the `NsDecl` after it is moved to new namespace.
576 std::string OldNs = NsDecl->getQualifiedNameAsString();
577 llvm::StringRef Postfix = OldNs;
578 bool Consumed = Postfix.consume_front(OldNamespace);
579 assert(Consumed && "Expect OldNS to start with OldNamespace.");
580 (void)Consumed;
581 const std::string NewNs = (NewNamespace + Postfix).str();
582
583 llvm::StringRef NestedName = Lexer::getSourceText(
584 CharSourceRange::getTokenRange(
585 Result.SourceManager->getSpellingLoc(Start),
586 Result.SourceManager->getSpellingLoc(End)),
587 *Result.SourceManager, Result.Context->getLangOpts());
588 // If the symbol is already fully qualified, no change needs to be make.
589 if (NestedName.startswith("::"))
590 return;
Eric Liub9bf1b52016-11-08 22:44:17 +0000591 std::string FromDeclName = FromDecl->getQualifiedNameAsString();
Eric Liu495b2112016-09-19 17:40:32 +0000592 std::string ReplaceName =
Eric Liub9bf1b52016-11-08 22:44:17 +0000593 getShortestQualifiedNameInNamespace(FromDeclName, NewNs);
594 // Checks if there is any using namespace declarations that can shorten the
595 // qualified name.
596 for (const auto *UsingNamespace : UsingNamespaceDecls) {
597 if (!isDeclVisibleAtLocation(*Result.SourceManager, UsingNamespace, DeclCtx,
598 Start))
599 continue;
600 StringRef FromDeclNameRef = FromDeclName;
601 if (FromDeclNameRef.consume_front(UsingNamespace->getNominatedNamespace()
602 ->getQualifiedNameAsString())) {
603 FromDeclNameRef = FromDeclNameRef.drop_front(2);
604 if (FromDeclNameRef.size() < ReplaceName.size())
605 ReplaceName = FromDeclNameRef;
606 }
607 }
608 // Checks if there is any using shadow declarations that can shorten the
609 // qualified name.
610 bool Matched = false;
611 for (const UsingDecl *Using : UsingDecls) {
612 if (Matched)
613 break;
614 if (isDeclVisibleAtLocation(*Result.SourceManager, Using, DeclCtx, Start)) {
615 for (const auto *UsingShadow : Using->shadows()) {
616 const auto *TargetDecl = UsingShadow->getTargetDecl();
617 if (TargetDecl == FromDecl) {
618 ReplaceName = FromDecl->getNameAsString();
619 Matched = true;
620 break;
621 }
622 }
623 }
624 }
Eric Liu495b2112016-09-19 17:40:32 +0000625 // If the new nested name in the new namespace is the same as it was in the
626 // old namespace, we don't create replacement.
627 if (NestedName == ReplaceName)
628 return;
629 auto R = createReplacement(Start, End, ReplaceName, *Result.SourceManager);
Eric Liuff51f012016-11-16 16:54:53 +0000630 auto Err = FileToReplacements[R.getFilePath()].add(R);
631 if (Err)
632 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
Eric Liu495b2112016-09-19 17:40:32 +0000633}
634
635// Replace the [Start, End] of `Type` with the shortest qualified name when the
636// `Type` is in `NewNamespace`.
637void ChangeNamespaceTool::fixTypeLoc(
638 const ast_matchers::MatchFinder::MatchResult &Result, SourceLocation Start,
639 SourceLocation End, TypeLoc Type) {
640 // FIXME: do not rename template parameter.
641 if (Start.isInvalid() || End.isInvalid())
642 return;
Eric Liuff51f012016-11-16 16:54:53 +0000643 // Types of CXXCtorInitializers do not need to be fixed.
644 if (llvm::is_contained(BaseCtorInitializerTypeLocs, Type))
645 return;
Eric Liu495b2112016-09-19 17:40:32 +0000646 // The declaration which this TypeLoc refers to.
647 const auto *FromDecl = Result.Nodes.getNodeAs<NamedDecl>("from_decl");
648 // `hasDeclaration` gives underlying declaration, but if the type is
649 // a typedef type, we need to use the typedef type instead.
Eric Liu32158862016-11-14 19:37:55 +0000650 if (auto *Typedef = Type.getType()->getAs<TypedefType>()) {
Eric Liu495b2112016-09-19 17:40:32 +0000651 FromDecl = Typedef->getDecl();
Eric Liu32158862016-11-14 19:37:55 +0000652 auto IsInMovedNs = [&](const NamedDecl *D) {
653 if (!llvm::StringRef(D->getQualifiedNameAsString())
654 .startswith(OldNamespace + "::"))
655 return false;
656 auto ExpansionLoc =
657 Result.SourceManager->getExpansionLoc(D->getLocStart());
658 if (ExpansionLoc.isInvalid())
659 return false;
660 llvm::StringRef Filename =
661 Result.SourceManager->getFilename(ExpansionLoc);
662 llvm::Regex RE(FilePattern);
663 return RE.match(Filename);
664 };
665 // Don't fix the \p Type if it refers to a type alias decl in the moved
666 // namespace since the alias decl will be moved along with the type
667 // reference.
668 if (IsInMovedNs(FromDecl))
669 return;
670 }
Eric Liu495b2112016-09-19 17:40:32 +0000671
672 const Decl *DeclCtx = Result.Nodes.getNodeAs<Decl>("dc");
673 assert(DeclCtx && "Empty decl context.");
Eric Liub9bf1b52016-11-08 22:44:17 +0000674 replaceQualifiedSymbolInDeclContext(Result, DeclCtx->getDeclContext(), Start,
675 End, FromDecl);
Eric Liu495b2112016-09-19 17:40:32 +0000676}
677
Eric Liu68765a82016-09-21 15:06:12 +0000678void ChangeNamespaceTool::fixUsingShadowDecl(
679 const ast_matchers::MatchFinder::MatchResult &Result,
680 const UsingDecl *UsingDeclaration) {
681 SourceLocation Start = UsingDeclaration->getLocStart();
682 SourceLocation End = UsingDeclaration->getLocEnd();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000683 if (Start.isInvalid() || End.isInvalid())
684 return;
Eric Liu68765a82016-09-21 15:06:12 +0000685
686 assert(UsingDeclaration->shadow_size() > 0);
687 // FIXME: it might not be always accurate to use the first using-decl.
688 const NamedDecl *TargetDecl =
689 UsingDeclaration->shadow_begin()->getTargetDecl();
690 std::string TargetDeclName = TargetDecl->getQualifiedNameAsString();
691 // FIXME: check if target_decl_name is in moved ns, which doesn't make much
692 // sense. If this happens, we need to use name with the new namespace.
693 // Use fully qualified name in UsingDecl for now.
694 auto R = createReplacement(Start, End, "using ::" + TargetDeclName,
695 *Result.SourceManager);
Eric Liuff51f012016-11-16 16:54:53 +0000696 auto Err = FileToReplacements[R.getFilePath()].add(R);
697 if (Err)
698 llvm_unreachable(llvm::toString(std::move(Err)).c_str());
Eric Liu68765a82016-09-21 15:06:12 +0000699}
700
Eric Liu495b2112016-09-19 17:40:32 +0000701void ChangeNamespaceTool::onEndOfTranslationUnit() {
702 // Move namespace blocks and insert forward declaration to old namespace.
703 for (const auto &FileAndNsMoves : MoveNamespaces) {
704 auto &NsMoves = FileAndNsMoves.second;
705 if (NsMoves.empty())
706 continue;
707 const std::string &FilePath = FileAndNsMoves.first;
708 auto &Replaces = FileToReplacements[FilePath];
Eric Liucc83c662016-09-19 17:58:59 +0000709 auto &SM = *NsMoves.begin()->SourceMgr;
710 llvm::StringRef Code = SM.getBufferData(NsMoves.begin()->FID);
Eric Liu495b2112016-09-19 17:40:32 +0000711 auto ChangedCode = tooling::applyAllReplacements(Code, Replaces);
712 if (!ChangedCode) {
713 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
714 continue;
715 }
716 // Replacements on the changed code for moving namespaces and inserting
717 // forward declarations to old namespaces.
718 tooling::Replacements NewReplacements;
719 // Cut the changed code from the old namespace and paste the code in the new
720 // namespace.
721 for (const auto &NsMove : NsMoves) {
722 // Calculate the range of the old namespace block in the changed
723 // code.
724 const unsigned NewOffset = Replaces.getShiftedCodePosition(NsMove.Offset);
725 const unsigned NewLength =
726 Replaces.getShiftedCodePosition(NsMove.Offset + NsMove.Length) -
727 NewOffset;
728 tooling::Replacement Deletion(FilePath, NewOffset, NewLength, "");
729 std::string MovedCode = ChangedCode->substr(NewOffset, NewLength);
730 std::string MovedCodeWrappedInNewNs =
731 wrapCodeInNamespace(DiffNewNamespace, MovedCode);
732 // Calculate the new offset at which the code will be inserted in the
733 // changed code.
734 unsigned NewInsertionOffset =
735 Replaces.getShiftedCodePosition(NsMove.InsertionOffset);
736 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
737 MovedCodeWrappedInNewNs);
738 addOrMergeReplacement(Deletion, &NewReplacements);
739 addOrMergeReplacement(Insertion, &NewReplacements);
740 }
741 // After moving namespaces, insert forward declarations back to old
742 // namespaces.
743 const auto &FwdDeclInsertions = InsertFwdDecls[FilePath];
744 for (const auto &FwdDeclInsertion : FwdDeclInsertions) {
745 unsigned NewInsertionOffset =
746 Replaces.getShiftedCodePosition(FwdDeclInsertion.InsertionOffset);
747 tooling::Replacement Insertion(FilePath, NewInsertionOffset, 0,
748 FwdDeclInsertion.ForwardDeclText);
749 addOrMergeReplacement(Insertion, &NewReplacements);
750 }
751 // Add replacements referring to the changed code to existing replacements,
752 // which refers to the original code.
753 Replaces = Replaces.merge(NewReplacements);
754 format::FormatStyle Style =
755 format::getStyle("file", FilePath, FallbackStyle);
756 // Clean up old namespaces if there is nothing in it after moving.
757 auto CleanReplacements =
758 format::cleanupAroundReplacements(Code, Replaces, Style);
759 if (!CleanReplacements) {
760 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
761 continue;
762 }
763 FileToReplacements[FilePath] = *CleanReplacements;
764 }
765}
766
767} // namespace change_namespace
768} // namespace clang