Get template parameters from CXXConstructExpr in Clang AST
Let's say I have a variable declaration:
std::vector<MyType> myVector(1);
This is represented as CXXConstructExpr
in the Clang AST. I have a helper that finds this CXXConstructExpr
, but I would like to extract the expression for MyType
.
I've tried all sorts of things, but nothing seems to work:
const CXXConstructExpr* construct = Result.Nodes.getNodeAs<CXXConstructExpr>("expr");
construct->getConstructor()->getTemplateSpecializationArgs() // Always nullptr
construct->getConstructor()->getParent() // Seems to lose the template parameters
construct->getConstructor()->getDescribedTemplate() // Always nullptr
source to share
Here's the socket:
varDecl(
has(
cxxConstructExpr()
)
,hasType(
classTemplateSpecializationDecl().bind(sp_dcl_bd_name_)
)
).bind(var_bd_name_);
It starts with VarDecl and goes down to a type that ClassTemplateSpecializationDecl
looks like a vector ClassTemplateDecl
. In the callback, you can work from ClassTemplateSpecializationDecl
within the template argument list and work with individual template arguments:
using CTSD = ClassTemplateSpecializationDecl;
CTSD * spec_decl =
const_cast<CTSD *>(result.Nodes.getNodeAs<CTSD>(sp_dcl_bd_name_));
VarDecl * var_decl =
const_cast<VarDecl *>(result.Nodes.getNodeAs<VarDecl>(var_bd_name_));
if(spec_decl && var_decl) {
// get the template args
TemplateArgumentList const &tal(spec_decl->getTemplateArgs());
for(unsigned i = 0; i < tal.size(); ++i){
TemplateArgument const &ta(tal[i]);
// is this arg a type arg? If so, get that type
TemplateArgument::ArgKind k(ta.getKind());
std::string argName = "";
if(k==TemplateArgument::ArgKind::Type){
QualType t = ta.getAsType();
argName = t.getAsString();
}
// Could do similar actions for integral args, etc...
std::cout << "For variable declared at "
<< corct::sourceRangeAsString(var_decl->getSourceRange(),&sm) << ":"
<< spec_decl->getNameAsString()
<< ": template arg " << (i+1) << ": " << argName << std::endl;
} // for template args
} // if
For this code:
struct B{int b_;};
std::vector<B> vb(1);
this gives:
For variable declared at <line:14:1, col:20>:vector: template arg 1: struct B
For variable declared at <col:1, col:20>:vector: template arg 2: class std::__1::allocator<struct B>
For a complete example, see the Code Analysis and Refactoring with Clang Tools repo examples at github: https://github.com/lanl/CoARCT (see apps / TemplateType.cc)
source to share