Skip to content

Commit 9bccaa1

Browse files
committed
[Tooling] Add a utility function to replace one nested name with another.
One problem in clang-tidy and other clang tools face is that there is no way to lookup an arbitrary name in the AST, that's buried deep inside Sema and might not even be what the user wants as the new name may be freshly inserted and not available in the AST. A common use case for lookups is replacing one nested name with another while minimizing namespace qualifications, so replacing 'ns::foo' with 'ns::bar' will use just 'bar' if we happen to be inside the namespace 'ns'. This adds a little helper utility for exactly that use case. Differential Revision: http://reviews.llvm.org/D13931 llvm-svn: 251022
1 parent 8f9e444 commit 9bccaa1

File tree

5 files changed

+271
-0
lines changed

5 files changed

+271
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//===--- Lookup.h - Framework for clang refactoring tools --*- C++ -*------===//
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+
//
10+
// This file defines helper methods for clang tools performing name lookup.
11+
//
12+
//===----------------------------------------------------------------------===//
13+
14+
#ifndef LLVM_CLANG_TOOLING_CORE_LOOKUP_H
15+
#define LLVM_CLANG_TOOLING_CORE_LOOKUP_H
16+
17+
#include "clang/Basic/LLVM.h"
18+
#include <string>
19+
20+
namespace clang {
21+
22+
class DeclContext;
23+
class NamedDecl;
24+
class NestedNameSpecifier;
25+
26+
namespace tooling {
27+
28+
/// Emulate a lookup to replace one nested name specifier with another using as
29+
/// few additional namespace qualifications as possible.
30+
///
31+
/// This does not perform a full C++ lookup so ADL will not work.
32+
///
33+
/// \param Use The nested name to be replaced.
34+
/// \param UseContext The context in which the nested name is contained. This
35+
/// will be used to minimize namespace qualifications.
36+
/// \param FromDecl The declaration to which the nested name points.
37+
/// \param ReplacementString The replacement nested name. Must be fully
38+
/// qualified including a leading "::".
39+
/// \returns The new name to be inserted in place of the current nested name.
40+
std::string replaceNestedName(const NestedNameSpecifier *Use,
41+
const DeclContext *UseContext,
42+
const NamedDecl *FromDecl,
43+
StringRef ReplacementString);
44+
45+
} // end namespace tooling
46+
} // end namespace clang
47+
48+
#endif // LLVM_CLANG_TOOLING_CORE_LOOKUP_H

clang/lib/Tooling/Core/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
set(LLVM_LINK_COMPONENTS support)
22

