QualType question

I’m trying to refactor in C++:

using namespace std;
string sp = " ";

into

std::string sp = " ";

However when I examine the VarDecl node it is not obvious how to get to the namespace the “typedef sting” is declared in.

My code gets the QualType, in QT from the VarDecl then the trouble starts:

** QT.getAsString() = string
** QT.getCanonicalType().getAsString() = class std::__cxx11::basic_string
** QT.getUnqualifiedType().getAsString() = string
** ds.getAsString() = basic_string
** QT.getBaseTypeIdentifier() = basic_string
** VarDecl: string sp = " "

below is the code, but the problem seems to be I cannot bind to a declaration of the typedef. Any suggestions or code to look at that does this would be most appreciated. Thanks!

Code that dumped the above:

/// Handle types in variable declarations
/// string s;
/// becomes
/// std::string s;
void UsingCheck::handleVarDecl(
const clang::ast_matchers::MatchFinder::MatchResult &Result) {
const VarDecl *VD = Result.Nodes.getNodeAs(“varDecl”);
if (!VD)
return;

clang::SourceLocation Loc{VD->getLocStart()};
if (VD->isImplicit() || !Loc.isValid() ||
utils::isPresumedLocInHeaderFile(Loc, *Result.SourceManager,
HeaderFileExtensions))
return;
clang::SourceRange Range{VD->getSourceRange()};
clang::QualType QT = VD->getType();

const clang::Type *UT = QT.getTypePtr();
if (!UT)
return;

if (UT->isBuiltinType())
return;

std::cerr << " ** QT.getAsString() = " << QT.getAsString() << “\n”;
std::cerr << " ** QT.getCanonicalType().getAsString() = " << QT.getCanonicalType().getAsString() << “\n”;
std::cerr << " ** QT.getUnqualifiedType().getAsString() = " << QT.getUnqualifiedType().getAsString() << “\n”;

clang::QualType ds = UT->getLocallyUnqualifiedSingleStepDesugaredType();

std::cerr << " ** ds.getAsString() = " << ds.getAsString() << “\n”;

const clang::IdentifierInfo *idinfo = QT.getBaseTypeIdentifier();
if (idinfo)
std::cerr << " ** QT.getBaseTypeIdentifier() = " << idinfo->getName().str()
<< “\n”;

clang::SourceRange RangeForString{Range};
CharSourceRange CSR = Lexer::makeFileCharRange(
CharSourceRange::getTokenRange(RangeForString), *Result.SourceManager,
Result.Context->getLangOpts());
std::string possibleSemi = Lexer::getSourceText(CSR, *Result.SourceManager,
Result.Context->getLangOpts())
.str();
std::cerr << " ** VarDecl: " << possibleSemi << “\n”;
}

“Tim Halloran via cfe-dev” cfe-dev@lists.llvm.org wrote in message news:CAFdkBy6St8R7p1cw0cUk_NCmJaq=+x719KuAk81cCgNTw0q49Q@mail.gmail.com

I’m trying to refactor in C++:

using namespace std;
string sp = " ";

into

std::string sp = " ";

However when I examine the VarDecl node it is not obvious how to get to the namespace the “typedef sting” is declared in.

This worked for me:

auto ty = varDecl->getType().getTypePtr();
if (ty->getTypeClass() == clang::Type::TypeClass::Typedef)
{
auto tdty = ty->getAsclang::TypedefType();
std::cout << tdty->getDecl()->getQualifiedNameAsString() << " " << varDecl->getNameAsString();
}

HTH,
Boris