And*_*Geo 3 c++ clang llvm-clang
我正在尝试确定ASTvisitor中的变量声明是否为数组,如果为数组,则要确定数组的维数。在下面可以找到我的代码。
bool VisitVarDecl(VarDecl *var)
{
if (astContext->getSourceManager().isInMainFile(var->getLocStart())) //checks if the node is in the main = input file.
{
FullSourceLoc FullLocation = astContext->getFullLoc(var->getLocStart());
if((var->hasLocalStorage() || var->isStaticLocal ()))
{
if (!var->isDefinedOutsideFunctionOrMethod())
{
if(avoid == 0)
{
numVariables++;
string varName = var->getQualifiedNameAsString();
string varType = var->getType().getAsString();
const Type *type = var->getType().getTypePtr();
if(type->isConstantArrayType())
{
const ArrayType *Array = type->castAsArrayTypeUnsafe();
cout << "Is array of type: " << Array->getElementType().getAsString() << endl;
}
REPORT << "[" << FullLocation.getSpellingLineNumber() << "," << FullLocation.getSpellingColumnNumber() << "]Variable Declaration: " << varName << " of type " << varType << "\n";
APIs << varType << ";";
}
else
{
avoid--;
REPORT << "Avoid is: " << avoid << endl;
}
}
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我不知道我是否正确地从VarDecl进行了“广播”到ArrayType。如果您有更好,更安全且不那么草率的方法,请公开征求意见。此外,我现在的主要问题是如何获取数组的维数,甚至以单元为单位的大小。
谢谢你们。
尝试这个:
bool VisitVarDecl(VarDecl *D){
if (auto t = dyn_cast_or_null<ConstantArrayType>(D->getType().getTypePtr())) {
t->getSize().dump(); // We got the array size as an APInt here
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
最后,这是“一种更好,更安全,更草率的方式”:
isa广播和dyn广播模板