33
add_clang_library(clangToolingCore
4+
Lookup.cpp
45
Replacement.cpp
56

67
LINK_LIBS

clang/lib/Tooling/Core/Lookup.cpp

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
//===--- Lookup.cpp - Framework for clang refactoring tools ---------------===//
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+
//
10+
// This file defines helper methods for clang tools performing name lookup.
11+
//
12+
//===----------------------------------------------------------------------===//
13+
14+
#include "clang/Tooling/Core/Lookup.h"
15+
#include "clang/AST/Decl.h"
16+
using namespace clang;
17+
using namespace clang::tooling;
18+
19+
static bool isInsideDifferentNamespaceWithSameName(const DeclContext *DeclA,
20+
const DeclContext *DeclB) {
21+
while (true) {
22+
// Look past non-namespaces on DeclA.
23+
while (DeclA && !isa<NamespaceDecl>(DeclA))
24+
DeclA = DeclA->getParent();
25+
26+
// Look past non-namespaces on DeclB.
27+
while (DeclB && !isa<NamespaceDecl>(DeclB))
28+
DeclB = DeclB->getParent();
29+
30+
// We hit the root, no namespace collision.
31+
if (!DeclA || !DeclB)
32+
return false;
33+
34+
// Literally the same namespace, not a collision.
35+
if (DeclA == DeclB)
36+
return false;
37+
38+
// Now check the names. If they match we have a different namespace with the
39+
// same name.
40+
if (cast<NamespaceDecl>(DeclA)->getDeclName() ==
41+
cast<NamespaceDecl>(DeclB)->getDeclName())
42+
return true;
43+
44+
DeclA = DeclA->getParent();
45+
DeclB = DeclB->getParent();
46+
}
47+
}
48+
49+
static StringRef getBestNamespaceSubstr(const DeclContext *DeclA,
50+
StringRef NewName,
51+
bool HadLeadingColonColon) {
52+
while (true) {
53+
while (DeclA && !isa<NamespaceDecl>(DeclA))
54+
DeclA = DeclA->getParent();
55+
56+
// Fully qualified it is! Leave :: in place if it's there already.
57+
if (!DeclA)
58+
return HadLeadingColonColon ? NewName : NewName.substr(2);
59+
60+
// Otherwise strip off redundant namespace qualifications from the new name.
61+
// We use the fully qualified name of the namespace and remove that part
62+
// from NewName if it has an identical prefix.
63+
std::string NS =
64+
"::" + cast<NamespaceDecl>(DeclA)->getQualifiedNameAsString() + "::";
65+
if (NewName.startswith(NS))
66+
return NewName.substr(NS.size());
67+
68+
// No match yet. Strip of a namespace from the end of the chain and try
69+
// again. This allows to get optimal qualifications even if the old and new
70+
// decl only share common namespaces at a higher level.
71+
DeclA = DeclA->getParent();
72+
}
73+
}
74+
75+
/// Check if the name specifier begins with a written "::".
76+
static bool isFullyQualified(const NestedNameSpecifier *NNS) {
77+
while (NNS) {
78+
if (NNS->getKind() == NestedNameSpecifier::Global)
79+
return true;
80+
NNS = NNS->getPrefix();
81+
}
82+
return false;
83+
}
84+
85+
std::string tooling::replaceNestedName(const NestedNameSpecifier *Use,
86+
const DeclContext *UseContext,
87+
const NamedDecl *FromDecl,
88+
StringRef ReplacementString) {
89+
assert(ReplacementString.startswith("::") &&
90+
"Expected fully-qualified name!");
91+
92+
// We can do a raw name replacement when we are not inside the namespace for
93+
// the original function and it is not in the global namespace. The
94+
// assumption is that outside the original namespace we must have a using
95+
// statement that makes this work out and that other parts of this refactor
96+
// will automatically fix using statements to point to the new function
97+
const bool class_name_only = !Use;
98+
const bool in_global_namespace =
99+
isa<TranslationUnitDecl>(FromDecl->getDeclContext());
100+
if (class_name_only && !in_global_namespace &&
101+
!isInsideDifferentNamespaceWithSameName(FromDecl->getDeclContext(),
102+
UseContext)) {
103+
auto Pos = ReplacementString.rfind("::");
104+
return Pos != StringRef::npos ? ReplacementString.substr(Pos + 2)
105+
: ReplacementString;
106+
}
107+
// We did not match this because of a using statement, so we will need to
108+
// figure out how good a namespace match we have with our destination type.
109+
// We work backwards (from most specific possible namespace to least
110+
// specific).
111+
return getBestNamespaceSubstr(UseContext, ReplacementString,
112+
isFullyQualified(Use));
113+
}

clang/unittests/Tooling/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ set(LLVM_LINK_COMPONENTS
66
add_clang_unittest(ToolingTests
77
CommentHandlerTest.cpp
88
CompilationDatabaseTest.cpp
9+
LookupTest.cpp
910
ToolingTest.cpp
1011
RecursiveASTVisitorTest.cpp
1112
RecursiveASTVisitorTestCallVisitor.cpp
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
//===- unittest/Tooling/LookupTest.cpp ------------------------------------===//
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+
10+
#include "TestVisitor.h"
11+
#include "clang/Tooling/Core/Lookup.h"
12+
using namespace clang;
13+
14+
namespace {
15+
struct GetDeclsVisitor : TestVisitor<GetDeclsVisitor> {
16+
std::function<void(CallExpr *)> OnCall;
17+
SmallVector<Decl *, 4> DeclStack;
18+
19+
bool VisitCallExpr(CallExpr *Expr) {
20+
OnCall(Expr);
21+
return true;
22+
}
23+
24+
bool TraverseDecl(Decl *D) {
25+
DeclStack.push_back(D);
26+
bool Ret = TestVisitor::TraverseDecl(D);
27+
DeclStack.pop_back();
28+
return Ret;
29+
}
30+
};
31+
32+
TEST(LookupTest, replaceNestedName) {
33+
GetDeclsVisitor Visitor;
34+
35+
auto replaceCallExpr = [&](const CallExpr *Expr,
36+
StringRef ReplacementString) {
37+
const auto *Callee = cast<DeclRefExpr>(Expr->getCallee()->IgnoreImplicit());
38+
const ValueDecl *FD = Callee->getDecl();
39+
return tooling::replaceNestedName(
40+
Callee->getQualifier(), Visitor.DeclStack.back()->getDeclContext(), FD,
41+
ReplacementString);
42+
};
43+
44+
Visitor.OnCall = [&](CallExpr *Expr) {
45+
EXPECT_EQ("bar", replaceCallExpr(Expr, "::bar"));
46+
};
47+
Visitor.runOver("namespace a { void foo(); }\n"
48+
"namespace a { void f() { foo(); } }\n");
49+
50+
Visitor.OnCall = [&](CallExpr *Expr) {
51+
EXPECT_EQ("bar", replaceCallExpr(Expr, "::a::bar"));
52+
};
53+
Visitor.runOver("namespace a { void foo(); }\n"
54+
"namespace a { void f() { foo(); } }\n");
55+
56+
Visitor.OnCall = [&](CallExpr *Expr) {
57+
EXPECT_EQ("a::bar", replaceCallExpr(Expr, "::a::bar"));
58+
};
59+
Visitor.runOver("namespace a { void foo(); }\n"
60+
"namespace b { void f() { a::foo(); } }\n");
61+
62+
Visitor.OnCall = [&](CallExpr *Expr) {
63+
EXPECT_EQ("a::bar", replaceCallExpr(Expr, "::a::bar"));
64+
};
65+
Visitor.runOver("namespace a { void foo(); }\n"
66+
"namespace b { namespace a { void foo(); }\n"
67+
"void f() { a::foo(); } }\n");
68+
69+
Visitor.OnCall = [&](CallExpr *Expr) {
70+
EXPECT_EQ("c::bar", replaceCallExpr(Expr, "::a::c::bar"));
71+
};
72+
Visitor.runOver("namespace a { namespace b { void foo(); }\n"
73+
"void f() { b::foo(); } }\n");
74+
75+
Visitor.OnCall = [&](CallExpr *Expr) {
76+
EXPECT_EQ("bar", replaceCallExpr(Expr, "::a::bar"));
77+
};
78+
Visitor.runOver("namespace a { namespace b { void foo(); }\n"
79+
"void f() { b::foo(); } }\n");
80+
81+
Visitor.OnCall = [&](CallExpr *Expr) {
82+
EXPECT_EQ("bar", replaceCallExpr(Expr, "::bar"));
83+
};
84+
Visitor.runOver("void foo(); void f() { foo(); }\n");
85+
86+
Visitor.OnCall = [&](CallExpr *Expr) {
87+
EXPECT_EQ("::bar", replaceCallExpr(Expr, "::bar"));
88+
};
89+
Visitor.runOver("void foo(); void f() { ::foo(); }\n");
90+
91+
Visitor.OnCall = [&](CallExpr *Expr) {
92+
EXPECT_EQ("a::bar", replaceCallExpr(Expr, "::a::bar"));
93+
};
94+
Visitor.runOver("namespace a { void foo(); }\nvoid f() { a::foo(); }\n");
95+
96+
Visitor.OnCall = [&](CallExpr *Expr) {
97+
EXPECT_EQ("a::bar", replaceCallExpr(Expr, "::a::bar"));
98+
};
99+
Visitor.runOver("namespace a { int foo(); }\nauto f = a::foo();\n");
100+
101+
Visitor.OnCall = [&](CallExpr *Expr) {
102+
EXPECT_EQ("bar", replaceCallExpr(Expr, "::a::bar"));
103+
};
104+
Visitor.runOver(
105+
"namespace a { int foo(); }\nusing a::foo;\nauto f = foo();\n");
106+
}
107+
108+
} // end anonymous namespace

0 commit comments

Comments
 (0)