Debian Codegraph @

clang_delta/RemoveNamespace.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2012, 2013, 2015, 2016, 2017, 2019, 2020 The University of Utah
4 // All rights reserved.
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See the file COPYING for details.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #if HAVE_CONFIG_H
12 # include <config.h>
13 #endif
14
15 #include "RemoveNamespace.h"
16
17 #include <sstream>
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/Basic/SourceManager.h"
21
22 #include "TransformationManager.h"
23
24 using namespace clang;
25
26 static const char *DescriptionMsg =
27 "Remove namespaces. This pass tries to remove namespace without \
28 introducing name conflicts. \n";
29
30 static RegisterTransformation<RemoveNamespace>
31 Trans("remove-namespace", DescriptionMsg);
32
33 class RemoveNamespaceASTVisitor : public
34 RecursiveASTVisitor<RemoveNamespaceASTVisitor> {
35
36 public:
37 explicit RemoveNamespaceASTVisitor(RemoveNamespace *Instance)
38 : ConsumerInstance(Instance)
39 { }
40
41 bool VisitNamespaceDecl(NamespaceDecl *ND);
42
43 private:
44 RemoveNamespace *ConsumerInstance;
45
46 };
47
48 // A visitor for rewriting decls in the namespace being removed
49 // ISSUE: quite a lot of functionality could be provided by the
50 // RenameClassRewriteVisitor from RenameClass.cpp.
51 // I have certain hesitation of factoring out
52 // RenameClassRewriteVisitor for common uses.
53 // A couple of reasons:
54 // * RenameClassRewriteVisitor is only suitable for renaming
55 // classes, but here we will be facing more types, e.g., enum.
56 // * RenameClassRewriteVisitor handles one class, but here
57 // we need to rename multiple conflicting classes;
58 // * some processing logic is different here
59 // * I don't want to make two transformations interference with
60 // each other
61 // Therefore, we will have some code duplications (but not much
62 // since I put quite a few common utility functions into RewriteUtils)
63 class RemoveNamespaceRewriteVisitor : public
64 RecursiveASTVisitor<RemoveNamespaceRewriteVisitor> {
65
66 public:
67 explicit RemoveNamespaceRewriteVisitor(RemoveNamespace *Instance)
68 : ConsumerInstance(Instance),
69 SkipRewriteName(false),
70 SkipTraverseNestedNameSpecifier(false)
71 { }
72
73 bool VisitNamespaceDecl(NamespaceDecl *ND);
74
75 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
76
77 bool VisitUsingDecl(UsingDecl *D);
78
79 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
80
81 bool VisitCXXConstructorDecl(CXXConstructorDecl *CtorDecl);
82
83 bool VisitCXXDestructorDecl(CXXDestructorDecl *DtorDecl);
84
85 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *CE);
86
87 bool VisitDeclRefExpr(DeclRefExpr *DRE);
88
89 bool VisitRecordTypeLoc(RecordTypeLoc RTLoc);
90
91 bool VisitTemplateSpecializationTypeLoc(
92 TemplateSpecializationTypeLoc TSPLoc);
93
94 bool VisitDependentTemplateSpecializationTypeLoc(
95 DependentTemplateSpecializationTypeLoc DTSLoc);
96
97 bool VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TyLoc);
98
99 bool VisitTypedefTypeLoc(TypedefTypeLoc TyLoc);
100
101 bool VisitClassTemplateSpecializationDecl(
102 ClassTemplateSpecializationDecl *TSD);
103
104 bool VisitEnumTypeLoc(EnumTypeLoc TpLoc);
105
106 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc SpecifierLoc);
107
108 private:
109 RemoveNamespace *ConsumerInstance;
110
111 bool SkipRewriteName;
112
113 bool SkipTraverseNestedNameSpecifier;
114 };
115
116 bool RemoveNamespaceASTVisitor::VisitNamespaceDecl(NamespaceDecl *ND)
117 {
118 ConsumerInstance->handleOneNamespaceDecl(ND);
119 return true;
120 }
121
122 // ISSUE: I am not sure why, but RecursiveASTVisitor doesn't recursively
123 // visit base classes from explicit template specialization, e.g.,
124 // struct A { };
125 // template<typename T> class B : public A<T> { };
126 // template<> class B : public A<short> { };
127 // In the above case, A<short> won't be touched.
128 // So we have to do it manually
129 bool RemoveNamespaceRewriteVisitor::VisitClassTemplateSpecializationDecl(
130 ClassTemplateSpecializationDecl *TSD)
131 {
132 if (!TSD->isExplicitInstantiationOrSpecialization())
133 return true;
134
135 const CXXRecordDecl *CXXRD = TSD->getSpecializedTemplate()->getTemplatedDecl();
136 std::string Name;
137 if (ConsumerInstance->getNewName(CXXRD, Name)) {
138 SourceLocation LocStart = TSD->getLocation();
139 TransAssert(LocStart.isValid() && "Invalid Location!");
140 ConsumerInstance->TheRewriter.ReplaceText(
141 LocStart, CXXRD->getNameAsString().size(), Name);
142 }
143
144 if (TSD->isExplicitSpecialization() && TSD->isCompleteDefinition()) {
145 for (CXXRecordDecl::base_class_const_iterator I = TSD->bases_begin(),
146 E = TSD->bases_end(); I != E; ++I) {
147 TypeSourceInfo *TSI = (*I).getTypeSourceInfo();
148 TransAssert(TSI && "Bad TypeSourceInfo!");
149 TraverseTypeLoc(TSI->getTypeLoc());
150 }
151 }
152 return true;
153 }
154
155 bool RemoveNamespaceRewriteVisitor::VisitNamespaceDecl(NamespaceDecl *ND)
156 {
157 if (ConsumerInstance->isForUsingNamedDecls)
158 return true;
159
160 const NamespaceDecl *CanonicalND = ND->getCanonicalDecl();
161 if (CanonicalND != ConsumerInstance->TheNamespaceDecl)
162 return true;
163
164 ConsumerInstance->removeNamespace(ND);
165 return true;
166 }
167
168 bool RemoveNamespaceRewriteVisitor::VisitUsingDirectiveDecl(
169 UsingDirectiveDecl *D)
170 {
171 if (ConsumerInstance->isForUsingNamedDecls)
172 return true;
173
174 if (ConsumerInstance->UselessUsingDirectiveDecls.count(D)) {
175 ConsumerInstance->RewriteHelper->removeDecl(D);
176 return true;
177 }
178
179 const NamespaceDecl *CanonicalND =
180 D->getNominatedNamespace()->getCanonicalDecl();
181
182 if (CanonicalND == ConsumerInstance->TheNamespaceDecl) {
183 // remove the entire Decl if it's in the following form:
184 // * using namespace TheNameSpace; or
185 // * using namespace ::TheNameSpace;
186
187 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
188 if (!QualifierLoc || ConsumerInstance->isGlobalNamespace(QualifierLoc))
189 ConsumerInstance->RewriteHelper->removeDecl(D);
190 else
191 ConsumerInstance->removeLastNamespaceFromUsingDecl(D, CanonicalND);
192 }
193
194 // handle cases like the following:
195 // namespace NS1 { }
196 // namespace NS2 {
197 // namespace NS1 {
198 // void foo() {}
199 // }
200 // namespace NS3 {
201 // using namespace NS1;
202 // void bar() {foo();}
203 // }
204 // }
205 // if we remove NS1, we need to update "using namespace NS1" because "NS1"
206 // conflicts with the global namespace NS1. Note that it could only happen
207 // if NS1 is the first name in a NestedNameSpecifier
208 std::string Name;
209 if (ConsumerInstance->getNewNamedDeclName(CanonicalND, Name)) {
210 ConsumerInstance->replaceFirstNamespaceFromUsingDecl(D, Name);
211 }
212
213 return true;
214 }
215
216 bool RemoveNamespaceRewriteVisitor::VisitUsingDecl(UsingDecl *D)
217 {
218 if (ConsumerInstance->isForUsingNamedDecls)
219 return true;
220
221 if (ConsumerInstance->UselessUsingDecls.count(D)) {
222 ConsumerInstance->RewriteHelper->removeDecl(D);
223 return true;
224 }
225
226 // check if this UsingDecl refers to the namespaced being removed
227 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
228 TransAssert(QualifierLoc && "Bad QualifierLoc!");
229 NestedNameSpecifierLoc PrefixLoc = QualifierLoc.getPrefix();
230
231 const NestedNameSpecifier *NNS = D->getQualifier();
232 TransAssert(NNS && "Bad NameSpecifier!");
233 if (ConsumerInstance->isTheNamespaceSpecifier(NNS) &&
234 (!PrefixLoc || ConsumerInstance->isGlobalNamespace(PrefixLoc))) {
235 ConsumerInstance->RewriteHelper->removeDecl(D);
236 SkipTraverseNestedNameSpecifier = true;
237 }
238
239 return true;
240 }
241
242 bool RemoveNamespaceRewriteVisitor::VisitNamespaceAliasDecl(
243 NamespaceAliasDecl *D)
244 {
245 if (ConsumerInstance->isForUsingNamedDecls)
246 return true;
247
248 const NamespaceDecl *CanonicalND =
249 D->getNamespace()->getCanonicalDecl();
250 if (D->getQualifier()) {
251 TraverseNestedNameSpecifierLoc(D->getQualifierLoc());
252 if (CanonicalND == ConsumerInstance->TheNamespaceDecl) {
253 NestedNameSpecifierLoc QualLoc = D->getQualifierLoc();
254 SourceLocation QualEndLoc = QualLoc.getEndLoc();
255 SourceLocation DeclEndLoc = D->getSourceRange().getEnd();
256 ConsumerInstance->TheRewriter.RemoveText(
257 SourceRange(QualEndLoc, DeclEndLoc));
258 }
259 }
260 else {
261 if (CanonicalND == ConsumerInstance->TheNamespaceDecl)
262 ConsumerInstance->RewriteHelper->removeDecl(D);
263 }
264
265 return true;
266 }
267
268 bool RemoveNamespaceRewriteVisitor::VisitCXXConstructorDecl
269 (CXXConstructorDecl *CtorDecl)
270 {
271 if (ConsumerInstance->isForUsingNamedDecls)
272 return true;
273
274 const DeclContext *Ctx = CtorDecl->getDeclContext();
275 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Ctx);
276 TransAssert(CXXRD && "Invalid CXXRecordDecl");
277
278 std::string Name;
279 if (ConsumerInstance->getNewNamedDeclName(CXXRD, Name))
280 ConsumerInstance->RewriteHelper->replaceFunctionDeclName(CtorDecl, Name);
281
282 return true;
283 }
284
285 // I didn't factor out the common part of this function
286 // into RewriteUtils, because the common part has implicit
287 // dependency on VisitTemplateSpecializationTypeLoc. If in another
288 // transformation we use this utility without implementing
289 // VisitTemplateSpecializationTypeLoc, we will be in trouble.
290 bool RemoveNamespaceRewriteVisitor::VisitCXXDestructorDecl(
291 CXXDestructorDecl *DtorDecl)
292 {
293 if (ConsumerInstance->isForUsingNamedDecls)
294 return true;
295
296 const DeclContext *Ctx = DtorDecl->getDeclContext();
297 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Ctx);
298 TransAssert(CXXRD && "Invalid CXXRecordDecl");
299
300 std::string Name;
301 if (!ConsumerInstance->getNewNamedDeclName(CXXRD, Name))
302 return true;
303
304 // Avoid duplicated VisitDtor.
305 // For example, in the code below:
306 // template<typename T>
307 // class SomeClass {
308 // public:
309 // ~SomeClass<T>() {}
310 // };
311 // ~SomeClass<T>'s TypeLoc is represented as TemplateSpecializationTypeLoc
312 // In this case, ~SomeClass will be renamed from
313 // VisitTemplateSpecializationTypeLoc.
314 DeclarationNameInfo NameInfo = DtorDecl->getNameInfo();
315 if ( TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo()) {
316 TypeLoc DtorLoc = TSInfo->getTypeLoc();
317 if (!DtorLoc.isNull() &&
318 (DtorLoc.getTypeLocClass() == TypeLoc::TemplateSpecialization))
319 return true;
320 }
321
322 ConsumerInstance->RewriteHelper->replaceCXXDestructorDeclName(DtorDecl, Name);
323
324 return true;
325 }
326
327 bool RemoveNamespaceRewriteVisitor::VisitCXXMemberCallExpr(
328 CXXMemberCallExpr *CXXCE)
329 {
330 const CXXRecordDecl *CXXRD = CXXCE->getRecordDecl();
331 // getRecordDEcl could return NULL if getImplicitObjectArgument()
332 // returns NULL
333 if (!CXXRD || ConsumerInstance->isForUsingNamedDecls)
334 return true;
335
336 std::string Name;
337 // Dtors from UsingNamedDecl can't have conflicts, so it's safe
338 // to get new names from NamedDecl set
339 if (ConsumerInstance->getNewNamedDeclName(CXXRD, Name))
340 ConsumerInstance->RewriteHelper->replaceCXXDtorCallExpr(CXXCE, Name);
341 return true;
342 }
343
344 bool RemoveNamespaceRewriteVisitor::VisitDeclRefExpr(DeclRefExpr *DRE)
345 {
346 NestedNameSpecifierLoc Loc = DRE->getQualifierLoc();
347
348 // traverse NestedNameSpecifier first, because we could probably
349 // ignore rewriting this DeclRefExpr
350 TraverseNestedNameSpecifierLoc(Loc);
351 // Avoid double-visit
352 SkipTraverseNestedNameSpecifier = true;
353 if (SkipRewriteName) {
354 SkipRewriteName = false;
355 return true;
356 }
357
358 const ValueDecl *OrigDecl = DRE->getDecl();
359
360 if (isa<FunctionDecl>(OrigDecl) || isa<VarDecl>(OrigDecl) ||
361 isa<EnumConstantDecl>(OrigDecl)) {
362 std::string Name;
363 if (ConsumerInstance->getNewName(OrigDecl, Name)) {
364 unsigned Len = OrigDecl->getNameAsString().size();
365 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(OrigDecl)) {
366 // handle user-defined literals
367 if (const IdentifierInfo *IdInfo = FD->getLiteralIdentifier()) {
368 Len = IdInfo->getLength();
369 }
370 }
371 ConsumerInstance->TheRewriter.ReplaceText(DRE->getBeginLoc(), Len, Name);
372 }
373 }
374
375 return true;
376 }
377
378 bool RemoveNamespaceRewriteVisitor::VisitRecordTypeLoc(RecordTypeLoc RTLoc)
379 {
380 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RTLoc.getDecl());
381 if (!RD)
382 return true;
383
384 std::string Name;
385 if (ConsumerInstance->getNewName(RD, Name)) {
386 ConsumerInstance->RewriteHelper->replaceRecordType(RTLoc, Name);
387 }
388 return true;
389 }
390
391 bool RemoveNamespaceRewriteVisitor::VisitTemplateSpecializationTypeLoc(
392 TemplateSpecializationTypeLoc TSPLoc)
393 {
394 const Type *Ty = TSPLoc.getTypePtr();
395 const TemplateSpecializationType *TST =
396 dyn_cast<TemplateSpecializationType>(Ty);
397 TransAssert(TST && "Bad TemplateSpecializationType!");
398
399 TemplateName TplName = TST->getTemplateName();
400 const TemplateDecl *TplD = TplName.getAsTemplateDecl();
401 TransAssert(TplD && "Invalid TemplateDecl!");
402 NamedDecl *ND = TplD->getTemplatedDecl();
403 // in some cases, ND could be NULL, e.g., the
404 // template template parameter code below:
405 // template<template<class> class BBB>
406 // struct AAA {
407 // template <class T>
408 // struct CCC {
409 // static BBB<T> a;
410 // };
411 // };
412 // where we don't know BBB
413 if (!ND)
414 return true;
415
416 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ND);
417 if (!CXXRD)
418 return true;
419
420 std::string Name;
421 if (ConsumerInstance->getNewName(CXXRD, Name)) {
422 SourceLocation LocStart = TSPLoc.getTemplateNameLoc();
423 ConsumerInstance->TheRewriter.ReplaceText(
424 LocStart, CXXRD->getNameAsString().size(), Name);
425 }
426
427 return true;
428 }
429
430 // handle the case where a template specialization type cannot be resolved, e.g.
431 // template <class T> struct Base {};
432 // template <class T> struct Derived: public Base<T> {
433 // typename Derived::template Base<double>* p1;
434 // };
435 bool RemoveNamespaceRewriteVisitor::VisitDependentTemplateSpecializationTypeLoc(
436 DependentTemplateSpecializationTypeLoc DTSLoc)
437 {
438 const Type *Ty = DTSLoc.getTypePtr();
439 const DependentTemplateSpecializationType *DTST =
440 dyn_cast<DependentTemplateSpecializationType>(Ty);
441 TransAssert(DTST && "Bad DependentTemplateSpecializationType!");
442
443 const IdentifierInfo *IdInfo = DTST->getIdentifier();
444 std::string IdName = IdInfo->getName().str();
445 std::string Name;
446
447 // FIXME:
448 // This isn't quite right, we will generate bad code for some cases, e.g.,
449 // namespace NS1 {
450 // template <class T> struct Base {};
451 // template <class T> struct Derived: public Base<T> {
452 // typename Derived::template Base<double>* p1;
453 // };
454 // }
455 // template <class T> struct Base {};
456 // template <class T> struct Derived: public Base<T> {
457 // typename Derived::template Base<double>* p1;
458 // };
459 // For the global Derived template class, we will end up with
460 // typename Derived::template Tran_NS_NS1_Base ...,
461 // which is obviously wrong.
462 // Any way to avoid this bad transformation?
463 if (ConsumerInstance->getNewNameByName(IdName, Name)) {
464 SourceLocation LocStart = DTSLoc.getTemplateNameLoc();
465 ConsumerInstance->TheRewriter.ReplaceText(
466 LocStart, IdName.size(), Name);
467 }
468
469 return true;
470 }
471
472 bool RemoveNamespaceRewriteVisitor::VisitInjectedClassNameTypeLoc(
473 InjectedClassNameTypeLoc TyLoc)
474 {
475 const CXXRecordDecl *CXXRD = TyLoc.getDecl();
476 TransAssert(CXXRD && "Invalid CXXRecordDecl!");
477
478 std::string Name;
479 if (ConsumerInstance->getNewName(CXXRD, Name)) {
480 SourceLocation LocStart = TyLoc.getBeginLoc();
481 TransAssert(LocStart.isValid() && "Invalid Location!");
482
483 ConsumerInstance->TheRewriter.ReplaceText(
484 LocStart, CXXRD->getNameAsString().size(), Name);
485 }
486 return true;
487 }
488
489 bool RemoveNamespaceRewriteVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TyLoc)
490 {
491 const TypedefNameDecl *D = TyLoc.getTypedefNameDecl();
492
493 std::string Name;
494 if (ConsumerInstance->getNewName(D, Name)) {
495 SourceLocation LocStart = TyLoc.getBeginLoc();
496 ConsumerInstance->TheRewriter.ReplaceText(
497 LocStart, D->getNameAsString().size(), Name);
498 }
499 return true;
500 }
501
502 bool RemoveNamespaceRewriteVisitor::VisitEnumTypeLoc(EnumTypeLoc TyLoc)
503 {
504 const EnumDecl *D = TyLoc.getDecl();
505
506 std::string Name;
507 if (ConsumerInstance->getNewName(D, Name)) {
508 SourceLocation LocStart = TyLoc.getBeginLoc();
509 ConsumerInstance->TheRewriter.ReplaceText(
510 LocStart, D->getNameAsString().size(), Name);
511 }
512 return true;
513 }
514
515 // It handles two cases:
516 // * remove the specifier if it refers to TheNamespaceDecl
517 // * replace the specifier with a new name if the corresponding namespace
518 // has a name conflicts, e.g.,
519 // namespace NS1 { }
520 // namespace NS2 {
521 // namespace NS1 {
522 // void foo() {}
523 // }
524 // namespace NS3 {
525 // using NS1::foo;
526 // void bar() { foo(); }
527 // }
528 // }
529 // If we remove NS2, then the inner namespace NS1 conflicts with
530 // the global NS1, but "using NS1::foo" refers to the conflicting NS1.
531 bool RemoveNamespaceRewriteVisitor::TraverseNestedNameSpecifierLoc(
532 NestedNameSpecifierLoc QualifierLoc)
533 {
534 SkipRewriteName = false;
535 // Reset the flag
536 if (SkipTraverseNestedNameSpecifier) {
537 SkipTraverseNestedNameSpecifier = false;
538 return true;
539 }
540
541 if (!QualifierLoc || QualifierLoc.getBeginLoc().isInvalid())
542 return true;
543
544 SmallVector<NestedNameSpecifierLoc, 8> QualifierLocs;
545 for (; QualifierLoc; QualifierLoc = QualifierLoc.getPrefix())
546 QualifierLocs.push_back(QualifierLoc);
547
548 while (!QualifierLocs.empty()) {
549 NestedNameSpecifierLoc Loc = QualifierLocs.pop_back_val();
550 NestedNameSpecifier *NNS = Loc.getNestedNameSpecifier();
551 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
552 const NamespaceDecl *ND = NULL;
553
554 switch (Kind) {
555 case NestedNameSpecifier::Namespace: {
556 ND = NNS->getAsNamespace()->getCanonicalDecl();
557 break;
558 }
559 case NestedNameSpecifier::NamespaceAlias: {
560 const NamespaceAliasDecl *NAD = NNS->getAsNamespaceAlias();
561 if (!NAD->getQualifier())
562 ND = NAD->getNamespace()->getCanonicalDecl();
563 break;
564 }
565 case NestedNameSpecifier::TypeSpec: // Fall-through
566 case NestedNameSpecifier::TypeSpecWithTemplate:
567 TraverseTypeLoc(Loc.getTypeLoc());
568 break;
569 default:
570 break;
571 }
572
573 if (!ND)
574 continue;
575
576 if (ND == ConsumerInstance->TheNamespaceDecl) {
577 ConsumerInstance->RewriteHelper->removeSpecifier(Loc);
578 continue;
579 }
580
581 std::string SpecifierName;
582 if (Loc.getBeginLoc().isInvalid())
583 continue;
584
585 ConsumerInstance->RewriteHelper->getSpecifierAsString(Loc, SpecifierName);
586 std::string NDName = ND->getNameAsString();
587 std::string Name = "";
588 ConsumerInstance->getNewName(ND, Name);
589
590 // Skip it if this specifier is the same as ND's name.
591 // Note that the above case could only happen for UsingNamedDecls
592 if (ConsumerInstance->isForUsingNamedDecls && (SpecifierName == NDName)) {
593 // It could happen for example:
594 // namespace NS1 { }
595 // namespace NS2 {
596 // using namespace NS1;
597 // void bar() { NS1::foo(); }
598 // }
599 // If we remove NS2, then the guard below avoids renaming
600 // NS1::foo to NS1::foo::foo.
601 if (Name.empty()) {
602 SkipRewriteName = true;
603 return true;
604 }
605
606 // another case to handle:
607 // namespace NS1 {
608 // namespace NS2 {
609 // void foo() {}
610 // }
611 // }
612 // namespace NS3 {
613 // using namespace NS1;
614 // void bar() { NS2::foo(); }
615 // }
616 // If we remove NS3, we do need to rename NS2::foo as NS1::NS2::foo
617 if (!ConsumerInstance->isSuffix(Name, SpecifierName)) {
618 SkipRewriteName = true;
619 return true;
620 }
621 }
622
623 if (!Name.empty()) {
624 ConsumerInstance->RewriteHelper->replaceSpecifier(Loc, Name);
625 SkipRewriteName = true;
626 return true;
627 }
628 }
629 return true;
630 }
631
632 void RemoveNamespace::Initialize(ASTContext &context)
633 {
634 Transformation::Initialize(context);
635 CollectionVisitor = new RemoveNamespaceASTVisitor(this);
636 RewriteVisitor = new RemoveNamespaceRewriteVisitor(this);
637 }
638
639 bool RemoveNamespace::HandleTopLevelDecl(DeclGroupRef D)
640 {
641 // Nothing to do
642 return true;
643 }
644
645 void RemoveNamespace::HandleTranslationUnit(ASTContext &Ctx)
646 {
647 if (TransformationManager::isCLangOpt()) {
648 ValidInstanceNum = 0;
649 }
650 else {
651 // Invoke CollectionVisitor here because we need full DeclContext
652 // to resolve name conflicts. Full ASTs has been built at this point.
653 CollectionVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
654 }
655
656 if (QueryInstanceOnly)
657 return;
658
659 if (TransformationCounter > ValidInstanceNum) {
660 TransError = TransMaxInstanceError;
661 return;
662 }
663
664 TransAssert(RewriteVisitor && "NULL RewriteVisitor!");
665 TransAssert(TheNamespaceDecl && "NULL TheNamespaceDecl!");
666 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
667
668 // First rename UsingNamedDecls, i.e., conflicting names
669 // from other namespaces.
670 // FIXME: isForUsingNamedDecls flag is quite ugly,
671 // need a way to remove it
672 isForUsingNamedDecls = true;
673 RewriteVisitor->TraverseDecl(TheNamespaceDecl);
674 isForUsingNamedDecls = false;
675
676 rewriteNamedDecls();
677 RewriteVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
678
679 if (Ctx.getDiagnostics().hasErrorOccurred() ||
680 Ctx.getDiagnostics().hasFatalErrorOccurred())
681 TransError = TransInternalError;
682 }
683
684 void RemoveNamespace::rewriteNamedDecls(void)
685 {
686 for (NamedDeclToNameMap::const_iterator I = NamedDeclToNewName.begin(),
687 E = NamedDeclToNewName.end(); I != E; ++I) {
688 const NamedDecl *D = (*I).first;
689 std::string Name = (*I).second;
690
691 Decl::Kind K = D->getKind();
692 switch (K) {
693 case Decl::Function:
694 case Decl::CXXMethod: {
695 // Check replaceFunctionDecl in RewriteUtils.cpp for the reason that
696 // we need a special case for FunctionDecl
697 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
698 RewriteHelper->replaceFunctionDeclName(FD, Name);
699 break;
700 }
701 case Decl::ClassTemplateSpecialization: {
702 // Skip this case, which will be handled by
703 // VisitTemplateSpecializationTypeLoc
704 break;
705 }
706 default:
707 RewriteHelper->replaceNamedDeclName(D, Name);
708 }
709 }
710 }
711
712 bool RemoveNamespace::isValidNamedDeclKind(const NamedDecl *ND)
713 {
714 return (isa<TemplateDecl>(ND) || isa<TypeDecl>(ND) ||
715 isa<ValueDecl>(ND) || isa<NamespaceDecl>(ND) ||
716 isa<NamespaceAliasDecl>(ND));
717 }
718
719 bool RemoveNamespace::hasNameConflict(const NamedDecl *ND,
720 const DeclContext *ParentCtx)
721 {
722 // we cannot lookup names from LinkageSpecDecl, e.g.,
723 // extern "C++" { ... }
724 if (dyn_cast<LinkageSpecDecl>(ParentCtx))
725 return false;
726
727 DeclarationName Name = ND->getDeclName();
728 DeclContext::lookup_result Result = ParentCtx->lookup(Name);
729 return !Result.empty();
730 }
731
732 // We always prepend the Prefix string to EnumConstantDecl if ParentCtx
733 // is NULL
734 void RemoveNamespace::handleOneEnumDecl(const EnumDecl *ED,
735 const std::string &Prefix,
736 NamedDeclToNameMap &NameMap,
737 const DeclContext *ParentCtx)
738 {
739 for (EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
740 E = ED->enumerator_end(); I != E; ++I) {
741 EnumConstantDecl *ECD = (*I);
742 if (!ParentCtx || hasNameConflict(ECD, ParentCtx)) {
743 const IdentifierInfo *IdInfo = ECD->getIdentifier();
744 std::string NewName = Prefix;
745 NewName += IdInfo->getName();
746 NameMap[ECD] = NewName;
747 }
748 }
749 }
750
751 // A using declaration in the removed namespace could cause
752 // name conflict, e.g.,
753 // namespace NS1 {
754 // void foo(void) {}
755 // }
756 // namespace NS2 {
757 // using NS1::foo;
758 // void bar() { ... foo(); ... }
759 // }
760 // void foo() {...}
761 // void func() {... foo(); ...}
762 // if we remove NS2, then foo() in func() will become ambiguous.
763 // In this case, we need to replace the first invocation of foo()
764 // with NS1::foo()
765 void RemoveNamespace::handleOneUsingShadowDecl(const UsingShadowDecl *UD,
766 const DeclContext *ParentCtx)
767 {
768 const NamedDecl *ND = UD->getTargetDecl();
769 if (!hasNameConflict(ND, ParentCtx))
770 return;
771
772 std::string NewName;
773 const BaseUsingDecl *BD = UD->getIntroducer();
774 const UsingDecl *D = dyn_cast<UsingDecl>(BD);
775 if (!D)
776 return;
777
778 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
779 NestedNameSpecifier *NNS = QualifierLoc.getNestedNameSpecifier();
780
781 // QualifierLoc could be ::foo, whose PrefixLoc is invalid, e.g.,
782 // void foo();
783 // namespace NS2 {
784 // using ::foo;
785 // void bar () { foo(); }
786 // }
787 if (NNS->getKind() != NestedNameSpecifier::Global) {
788 // NestedNameSpecifierLoc PrefixLoc = QualifierLoc.getPrefix();
789 RewriteHelper->getQualifierAsString(QualifierLoc, NewName);
790 }
791
792 if ( const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND) ) {
793 ND = TD->getTemplatedDecl();
794 }
795
796 // NewName += "::";
797 const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
798 if (FD && FD->isOverloadedOperator()) {
799 const char *Op = clang::getOperatorSpelling(FD->getOverloadedOperator());
800 std::string OpStr(Op);
801 NewName += ("operator::" + OpStr);
802 }
803 else {
804 const IdentifierInfo *IdInfo = ND->getIdentifier();
805 TransAssert(IdInfo && "Invalid IdentifierInfo!");
806 NewName += IdInfo->getName();
807 }
808 UsingNamedDeclToNewName[ND] = NewName;
809
810 // the tied UsingDecl becomes useless, and hence it's removable
811 UselessUsingDecls.insert(D);
812 }
813
814 // For the similar reason as dealing with using declarations,
815 // we need to resolve the possible name conflicts introduced by
816 // using directives
817 void RemoveNamespace::handleOneUsingDirectiveDecl(const UsingDirectiveDecl *UD,
818 const DeclContext *ParentCtx)
819 {
820 const NamespaceDecl *ND = UD->getNominatedNamespace();
821
822 // It could happen, for example:
823 // namespace NS {
824 // namespace {
825 // int x;
826 // }
827 // }
828 // where the inner anonymous namespace will have an implicit using directive
829 // declaration
830 if (ND->isAnonymousNamespace())
831 return;
832
833 std::string NamespaceName = ND->getNameAsString();
834
835 for (DeclContext::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
836 I != E; ++I) {
837 const NamedDecl *NamedD = dyn_cast<NamedDecl>(*I);
838 if (!NamedD)
839 continue;
840
841 if (!isValidNamedDeclKind(NamedD))
842 continue;
843
844 std::string NewName = "";
845 if ( NestedNameSpecifierLoc QualifierLoc = UD->getQualifierLoc() ) {
846 RewriteHelper->getQualifierAsString(QualifierLoc, NewName);
847 }
848 NewName += NamespaceName;
849 NewName += "::";
850
851 if ( const TemplateDecl *TD = dyn_cast<TemplateDecl>(NamedD) ) {
852 NamedD = TD->getTemplatedDecl();
853 }
854 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(NamedD)) {
855 handleOneEnumDecl(ED, NewName, UsingNamedDeclToNewName, NULL);
856 }
857 const FunctionDecl *FD = dyn_cast<FunctionDecl>(NamedD);
858 if (FD && FD->isOverloadedOperator()) {
859 const char *Op = clang::getOperatorSpelling(FD->getOverloadedOperator());
860 std::string OpStr(Op);
861 NewName += ("operator::" + OpStr);
862 }
863 else {
864 const IdentifierInfo *IdInfo = NamedD->getIdentifier();
865 if (!IdInfo)
866 continue;
867 NewName += IdInfo->getName();
868 }
869 UsingNamedDeclToNewName[NamedD] = NewName;
870 }
871
872 // We always remove this using directive, and in ThenNamespaceDecl
873 // append the corresponding namespace specifier to all names from the
874 // used namespace. The reason is that the conlicted name in the outter
875 // namespace could appear after TheNamespaceDecl, e.g.,
876 // namespace NS1 {
877 // void foo() {}
878 // void fiz() {}
879 // }
880 // namespace NS2 {
881 // using namespace NS1;
882 // int bar() { foo(); }
883 // }
884 // void fiz() {}
885 // void f() { fiz(); }
886 // If we keep "using namespace NS1" after removing NS2, then we will
887 // end up with an ambiguous name fiz
888 // Consequently, we will add a few unecessary namespace qualifiers to
889 // those without conflicting names. It's a trade-off.
890 UselessUsingDirectiveDecls.insert(UD);
891 }
892
893 void RemoveNamespace::handleOneNamedDecl(const NamedDecl *ND,
894 const DeclContext *ParentCtx,
895 const std::string &NamespaceName)
896 {
897 Decl::Kind K = ND->getKind();
898 switch (K) {
899 case Decl::UsingShadow: {
900 const UsingShadowDecl *D = dyn_cast<UsingShadowDecl>(ND);
901 handleOneUsingShadowDecl(D, ParentCtx);
902 return;
903 }
904
905 case Decl::UsingDirective: {
906 const UsingDirectiveDecl *D = dyn_cast<UsingDirectiveDecl>(ND);
907 handleOneUsingDirectiveDecl(D, ParentCtx);
908 return;
909 }
910
911 default:
912 if (!isValidNamedDeclKind(ND))
913 return;
914
915 if (!hasNameConflict(ND, ParentCtx))
916 return;
917
918 std::string NewName = NamePrefix + NamespaceName;
919 NewName += "_";
920
921 if ( const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND) ) {
922 ND = TD->getTemplatedDecl();
923 }
924 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(ND)) {
925 handleOneEnumDecl(ED, NewName, NamedDeclToNewName, ParentCtx);
926 }
927
928 // This is bad. Any better solution? Maybe we need to change
929 // the overloaded operator to a regular function?
930 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
931 if (FD->isOverloadedOperator())
932 return;
933 }
934
935 const IdentifierInfo *IdInfo = ND->getIdentifier();
936 bool IsUserLiteral = false;
937 if (!IdInfo) {
938 const FunctionDecl *FD = cast<FunctionDecl>(ND);
939 IdInfo = FD->getLiteralIdentifier();
940 if (IdInfo)
941 IsUserLiteral = true;
942 }
943
944 TransAssert(IdInfo && "Invalid IdentifierInfo!");
945 NewName += IdInfo->getName();
946 // Make sure we have valid suffix for user literals
947 if (IsUserLiteral && IdInfo->getName().startswith("_")) {
948 NewName = "_" + NewName;
949 }
950 NamedDeclToNewName[ND] = NewName;
951 }
952 }
953
954 void RemoveNamespace::addNamedDeclsFromNamespace(const NamespaceDecl *ND)
955 {
956 // We don't care about name-lookup for friend's functions, so just
957 // retrive ParentContext rather than LookupParent
958 const DeclContext *ParentCtx = ND->getParent();
959 std::string NamespaceName;
960
961 if (ND->isAnonymousNamespace()) {
962 std::stringstream TmpSS;
963 TmpSS << AnonNamePrefix << AnonNamespaceCounter;
964 NamespaceName = TmpSS.str();
965 AnonNamespaceCounter++;
966 }
967 else {
968 NamespaceName = ND->getNameAsString();
969 }
970
971 for (DeclContext::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
972 I != E; ++I) {
973 if ( const NamedDecl *D = dyn_cast<NamedDecl>(*I) )
974 handleOneNamedDecl(D, ParentCtx, NamespaceName);
975 }
976 }
977
978 bool RemoveNamespace::handleOneNamespaceDecl(NamespaceDecl *ND)
979 {
980 if (isInIncludedFile(ND))
981 return true;
982
983 NamespaceDecl *CanonicalND = ND->getCanonicalDecl();
984 if (VisitedND.count(CanonicalND)) {
985 if (TheNamespaceDecl == CanonicalND) {
986 addNamedDeclsFromNamespace(ND);
987 }
988 return true;
989 }
990
991 VisitedND.insert(CanonicalND);
992 ValidInstanceNum++;
993 if (ValidInstanceNum == TransformationCounter) {
994 TheNamespaceDecl = CanonicalND;
995 addNamedDeclsFromNamespace(ND);
996 }
997 return true;
998 }
999
1000 void RemoveNamespace::removeNamespace(const NamespaceDecl *ND)
1001 {
1002 // Remove the right brace first
1003 SourceLocation RBLoc = ND->getRBraceLoc();
1004 if (RBLoc.isValid()) {
1005 if (RBLoc.isMacroID()) {
1006 TheRewriter.RemoveText(SrcManager->getExpansionRange(RBLoc).getAsRange());
1007 }
1008 else {
1009 TheRewriter.RemoveText(RBLoc, 1);
1010 }
1011 }
1012
1013 // Then remove name and the left brace
1014 SourceLocation StartLoc = ND->getBeginLoc();
1015 TransAssert(StartLoc.isValid() && "Invalid Namespace LocStart!");
1016
1017 StartLoc = SrcManager->getFileLoc(StartLoc);
1018 SourceLocation EndLoc;
1019 if (ND->decls_empty()) {
1020 EndLoc = SrcManager->getFileLoc(RBLoc);
1021 }
1022 else {
1023 DeclContext::decl_iterator I = ND->decls_begin();
1024 EndLoc = SrcManager->getFileLoc(dyn_cast<Decl>(*I)->getBeginLoc());
1025 }
1026
1027 if (StartLoc != EndLoc) {
1028 EndLoc = EndLoc.getLocWithOffset(-1);
1029 SourceRange NewRange(StartLoc, EndLoc);
1030 int RangeSize = TheRewriter.getRangeSize(NewRange);
1031 TransAssert((RangeSize != -1) && "Bad Namespace Range!");
1032 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1033 std::string NDStr(StartBuf, RangeSize);
1034 size_t Pos = NDStr.find('{');
1035 if (Pos != std::string::npos)
1036 EndLoc = StartLoc.getLocWithOffset(Pos);
1037 }
1038
1039 TheRewriter.RemoveText(SourceRange(StartLoc, EndLoc));
1040 }
1041
1042 bool RemoveNamespace::getNewNameFromNameMap(const NamedDecl *ND,
1043 std::string &Name,
1044 const NamedDeclToNameMap &NameMap)
1045 {
1046 NamedDeclToNameMap::const_iterator Pos =
1047 NameMap.find(ND);
1048 if (Pos == NameMap.end())
1049 return false;
1050
1051 Name = (*Pos).second;
1052 return true;
1053 }
1054
1055 bool RemoveNamespace::getNewNameByNameFromNameMap(const std::string &Name,
1056 std::string &NewName,
1057 const NamedDeclToNameMap &NameMap)
1058 {
1059 for (NamedDeclToNameMap::const_iterator I = NameMap.begin(),
1060 E = NameMap.end(); I != E; ++I) {
1061 const NamedDecl *D = (*I).first;
1062 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(D);
1063 if (!CXXRD)
1064 continue;
1065 if (Name == CXXRD->getNameAsString()) {
1066 NewName = (*I).second;
1067 return true;
1068 }
1069 }
1070 return false;
1071 }
1072
1073 bool RemoveNamespace::getNewNamedDeclName(const NamedDecl *ND,
1074 std::string &Name)
1075 {
1076 return getNewNameFromNameMap(ND, Name, NamedDeclToNewName);
1077 }
1078
1079 bool RemoveNamespace::getNewUsingNamedDeclName(const NamedDecl *ND,
1080 std::string &Name)
1081 {
1082 return getNewNameFromNameMap(ND, Name, UsingNamedDeclToNewName);
1083 }
1084
1085 bool RemoveNamespace::getNewName(const NamedDecl *ND,
1086 std::string &Name)
1087 {
1088 if (isForUsingNamedDecls)
1089 return getNewUsingNamedDeclName(ND, Name);
1090 else
1091 return getNewNamedDeclName(ND, Name);
1092 }
1093
1094 bool RemoveNamespace::getNewNameByName(const std::string &Name,
1095 std::string &NewName)
1096 {
1097 if (isForUsingNamedDecls)
1098 return getNewNameByNameFromNameMap(Name, NewName, UsingNamedDeclToNewName);
1099 else
1100 return getNewNameByNameFromNameMap(Name, NewName, NamedDeclToNewName);
1101 }
1102
1103 bool RemoveNamespace::isGlobalNamespace(NestedNameSpecifierLoc Loc)
1104 {
1105 NestedNameSpecifier *NNS = Loc.getNestedNameSpecifier();
1106 return (NNS->getKind() == NestedNameSpecifier::Global);
1107 }
1108
1109 bool RemoveNamespace::isTheNamespaceSpecifier(const NestedNameSpecifier *NNS)
1110 {
1111 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
1112 switch (Kind) {
1113 case NestedNameSpecifier::Namespace: {
1114 const NamespaceDecl *CanonicalND =
1115 NNS->getAsNamespace()->getCanonicalDecl();
1116 return (CanonicalND == TheNamespaceDecl);
1117 }
1118
1119 case NestedNameSpecifier::NamespaceAlias: {
1120 const NamespaceAliasDecl *NAD = NNS->getAsNamespaceAlias();
1121 // we remove the namealias only when it doesn't have nestedspecifier
1122 if (NAD->getQualifier())
1123 return false;
1124 const NamespaceDecl *CanonicalND =
1125 NAD->getNamespace()->getCanonicalDecl();
1126 return (CanonicalND == TheNamespaceDecl);
1127 }
1128
1129 default:
1130 return false;
1131 }
1132 TransAssert(0 && "Unreachable code!");
1133 return false;
1134 }
1135
1136 bool RemoveNamespace::isSuffix(std::string &Name, std::string &SpecifierName)
1137 {
1138 size_t NameLen = Name.length();
1139 std::string Suffix = "::" + SpecifierName;
1140 size_t SuffixLen = Suffix.length();
1141 if (NameLen <= SuffixLen)
1142 return false;
1143
1144 return !Suffix.compare(0, SuffixLen, Name, NameLen - SuffixLen, SuffixLen);
1145 }
1146
1147 void RemoveNamespace::replaceFirstNamespaceFromUsingDecl(
1148 const UsingDirectiveDecl *D, const std::string &Name)
1149 {
1150 const NamespaceDecl *ND = D->getNominatedNamespace();
1151 SourceLocation IdLocStart = D->getIdentLocation();
1152 TheRewriter.ReplaceText(IdLocStart, ND->getNameAsString().length(), Name);
1153 }
1154
1155 void RemoveNamespace::removeLastNamespaceFromUsingDecl(
1156 const UsingDirectiveDecl *D, const NamespaceDecl *ND)
1157 {
1158 SourceLocation IdLocStart = D->getIdentLocation();
1159 SourceRange DeclSourceRange = D->getSourceRange();
1160 SourceLocation DeclLocStart = DeclSourceRange.getBegin();
1161
1162 const char *IdStartBuf = SrcManager->getCharacterData(IdLocStart);
1163 const char *DeclStartBuf = SrcManager->getCharacterData(DeclLocStart);
1164
1165 unsigned Count = 0;
1166 int Offset = 0;
1167 while (IdStartBuf != DeclStartBuf) {
1168 if (*IdStartBuf != ':') {
1169 IdStartBuf--;
1170 Offset--;
1171 continue;
1172 }
1173
1174 Count++;
1175 if (Count == 2) {
1176 break;
1177 }
1178 Offset--;
1179 IdStartBuf--;
1180 }
1181 TransAssert((Count == 2) && "Bad NestedNamespaceSpecifier!");
1182 TransAssert((Offset < 0) && "Bad Offset Value!");
1183 IdLocStart = IdLocStart.getLocWithOffset(Offset);
1184
1185 TheRewriter.RemoveText(IdLocStart,
1186 ND->getNameAsString().length() - Offset);
1187 }
1188
1189 RemoveNamespace::~RemoveNamespace(void)
1190 {
1191 delete CollectionVisitor;
1192 delete RewriteVisitor;
1193 }
1194