Debian Codegraph @

clang_delta/RemoveNamespace.cpp

raw symbols ◀ ▶ SCIP
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 #if LLVM_VERSION_MAJOR >= 21
444 const IdentifierInfo *IdInfo = DTST->getDependentTemplateName().getName().getIdentifier();
445 #else
446 const IdentifierInfo *IdInfo = DTST->getIdentifier();
•447 #endif
448 std::string IdName = IdInfo->getName().str();
449 std::string Name;
450
451 // FIXME:
452 // This isn't quite right, we will generate bad code for some cases, e.g.,
453 // namespace NS1 {
454 // template <class T> struct Base {};
455 // template <class T> struct Derived: public Base<T> {
456 // typename Derived::template Base<double>* p1;
457 // };
458 // }
459 // template <class T> struct Base {};
460 // template <class T> struct Derived: public Base<T> {
461 // typename Derived::template Base<double>* p1;
462 // };
463 // For the global Derived template class, we will end up with
464 // typename Derived::template Tran_NS_NS1_Base ...,
465 // which is obviously wrong.
466 // Any way to avoid this bad transformation?
467 if (ConsumerInstance->getNewNameByName(IdName, Name)) {
468 SourceLocation LocStart = DTSLoc.getTemplateNameLoc();
469 ConsumerInstance->TheRewriter.ReplaceText(
470 LocStart, IdName.size(), Name);
471 }
472
473 return true;
474 }
475
476 bool RemoveNamespaceRewriteVisitor::VisitInjectedClassNameTypeLoc(
477 InjectedClassNameTypeLoc TyLoc)
478 {
479 const CXXRecordDecl *CXXRD = TyLoc.getDecl();
480 TransAssert(CXXRD && "Invalid CXXRecordDecl!");
481
482 std::string Name;
483 if (ConsumerInstance->getNewName(CXXRD, Name)) {
484 SourceLocation LocStart = TyLoc.getBeginLoc();
485 TransAssert(LocStart.isValid() && "Invalid Location!");
486
487 ConsumerInstance->TheRewriter.ReplaceText(
488 LocStart, CXXRD->getNameAsString().size(), Name);
489 }
490 return true;
491 }
492
493 bool RemoveNamespaceRewriteVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TyLoc)
494 {
495 const TypedefNameDecl *D = TyLoc.getTypedefNameDecl();
496
497 std::string Name;
498 if (ConsumerInstance->getNewName(D, Name)) {
499 SourceLocation LocStart = TyLoc.getBeginLoc();
500 ConsumerInstance->TheRewriter.ReplaceText(
501 LocStart, D->getNameAsString().size(), Name);
502 }
503 return true;
504 }
505
506 bool RemoveNamespaceRewriteVisitor::VisitEnumTypeLoc(EnumTypeLoc TyLoc)
507 {
508 const EnumDecl *D = TyLoc.getDecl();
509
510 std::string Name;
511 if (ConsumerInstance->getNewName(D, Name)) {
512 SourceLocation LocStart = TyLoc.getBeginLoc();
513 ConsumerInstance->TheRewriter.ReplaceText(
514 LocStart, D->getNameAsString().size(), Name);
515 }
516 return true;
517 }
518
519 // It handles two cases:
520 // * remove the specifier if it refers to TheNamespaceDecl
521 // * replace the specifier with a new name if the corresponding namespace
522 // has a name conflicts, e.g.,
523 // namespace NS1 { }
524 // namespace NS2 {
525 // namespace NS1 {
526 // void foo() {}
527 // }
528 // namespace NS3 {
529 // using NS1::foo;
530 // void bar() { foo(); }
531 // }
532 // }
533 // If we remove NS2, then the inner namespace NS1 conflicts with
534 // the global NS1, but "using NS1::foo" refers to the conflicting NS1.
535 bool RemoveNamespaceRewriteVisitor::TraverseNestedNameSpecifierLoc(
536 NestedNameSpecifierLoc QualifierLoc)
537 {
538 SkipRewriteName = false;
539 // Reset the flag
540 if (SkipTraverseNestedNameSpecifier) {
541 SkipTraverseNestedNameSpecifier = false;
542 return true;
543 }
544
545 if (!QualifierLoc || QualifierLoc.getBeginLoc().isInvalid())
546 return true;
547
548 SmallVector<NestedNameSpecifierLoc, 8> QualifierLocs;
549 for (; QualifierLoc; QualifierLoc = QualifierLoc.getPrefix())
550 QualifierLocs.push_back(QualifierLoc);
551
552 while (!QualifierLocs.empty()) {
553 NestedNameSpecifierLoc Loc = QualifierLocs.pop_back_val();
554 NestedNameSpecifier *NNS = Loc.getNestedNameSpecifier();
555 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
556 const NamespaceDecl *ND = NULL;
557
558 switch (Kind) {
559 case NestedNameSpecifier::Namespace: {
560 ND = NNS->getAsNamespace()->getCanonicalDecl();
561 break;
562 }
563 case NestedNameSpecifier::NamespaceAlias: {
564 const NamespaceAliasDecl *NAD = NNS->getAsNamespaceAlias();
565 if (!NAD->getQualifier())
566 ND = NAD->getNamespace()->getCanonicalDecl();
567 break;
568 }
•569 #if LLVM_VERSION_MAJOR < 21
570 case NestedNameSpecifier::TypeSpecWithTemplate: // Fall-through
571 #endif
572 case NestedNameSpecifier::TypeSpec:
573 TraverseTypeLoc(Loc.getTypeLoc());
574 break;
575 default:
576 break;
577 }
578
579 if (!ND)
580 continue;
581
582 if (ND == ConsumerInstance->TheNamespaceDecl) {
583 ConsumerInstance->RewriteHelper->removeSpecifier(Loc);
584 continue;
585 }
586
587 std::string SpecifierName;
588 if (Loc.getBeginLoc().isInvalid())
589 continue;
590
591 ConsumerInstance->RewriteHelper->getSpecifierAsString(Loc, SpecifierName);
592 std::string NDName = ND->getNameAsString();
593 std::string Name = "";
594 ConsumerInstance->getNewName(ND, Name);
595
596 // Skip it if this specifier is the same as ND's name.
597 // Note that the above case could only happen for UsingNamedDecls
598 if (ConsumerInstance->isForUsingNamedDecls && (SpecifierName == NDName)) {
599 // It could happen for example:
600 // namespace NS1 { }
601 // namespace NS2 {
602 // using namespace NS1;
603 // void bar() { NS1::foo(); }
604 // }
605 // If we remove NS2, then the guard below avoids renaming
606 // NS1::foo to NS1::foo::foo.
607 if (Name.empty()) {
608 SkipRewriteName = true;
609 return true;
610 }
611
612 // another case to handle:
613 // namespace NS1 {
614 // namespace NS2 {
615 // void foo() {}
616 // }
617 // }
618 // namespace NS3 {
619 // using namespace NS1;
620 // void bar() { NS2::foo(); }
621 // }
622 // If we remove NS3, we do need to rename NS2::foo as NS1::NS2::foo
623 if (!ConsumerInstance->isSuffix(Name, SpecifierName)) {
624 SkipRewriteName = true;
625 return true;
626 }
627 }
628
629 if (!Name.empty()) {
630 ConsumerInstance->RewriteHelper->replaceSpecifier(Loc, Name);
631 SkipRewriteName = true;
632 return true;
633 }
634 }
635 return true;
636 }
637
638 void RemoveNamespace::Initialize(ASTContext &context)
639 {
640 Transformation::Initialize(context);
641 CollectionVisitor = new RemoveNamespaceASTVisitor(this);
642 RewriteVisitor = new RemoveNamespaceRewriteVisitor(this);
643 }
644
645 bool RemoveNamespace::HandleTopLevelDecl(DeclGroupRef D)
646 {
647 // Nothing to do
648 return true;
649 }
650
651 void RemoveNamespace::HandleTranslationUnit(ASTContext &Ctx)
652 {
653 if (TransformationManager::isCLangOpt()) {
654 ValidInstanceNum = 0;
655 }
656 else {
657 // Invoke CollectionVisitor here because we need full DeclContext
658 // to resolve name conflicts. Full ASTs has been built at this point.
659 CollectionVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
660 }
661
662 if (QueryInstanceOnly)
663 return;
664
665 if (TransformationCounter > ValidInstanceNum) {
666 TransError = TransMaxInstanceError;
667 return;
668 }
669
670 TransAssert(RewriteVisitor && "NULL RewriteVisitor!");
671 TransAssert(TheNamespaceDecl && "NULL TheNamespaceDecl!");
672 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
673
674 // First rename UsingNamedDecls, i.e., conflicting names
675 // from other namespaces.
676 // FIXME: isForUsingNamedDecls flag is quite ugly,
677 // need a way to remove it
678 isForUsingNamedDecls = true;
679 RewriteVisitor->TraverseDecl(TheNamespaceDecl);
680 isForUsingNamedDecls = false;
681
682 rewriteNamedDecls();
683 RewriteVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
684
685 if (Ctx.getDiagnostics().hasErrorOccurred() ||
686 Ctx.getDiagnostics().hasFatalErrorOccurred())
687 TransError = TransInternalError;
688 }
689
690 void RemoveNamespace::rewriteNamedDecls(void)
691 {
692 for (NamedDeclToNameMap::const_iterator I = NamedDeclToNewName.begin(),
693 E = NamedDeclToNewName.end(); I != E; ++I) {
694 const NamedDecl *D = (*I).first;
695 std::string Name = (*I).second;
696
697 Decl::Kind K = D->getKind();
698 switch (K) {
699 case Decl::Function:
700 case Decl::CXXMethod: {
701 // Check replaceFunctionDecl in RewriteUtils.cpp for the reason that
702 // we need a special case for FunctionDecl
703 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
704 RewriteHelper->replaceFunctionDeclName(FD, Name);
705 break;
706 }
707 case Decl::ClassTemplateSpecialization: {
708 // Skip this case, which will be handled by
709 // VisitTemplateSpecializationTypeLoc
710 break;
711 }
712 default:
713 RewriteHelper->replaceNamedDeclName(D, Name);
714 }
715 }
716 }
717
718 bool RemoveNamespace::isValidNamedDeclKind(const NamedDecl *ND)
719 {
720 return (isa<TemplateDecl>(ND) || isa<TypeDecl>(ND) ||
721 isa<ValueDecl>(ND) || isa<NamespaceDecl>(ND) ||
722 isa<NamespaceAliasDecl>(ND));
723 }
724
725 bool RemoveNamespace::hasNameConflict(const NamedDecl *ND,
726 const DeclContext *ParentCtx)
727 {
728 // we cannot lookup names from LinkageSpecDecl, e.g.,
729 // extern "C++" { ... }
730 if (dyn_cast<LinkageSpecDecl>(ParentCtx))
731 return false;
732
733 DeclarationName Name = ND->getDeclName();
734 DeclContext::lookup_result Result = ParentCtx->lookup(Name);
735 return !Result.empty();
736 }
737
738 // We always prepend the Prefix string to EnumConstantDecl if ParentCtx
739 // is NULL
740 void RemoveNamespace::handleOneEnumDecl(const EnumDecl *ED,
741 const std::string &Prefix,
742 NamedDeclToNameMap &NameMap,
743 const DeclContext *ParentCtx)
744 {
745 for (EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
746 E = ED->enumerator_end(); I != E; ++I) {
747 EnumConstantDecl *ECD = (*I);
748 if (!ParentCtx || hasNameConflict(ECD, ParentCtx)) {
749 const IdentifierInfo *IdInfo = ECD->getIdentifier();
750 std::string NewName = Prefix;
751 NewName += IdInfo->getName();
752 NameMap[ECD] = NewName;
753 }
754 }
755 }
756
757 // A using declaration in the removed namespace could cause
758 // name conflict, e.g.,
759 // namespace NS1 {
760 // void foo(void) {}
761 // }
762 // namespace NS2 {
763 // using NS1::foo;
764 // void bar() { ... foo(); ... }
765 // }
766 // void foo() {...}
767 // void func() {... foo(); ...}
768 // if we remove NS2, then foo() in func() will become ambiguous.
769 // In this case, we need to replace the first invocation of foo()
770 // with NS1::foo()
771 void RemoveNamespace::handleOneUsingShadowDecl(const UsingShadowDecl *UD,
772 const DeclContext *ParentCtx)
773 {
774 const NamedDecl *ND = UD->getTargetDecl();
775 if (!hasNameConflict(ND, ParentCtx))
776 return;
777
778 std::string NewName;
779 const BaseUsingDecl *BD = UD->getIntroducer();
780 const UsingDecl *D = dyn_cast<UsingDecl>(BD);
781 if (!D)
782 return;
783
784 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
785 NestedNameSpecifier *NNS = QualifierLoc.getNestedNameSpecifier();
786
787 // QualifierLoc could be ::foo, whose PrefixLoc is invalid, e.g.,
788 // void foo();
789 // namespace NS2 {
790 // using ::foo;
791 // void bar () { foo(); }
792 // }
793 if (NNS->getKind() != NestedNameSpecifier::Global) {
794 // NestedNameSpecifierLoc PrefixLoc = QualifierLoc.getPrefix();
795 RewriteHelper->getQualifierAsString(QualifierLoc, NewName);
796 }
797
798 if ( const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND) ) {
799 ND = TD->getTemplatedDecl();
800 }
801
802 // NewName += "::";
803 const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
804 if (FD && FD->isOverloadedOperator()) {
805 const char *Op = clang::getOperatorSpelling(FD->getOverloadedOperator());
806 std::string OpStr(Op);
807 NewName += ("operator::" + OpStr);
808 }
809 else {
810 const IdentifierInfo *IdInfo = ND->getIdentifier();
811 TransAssert(IdInfo && "Invalid IdentifierInfo!");
812 NewName += IdInfo->getName();
813 }
814 UsingNamedDeclToNewName[ND] = NewName;
815
816 // the tied UsingDecl becomes useless, and hence it's removable
817 UselessUsingDecls.insert(D);
818 }
819
820 // For the similar reason as dealing with using declarations,
821 // we need to resolve the possible name conflicts introduced by
822 // using directives
823 void RemoveNamespace::handleOneUsingDirectiveDecl(const UsingDirectiveDecl *UD,
824 const DeclContext *ParentCtx)
825 {
826 const NamespaceDecl *ND = UD->getNominatedNamespace();
827
828 // It could happen, for example:
829 // namespace NS {
830 // namespace {
831 // int x;
832 // }
833 // }
834 // where the inner anonymous namespace will have an implicit using directive
835 // declaration
836 if (ND->isAnonymousNamespace())
837 return;
838
839 std::string NamespaceName = ND->getNameAsString();
840
841 for (DeclContext::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
842 I != E; ++I) {
843 const NamedDecl *NamedD = dyn_cast<NamedDecl>(*I);
844 if (!NamedD)
845 continue;
846
847 if (!isValidNamedDeclKind(NamedD))
848 continue;
849
850 std::string NewName = "";
851 if ( NestedNameSpecifierLoc QualifierLoc = UD->getQualifierLoc() ) {
852 RewriteHelper->getQualifierAsString(QualifierLoc, NewName);
853 }
854 NewName += NamespaceName;
855 NewName += "::";
856
857 if ( const TemplateDecl *TD = dyn_cast<TemplateDecl>(NamedD) ) {
858 NamedD = TD->getTemplatedDecl();
859 }
860 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(NamedD)) {
861 handleOneEnumDecl(ED, NewName, UsingNamedDeclToNewName, NULL);
862 }
863 const FunctionDecl *FD = dyn_cast<FunctionDecl>(NamedD);
864 if (FD && FD->isOverloadedOperator()) {
865 const char *Op = clang::getOperatorSpelling(FD->getOverloadedOperator());
866 std::string OpStr(Op);
867 NewName += ("operator::" + OpStr);
868 }
869 else {
870 const IdentifierInfo *IdInfo = NamedD->getIdentifier();
871 if (!IdInfo)
872 continue;
873 NewName += IdInfo->getName();
874 }
875 UsingNamedDeclToNewName[NamedD] = NewName;
876 }
877
878 // We always remove this using directive, and in ThenNamespaceDecl
879 // append the corresponding namespace specifier to all names from the
880 // used namespace. The reason is that the conlicted name in the outter
881 // namespace could appear after TheNamespaceDecl, e.g.,
882 // namespace NS1 {
883 // void foo() {}
884 // void fiz() {}
885 // }
886 // namespace NS2 {
887 // using namespace NS1;
888 // int bar() { foo(); }
889 // }
890 // void fiz() {}
891 // void f() { fiz(); }
892 // If we keep "using namespace NS1" after removing NS2, then we will
893 // end up with an ambiguous name fiz
894 // Consequently, we will add a few unecessary namespace qualifiers to
895 // those without conflicting names. It's a trade-off.
896 UselessUsingDirectiveDecls.insert(UD);
897 }
898
899 void RemoveNamespace::handleOneNamedDecl(const NamedDecl *ND,
900 const DeclContext *ParentCtx,
901 const std::string &NamespaceName)
902 {
903 Decl::Kind K = ND->getKind();
904 switch (K) {
905 case Decl::UsingShadow: {
906 const UsingShadowDecl *D = dyn_cast<UsingShadowDecl>(ND);
907 handleOneUsingShadowDecl(D, ParentCtx);
908 return;
909 }
910
911 case Decl::UsingDirective: {
912 const UsingDirectiveDecl *D = dyn_cast<UsingDirectiveDecl>(ND);
913 handleOneUsingDirectiveDecl(D, ParentCtx);
914 return;
915 }
916
917 default:
918 if (!isValidNamedDeclKind(ND))
919 return;
920
921 if (!hasNameConflict(ND, ParentCtx))
922 return;
923
924 std::string NewName = NamePrefix + NamespaceName;
925 NewName += "_";
926
927 if ( const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND) ) {
928 ND = TD->getTemplatedDecl();
929 }
930 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(ND)) {
931 handleOneEnumDecl(ED, NewName, NamedDeclToNewName, ParentCtx);
932 }
933
934 // This is bad. Any better solution? Maybe we need to change
935 // the overloaded operator to a regular function?
936 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
937 if (FD->isOverloadedOperator())
938 return;
939 }
940
941 const IdentifierInfo *IdInfo = ND->getIdentifier();
942 bool IsUserLiteral = false;
943 if (!IdInfo) {
944 const FunctionDecl *FD = cast<FunctionDecl>(ND);
945 IdInfo = FD->getLiteralIdentifier();
946 if (IdInfo)
947 IsUserLiteral = true;
948 }
949
950 TransAssert(IdInfo && "Invalid IdentifierInfo!");
951 NewName += IdInfo->getName();
952 // Make sure we have valid suffix for user literals
•953 #if LLVM_VERSION_MAJOR < 18
954 if (IsUserLiteral && IdInfo->getName().startswith("_")) {
•955 #else
956 if (IsUserLiteral && IdInfo->getName().starts_with("_")) {
957 #endif
958 NewName = "_" + NewName;
959 }
960 NamedDeclToNewName[ND] = NewName;
961 }
962 }
963
964 void RemoveNamespace::addNamedDeclsFromNamespace(const NamespaceDecl *ND)
965 {
966 // We don't care about name-lookup for friend's functions, so just
967 // retrive ParentContext rather than LookupParent
968 const DeclContext *ParentCtx = ND->getParent();
969 std::string NamespaceName;
970
971 if (ND->isAnonymousNamespace()) {
972 std::stringstream TmpSS;
973 TmpSS << AnonNamePrefix << AnonNamespaceCounter;
974 NamespaceName = TmpSS.str();
975 AnonNamespaceCounter++;
976 }
977 else {
978 NamespaceName = ND->getNameAsString();
979 }
980
981 for (DeclContext::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
982 I != E; ++I) {
983 if ( const NamedDecl *D = dyn_cast<NamedDecl>(*I) )
984 handleOneNamedDecl(D, ParentCtx, NamespaceName);
985 }
986 }
987
988 bool RemoveNamespace::handleOneNamespaceDecl(NamespaceDecl *ND)
989 {
990 if (isInIncludedFile(ND))
991 return true;
992
993 NamespaceDecl *CanonicalND = ND->getCanonicalDecl();
994 if (VisitedND.count(CanonicalND)) {
995 if (TheNamespaceDecl == CanonicalND) {
996 addNamedDeclsFromNamespace(ND);
997 }
998 return true;
999 }
1000
1001 VisitedND.insert(CanonicalND);
1002 ValidInstanceNum++;
1003 if (ValidInstanceNum == TransformationCounter) {
1004 TheNamespaceDecl = CanonicalND;
1005 addNamedDeclsFromNamespace(ND);
1006 }
1007 return true;
1008 }
1009
1010 void RemoveNamespace::removeNamespace(const NamespaceDecl *ND)
1011 {
1012 // Remove the right brace first
1013 SourceLocation RBLoc = ND->getRBraceLoc();
1014 if (RBLoc.isValid()) {
1015 if (RBLoc.isMacroID()) {
1016 TheRewriter.RemoveText(SrcManager->getExpansionRange(RBLoc).getAsRange());
1017 }
1018 else {
1019 TheRewriter.RemoveText(RBLoc, 1);
1020 }
1021 }
1022
1023 // Then remove name and the left brace
1024 SourceLocation StartLoc = ND->getBeginLoc();
1025 TransAssert(StartLoc.isValid() && "Invalid Namespace LocStart!");
1026
1027 StartLoc = SrcManager->getFileLoc(StartLoc);
1028 SourceLocation EndLoc;
1029 if (ND->decls_empty()) {
1030 EndLoc = SrcManager->getFileLoc(RBLoc);
1031 }
1032 else {
1033 DeclContext::decl_iterator I = ND->decls_begin();
1034 EndLoc = SrcManager->getFileLoc(dyn_cast<Decl>(*I)->getBeginLoc());
1035 }
1036
1037 if (StartLoc != EndLoc) {
1038 EndLoc = EndLoc.getLocWithOffset(-1);
1039 SourceRange NewRange(StartLoc, EndLoc);
1040 int RangeSize = TheRewriter.getRangeSize(NewRange);
1041 TransAssert((RangeSize != -1) && "Bad Namespace Range!");
1042 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
1043 std::string NDStr(StartBuf, RangeSize);
1044 size_t Pos = NDStr.find('{');
1045 if (Pos != std::string::npos)
1046 EndLoc = StartLoc.getLocWithOffset(Pos);
1047 }
1048
1049 TheRewriter.RemoveText(SourceRange(StartLoc, EndLoc));
1050 }
1051
1052 bool RemoveNamespace::getNewNameFromNameMap(const NamedDecl *ND,
1053 std::string &Name,
1054 const NamedDeclToNameMap &NameMap)
1055 {
1056 NamedDeclToNameMap::const_iterator Pos =
1057 NameMap.find(ND);
1058 if (Pos == NameMap.end())
1059 return false;
1060
1061 Name = (*Pos).second;
1062 return true;
1063 }
1064
1065 bool RemoveNamespace::getNewNameByNameFromNameMap(const std::string &Name,
1066 std::string &NewName,
1067 const NamedDeclToNameMap &NameMap)
1068 {
1069 for (NamedDeclToNameMap::const_iterator I = NameMap.begin(),
1070 E = NameMap.end(); I != E; ++I) {
1071 const NamedDecl *D = (*I).first;
1072 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(D);
1073 if (!CXXRD)
1074 continue;
1075 if (Name == CXXRD->getNameAsString()) {
1076 NewName = (*I).second;
1077 return true;
1078 }
1079 }
1080 return false;
1081 }
1082
1083 bool RemoveNamespace::getNewNamedDeclName(const NamedDecl *ND,
1084 std::string &Name)
1085 {
1086 return getNewNameFromNameMap(ND, Name, NamedDeclToNewName);
1087 }
1088
1089 bool RemoveNamespace::getNewUsingNamedDeclName(const NamedDecl *ND,
1090 std::string &Name)
1091 {
1092 return getNewNameFromNameMap(ND, Name, UsingNamedDeclToNewName);
1093 }
1094
1095 bool RemoveNamespace::getNewName(const NamedDecl *ND,
1096 std::string &Name)
1097 {
1098 if (isForUsingNamedDecls)
1099 return getNewUsingNamedDeclName(ND, Name);
1100 else
1101 return getNewNamedDeclName(ND, Name);
1102 }
1103
1104 bool RemoveNamespace::getNewNameByName(const std::string &Name,
1105 std::string &NewName)
1106 {
1107 if (isForUsingNamedDecls)
1108 return getNewNameByNameFromNameMap(Name, NewName, UsingNamedDeclToNewName);
1109 else
1110 return getNewNameByNameFromNameMap(Name, NewName, NamedDeclToNewName);
1111 }
1112
1113 bool RemoveNamespace::isGlobalNamespace(NestedNameSpecifierLoc Loc)
1114 {
1115 NestedNameSpecifier *NNS = Loc.getNestedNameSpecifier();
1116 return (NNS->getKind() == NestedNameSpecifier::Global);
1117 }
1118
1119 bool RemoveNamespace::isTheNamespaceSpecifier(const NestedNameSpecifier *NNS)
1120 {
1121 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
1122 switch (Kind) {
1123 case NestedNameSpecifier::Namespace: {
1124 const NamespaceDecl *CanonicalND =
1125 NNS->getAsNamespace()->getCanonicalDecl();
1126 return (CanonicalND == TheNamespaceDecl);
1127 }
1128
1129 case NestedNameSpecifier::NamespaceAlias: {
1130 const NamespaceAliasDecl *NAD = NNS->getAsNamespaceAlias();
1131 // we remove the namealias only when it doesn't have nestedspecifier
1132 if (NAD->getQualifier())
1133 return false;
1134 const NamespaceDecl *CanonicalND =
1135 NAD->getNamespace()->getCanonicalDecl();
1136 return (CanonicalND == TheNamespaceDecl);
1137 }
1138
1139 default:
1140 return false;
1141 }
1142 TransAssert(0 && "Unreachable code!");
1143 return false;
1144 }
1145
1146 bool RemoveNamespace::isSuffix(std::string &Name, std::string &SpecifierName)
1147 {
1148 size_t NameLen = Name.length();
1149 std::string Suffix = "::" + SpecifierName;
1150 size_t SuffixLen = Suffix.length();
1151 if (NameLen <= SuffixLen)
1152 return false;
1153
1154 return !Suffix.compare(0, SuffixLen, Name, NameLen - SuffixLen, SuffixLen);
1155 }
1156
1157 void RemoveNamespace::replaceFirstNamespaceFromUsingDecl(
1158 const UsingDirectiveDecl *D, const std::string &Name)
1159 {
1160 const NamespaceDecl *ND = D->getNominatedNamespace();
1161 SourceLocation IdLocStart = D->getIdentLocation();
1162 TheRewriter.ReplaceText(IdLocStart, ND->getNameAsString().length(), Name);
1163 }
1164
1165 void RemoveNamespace::removeLastNamespaceFromUsingDecl(
1166 const UsingDirectiveDecl *D, const NamespaceDecl *ND)
1167 {
1168 SourceLocation IdLocStart = D->getIdentLocation();
1169 SourceRange DeclSourceRange = D->getSourceRange();
1170 SourceLocation DeclLocStart = DeclSourceRange.getBegin();
1171
1172 const char *IdStartBuf = SrcManager->getCharacterData(IdLocStart);
1173 const char *DeclStartBuf = SrcManager->getCharacterData(DeclLocStart);
1174
1175 unsigned Count = 0;
1176 int Offset = 0;
1177 while (IdStartBuf != DeclStartBuf) {
1178 if (*IdStartBuf != ':') {
1179 IdStartBuf--;
1180 Offset--;
1181 continue;
1182 }
1183
1184 Count++;
1185 if (Count == 2) {
1186 break;
1187 }
1188 Offset--;
1189 IdStartBuf--;
1190 }
1191 TransAssert((Count == 2) && "Bad NestedNamespaceSpecifier!");
1192 TransAssert((Offset < 0) && "Bad Offset Value!");
1193 IdLocStart = IdLocStart.getLocWithOffset(Offset);
1194
1195 TheRewriter.RemoveText(IdLocStart,
1196 ND->getNameAsString().length() - Offset);
1197 }
1198
1199 RemoveNamespace::~RemoveNamespace(void)
1200 {
1201 delete CollectionVisitor;
1202 delete RewriteVisitor;
1203 }
1204